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