Fix thread safety issues in netconf client
[controller.git] / opendaylight / netconf / netconf-client / src / main / java / org / opendaylight / controller / netconf / client / NetconfClient.java
1 /*
2  * Copyright (c) 2013 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.controller.netconf.client;
10
11 import io.netty.util.concurrent.Future;
12 import io.netty.util.concurrent.GlobalEventExecutor;
13
14 import java.io.Closeable;
15 import java.io.IOException;
16 import java.net.InetSocketAddress;
17 import java.util.Set;
18 import java.util.concurrent.CancellationException;
19 import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.TimeUnit;
21 import java.util.concurrent.TimeoutException;
22
23 import org.opendaylight.controller.netconf.api.NetconfMessage;
24 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
25 import org.opendaylight.protocol.framework.ReconnectStrategy;
26 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 import com.google.common.base.Preconditions;
31 import com.google.common.base.Stopwatch;
32 import com.google.common.collect.Sets;
33
34 public class NetconfClient implements Closeable {
35
36     private static final Logger logger = LoggerFactory.getLogger(NetconfClient.class);
37
38     public static final int DEFAULT_CONNECT_TIMEOUT = 5000;
39     private final NetconfClientDispatcher dispatch;
40     private final String label;
41     private final NetconfClientSession clientSession;
42     private final NetconfClientSessionListener sessionListener;
43     private final long sessionId;
44     private final InetSocketAddress address;
45
46     // TODO test reconnecting constructor
47     public NetconfClient(String clientLabelForLogging, InetSocketAddress address, int connectionAttempts,
48             int attemptMsTimeout, NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
49         this(clientLabelForLogging, address, getReconnectStrategy(connectionAttempts, attemptMsTimeout),
50                 netconfClientDispatcher);
51     }
52
53     private NetconfClient(String clientLabelForLogging, InetSocketAddress address, ReconnectStrategy strat, NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
54         this.label = clientLabelForLogging;
55         dispatch = netconfClientDispatcher;
56         sessionListener = new NetconfClientSessionListener();
57         Future<NetconfClientSession> clientFuture = dispatch.createClient(address, sessionListener, strat);
58         this.address = address;
59         clientSession = get(clientFuture);
60         this.sessionId = clientSession.getSessionId();
61     }
62
63     private NetconfClientSession get(Future<NetconfClientSession> clientFuture) throws InterruptedException {
64         try {
65             return clientFuture.get();
66         } catch (CancellationException e) {
67             throw new RuntimeException("Cancelling " + this, e);
68         } catch (ExecutionException e) {
69             throw new IllegalStateException("Unable to create " + this, e);
70         }
71     }
72
73     public static NetconfClient clientFor(String clientLabelForLogging, InetSocketAddress address, ReconnectStrategy strategy, NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
74         return new NetconfClient(clientLabelForLogging,address,strategy,netconfClientDispatcher);
75     }
76
77     public static NetconfClient clientFor(String clientLabelForLogging, InetSocketAddress address, ReconnectStrategy strategy, NetconfClientDispatcher netconfClientDispatcher,NetconfClientSessionListener listener) throws InterruptedException {
78         return new NetconfClient(clientLabelForLogging,address,strategy,netconfClientDispatcher,listener);
79     }
80
81     public NetconfClient(String clientLabelForLogging, InetSocketAddress address, int connectTimeoutMs,
82             NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
83         this(clientLabelForLogging, address,
84                 new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, connectTimeoutMs), netconfClientDispatcher);
85     }
86
87     public NetconfClient(String clientLabelForLogging, InetSocketAddress address,
88             NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
89         this(clientLabelForLogging, address, new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE,
90                 DEFAULT_CONNECT_TIMEOUT), netconfClientDispatcher);
91     }
92
93     public NetconfClient(String clientLabelForLogging, InetSocketAddress address, ReconnectStrategy strategy,
94             NetconfClientDispatcher netconfClientDispatcher, NetconfClientSessionListener listener) throws InterruptedException{
95         this.label = clientLabelForLogging;
96         dispatch = netconfClientDispatcher;
97         sessionListener = listener;
98         Future<NetconfClientSession> clientFuture = dispatch.createClient(address, sessionListener, strategy);
99         this.address = address;
100         clientSession = get(clientFuture);
101         this.sessionId = clientSession.getSessionId();
102     }
103
104     public Future<NetconfMessage> sendRequest(NetconfMessage message) {
105         return sessionListener.sendRequest(message);
106     }
107
108     /**
109      * @deprecated Use {@link sendRequest} instead
110      */
111     @Deprecated
112     public NetconfMessage sendMessage(NetconfMessage message) throws ExecutionException, InterruptedException, TimeoutException {
113         return sendMessage(message, 5, 1000);
114     }
115
116     /**
117      * @deprecated Use {@link sendRequest} instead
118      */
119     @Deprecated
120     public NetconfMessage sendMessage(NetconfMessage message, int attempts, int attemptMsDelay) throws ExecutionException, InterruptedException, TimeoutException {
121         //logger.debug("Sending message: {}",XmlUtil.toString(message.getDocument()));
122         final Stopwatch stopwatch = new Stopwatch().start();
123
124         try {
125             return sessionListener.sendRequest(message).get(attempts * attemptMsDelay, TimeUnit.MILLISECONDS);
126         } finally {
127             stopwatch.stop();
128             logger.debug("Total time spent waiting for response from {}: {} ms", address, stopwatch.elapsed(TimeUnit.MILLISECONDS));
129         }
130     }
131
132     @Override
133     public void close() throws IOException {
134         clientSession.close();
135     }
136
137     public NetconfClientDispatcher getNetconfClientDispatcher() {
138         return dispatch;
139     }
140
141     private static ReconnectStrategy getReconnectStrategy(int connectionAttempts, int attemptMsTimeout) {
142         return new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, attemptMsTimeout, 1000, 1.0, null,
143                 Long.valueOf(connectionAttempts), null);
144     }
145
146     @Override
147     public String toString() {
148         final StringBuffer sb = new StringBuffer("NetconfClient{");
149         sb.append("label=").append(label);
150         sb.append(", sessionId=").append(sessionId);
151         sb.append('}');
152         return sb.toString();
153     }
154
155     public long getSessionId() {
156         return sessionId;
157     }
158
159     public Set<String> getCapabilities() {
160         Preconditions.checkState(clientSession != null, "Client was not initialized successfully");
161         return Sets.newHashSet(clientSession.getServerCapabilities());
162     }
163
164     public NetconfClientSession getClientSession() {
165         return clientSession;
166     }
167 }