1b59e883989c8b6d3c21e2c3529e194b9741bbe1
[netconf.git] / netconf / netconf-topology-singleton / src / main / java / org / opendaylight / netconf / topology / singleton / impl / utils / NetconfTopologyUtils.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.netconf.topology.singleton.impl.utils;
10
11 import com.google.common.base.Strings;
12 import java.io.File;
13 import java.math.BigDecimal;
14 import java.net.InetSocketAddress;
15 import java.util.HashMap;
16 import java.util.Map;
17 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
18 import org.opendaylight.netconf.sal.connect.netconf.NetconfStateSchemasResolverImpl;
19 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
20 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
22 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
23 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
24 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
25 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
26 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
27 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
28 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
29 import org.opendaylight.yangtools.yang.binding.Identifier;
30 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
31 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
32 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
33 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
34 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
35 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
36 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
37 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
38 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
39 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public class NetconfTopologyUtils {
44     private static Logger LOG = LoggerFactory.getLogger(NetconfTopologyUtils.class);
45
46     private static final String DEFAULT_SCHEMA_REPOSITORY_NAME = "sal-netconf-connector";
47
48     public static final long DEFAULT_REQUEST_TIMEOUT_MILLIS = 60000L;
49     public static final int DEFAULT_KEEPALIVE_DELAY = 0;
50     public static final boolean DEFAULT_RECONNECT_ON_CHANGED_SCHEMA = false;
51     public static final int DEFAULT_CONCURRENT_RPC_LIMIT = 0;
52     public static final int DEFAULT_MAX_CONNECTION_ATTEMPTS = 0;
53     public static final int DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS = 2000;
54     public static final long DEFAULT_CONNECTION_TIMEOUT_MILLIS = 20000L;
55     public static final BigDecimal DEFAULT_SLEEP_FACTOR = new BigDecimal(1.5);
56
57
58     // The default cache directory relative to <code>CACHE_DIRECTORY</code>
59
60     public static final String DEFAULT_CACHE_DIRECTORY = "schema";
61
62     // Filesystem based caches are stored relative to the cache directory.
63     public static final String CACHE_DIRECTORY = "cache";
64
65     // The qualified schema cache directory <code>cache/schema</code>
66     public static final String QUALIFIED_DEFAULT_CACHE_DIRECTORY =
67             CACHE_DIRECTORY + File.separator + DEFAULT_CACHE_DIRECTORY;
68
69     // The default schema repository in the case that one is not specified.
70     public static final SharedSchemaRepository DEFAULT_SCHEMA_REPOSITORY =
71             new SharedSchemaRepository(DEFAULT_SCHEMA_REPOSITORY_NAME);
72
73
74      // The default <code>FilesystemSchemaSourceCache</code>, which stores cached files in <code>cache/schema</code>.
75     public static final FilesystemSchemaSourceCache<YangTextSchemaSource> DEFAULT_CACHE =
76             new FilesystemSchemaSourceCache<>(DEFAULT_SCHEMA_REPOSITORY, YangTextSchemaSource.class,
77                     new File(QUALIFIED_DEFAULT_CACHE_DIRECTORY));
78
79     // The default factory for creating <code>SchemaContext</code> instances.
80     public static final SchemaContextFactory DEFAULT_SCHEMA_CONTEXT_FACTORY =
81             DEFAULT_SCHEMA_REPOSITORY.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
82
83     /**
84      * Keeps track of initialized Schema resources.  A Map is maintained in which the key represents the name
85      * of the schema cache directory, and the value is a corresponding <code>SchemaResourcesDTO</code>.  The
86      * <code>SchemaResourcesDTO</code> is essentially a container that allows for the extraction of the
87      * <code>SchemaRegistry</code> and <code>SchemaContextFactory</code> which should be used for a particular
88      * Netconf mount.  Access to <code>schemaResourcesDTOs</code> should be surrounded by appropriate
89      * synchronization locks.
90      */
91     private static final Map<String, NetconfDevice.SchemaResourcesDTO> schemaResourcesDTOs = new HashMap<>();
92
93     // Initializes default constant instances for the case when the default schema repository
94     // directory cache/schema is used.
95     static {
96         schemaResourcesDTOs.put(DEFAULT_CACHE_DIRECTORY,
97                 new NetconfDevice.SchemaResourcesDTO(DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY,
98                         DEFAULT_SCHEMA_CONTEXT_FACTORY, new NetconfStateSchemasResolverImpl()));
99         DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(DEFAULT_CACHE);
100         DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(
101                 TextToASTTransformer.create(DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY));
102     }
103
104     public static NetconfDevice.SchemaResourcesDTO setupSchemaCacheDTO(final Node node) {
105         final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
106         final String moduleSchemaCacheDirectory = netconfNode.getSchemaCacheDirectory();
107         final RemoteDeviceId deviceId = createRemoteDeviceId(node.getNodeId(), netconfNode);
108
109         // Setup information related to the SchemaRegistry, SchemaResourceFactory, etc.
110         NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = null;
111         // Only checks to ensure the String is not empty or null;  further checks related to directory accessibility
112         // and file permissions are handled during the FilesystemSchemaSourceCache initialization.
113         if (!Strings.isNullOrEmpty(moduleSchemaCacheDirectory)) {
114             // If a custom schema cache directory is specified, create the backing DTO; otherwise, the SchemaRegistry
115             // and SchemaContextFactory remain the default values.
116             if (!moduleSchemaCacheDirectory.equals(DEFAULT_CACHE_DIRECTORY)) {
117                 // Multiple modules may be created at once;  synchronize to avoid issues with data consistency among
118                 // threads.
119                 synchronized (schemaResourcesDTOs) {
120                     // Look for the cached DTO to reuse SchemaRegistry and SchemaContextFactory variables if
121                     // they already exist
122                     schemaResourcesDTO = schemaResourcesDTOs.get(moduleSchemaCacheDirectory);
123                     if (schemaResourcesDTO == null) {
124                         schemaResourcesDTO = createSchemaResourcesDTO(moduleSchemaCacheDirectory);
125                         schemaResourcesDTO.getSchemaRegistry().registerSchemaSourceListener(
126                                 TextToASTTransformer.create((SchemaRepository) schemaResourcesDTO.getSchemaRegistry(),
127                                         schemaResourcesDTO.getSchemaRegistry())
128                         );
129                         schemaResourcesDTOs.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
130                     }
131                 }
132                 LOG.info("{} : netconf connector will use schema cache directory {} instead of {}",
133                         deviceId, moduleSchemaCacheDirectory, DEFAULT_CACHE_DIRECTORY);
134             }
135         }
136
137         if (schemaResourcesDTO == null) {
138             synchronized (schemaResourcesDTOs) {
139                 schemaResourcesDTO = schemaResourcesDTOs.get(DEFAULT_CACHE_DIRECTORY);
140             }
141             LOG.info("{} : using the default directory {}",
142                     deviceId, QUALIFIED_DEFAULT_CACHE_DIRECTORY);
143         }
144
145         return schemaResourcesDTO;
146     }
147
148     /**
149      * Creates the backing Schema classes for a particular directory.
150      *
151      * @param moduleSchemaCacheDirectory The string directory relative to "cache"
152      * @return A DTO containing the Schema classes for the Netconf mount.
153      */
154     private static NetconfDevice.SchemaResourcesDTO createSchemaResourcesDTO(final String moduleSchemaCacheDirectory) {
155         final SharedSchemaRepository repository = new SharedSchemaRepository(moduleSchemaCacheDirectory);
156         final SchemaContextFactory schemaContextFactory
157                 = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
158
159         final FilesystemSchemaSourceCache<YangTextSchemaSource> deviceCache =
160                 createDeviceFilesystemCache(moduleSchemaCacheDirectory, repository);
161         repository.registerSchemaSourceListener(deviceCache);
162         return new NetconfDevice.SchemaResourcesDTO(repository, repository, schemaContextFactory,
163                 new NetconfStateSchemasResolverImpl());
164     }
165
166     /**
167      * Creates a <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory.
168      *
169      * @param schemaCacheDirectory The custom cache directory relative to "cache"
170      * @return A <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory
171      */
172     private static FilesystemSchemaSourceCache<YangTextSchemaSource> createDeviceFilesystemCache(
173             final String schemaCacheDirectory, final SchemaSourceRegistry schemaRegistry) {
174         final String relativeSchemaCacheDirectory =
175                 NetconfTopologyUtils.CACHE_DIRECTORY + File.separator + schemaCacheDirectory;
176         return new FilesystemSchemaSourceCache<>(schemaRegistry, YangTextSchemaSource.class,
177                 new File(relativeSchemaCacheDirectory));
178     }
179
180
181     public static RemoteDeviceId createRemoteDeviceId(final NodeId nodeId, final NetconfNode node) {
182         final IpAddress ipAddress = node.getHost().getIpAddress();
183         final InetSocketAddress address = new InetSocketAddress(ipAddress.getIpv4Address() != null
184                 ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue(),
185                 node.getPort().getValue());
186         return new RemoteDeviceId(nodeId.getValue(), address);
187     }
188
189     public static String createActorPath(final String masterMember, final String name) {
190         return  masterMember + "/user/" + name;
191     }
192
193     public static String createMasterActorName(final String name, final String masterAddress) {
194         return masterAddress.replaceAll("//", "") + "_" + name;
195     }
196
197     public static NodeId getNodeId(final InstanceIdentifier.PathArgument pathArgument) {
198         if (pathArgument instanceof InstanceIdentifier.IdentifiableItem<?, ?>) {
199
200             final Identifier key = ((InstanceIdentifier.IdentifiableItem) pathArgument).getKey();
201             if (key instanceof NodeKey) {
202                 return ((NodeKey) key).getNodeId();
203             }
204         }
205         throw new IllegalStateException("Unable to create NodeId from: " + pathArgument);
206     }
207
208     public static KeyedInstanceIdentifier<Topology, TopologyKey> createTopologyListPath(final String topologyId) {
209         final InstanceIdentifier<NetworkTopology> networkTopology = InstanceIdentifier.create(NetworkTopology.class);
210         return networkTopology.child(Topology.class, new TopologyKey(new TopologyId(topologyId)));
211     }
212
213     public static InstanceIdentifier<Node> createTopologyNodeListPath(final NodeKey key, final String topologyId) {
214         return createTopologyListPath(topologyId)
215                 .child(Node.class, new NodeKey(new NodeId(key.getNodeId().getValue())));
216     }
217
218     public static InstanceIdentifier<Node> createTopologyNodePath(final String topologyId) {
219         return createTopologyListPath(topologyId).child(Node.class);
220     }
221 }