BUG-372: Rework sal-netconf-connector
[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 /**
35  * @deprecated Use {@link NetconfClientDispatcher.createClient()} or {@link NetconfClientDispatcher.createReconnectingClient()} instead.
36  */
37 @Deprecated
38 public class NetconfClient implements Closeable {
39
40     private static final Logger logger = LoggerFactory.getLogger(NetconfClient.class);
41
42     public static final int DEFAULT_CONNECT_TIMEOUT = 5000;
43     private final NetconfClientDispatcher dispatch;
44     private final String label;
45     private final NetconfClientSession clientSession;
46     private final NetconfClientSessionListener sessionListener;
47     private final long sessionId;
48     private final InetSocketAddress address;
49
50     // TODO test reconnecting constructor
51     public NetconfClient(String clientLabelForLogging, InetSocketAddress address, int connectionAttempts,
52             int attemptMsTimeout, NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
53         this(clientLabelForLogging, address, getReconnectStrategy(connectionAttempts, attemptMsTimeout),
54                 netconfClientDispatcher);
55     }
56
57     private NetconfClient(String clientLabelForLogging, InetSocketAddress address, ReconnectStrategy strat, NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
58         this.label = clientLabelForLogging;
59         dispatch = netconfClientDispatcher;
60         sessionListener = new SimpleNetconfClientSessionListener();
61         Future<NetconfClientSession> clientFuture = dispatch.createClient(address, sessionListener, strat);
62         this.address = address;
63         clientSession = get(clientFuture);
64         this.sessionId = clientSession.getSessionId();
65     }
66
67     private NetconfClientSession get(Future<NetconfClientSession> clientFuture) throws InterruptedException {
68         try {
69             return clientFuture.get();
70         } catch (CancellationException e) {
71             throw new RuntimeException("Cancelling " + this, e);
72         } catch (ExecutionException e) {
73             throw new IllegalStateException("Unable to create " + this, e);
74         }
75     }
76
77     public static NetconfClient clientFor(String clientLabelForLogging, InetSocketAddress address, ReconnectStrategy strategy, NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
78         return new NetconfClient(clientLabelForLogging,address,strategy,netconfClientDispatcher);
79     }
80
81     public static NetconfClient clientFor(String clientLabelForLogging, InetSocketAddress address,
82             ReconnectStrategy strategy, NetconfClientDispatcher netconfClientDispatcher, NetconfClientSessionListener listener) throws InterruptedException {
83         return new NetconfClient(clientLabelForLogging,address,strategy,netconfClientDispatcher,listener);
84     }
85
86     public NetconfClient(String clientLabelForLogging, InetSocketAddress address, int connectTimeoutMs,
87             NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
88         this(clientLabelForLogging, address,
89                 new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, connectTimeoutMs), netconfClientDispatcher);
90     }
91
92     public NetconfClient(String clientLabelForLogging, InetSocketAddress address,
93             NetconfClientDispatcher netconfClientDispatcher) throws InterruptedException {
94         this(clientLabelForLogging, address, new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE,
95                 DEFAULT_CONNECT_TIMEOUT), netconfClientDispatcher);
96     }
97
98     public NetconfClient(String clientLabelForLogging, InetSocketAddress address, ReconnectStrategy strategy,
99             NetconfClientDispatcher netconfClientDispatcher, NetconfClientSessionListener listener) throws InterruptedException{
100         this.label = clientLabelForLogging;
101         dispatch = netconfClientDispatcher;
102         sessionListener = listener;
103         Future<NetconfClientSession> clientFuture = dispatch.createClient(address, sessionListener, strategy);
104         this.address = address;
105         clientSession = get(clientFuture);
106         this.sessionId = clientSession.getSessionId();
107     }
108
109     public Future<NetconfMessage> sendRequest(NetconfMessage message) {
110         return ((SimpleNetconfClientSessionListener)sessionListener).sendRequest(message);
111     }
112
113     /**
114      * @deprecated Use {@link sendRequest} instead
115      */
116     @Deprecated
117     public NetconfMessage sendMessage(NetconfMessage message) throws ExecutionException, InterruptedException, TimeoutException {
118         return sendMessage(message, 5, 1000);
119     }
120
121     /**
122      * @deprecated Use {@link sendRequest} instead
123      */
124     @Deprecated
125     public NetconfMessage sendMessage(NetconfMessage message, int attempts, int attemptMsDelay) throws ExecutionException, InterruptedException, TimeoutException {
126         //logger.debug("Sending message: {}",XmlUtil.toString(message.getDocument()));
127         final Stopwatch stopwatch = new Stopwatch().start();
128
129         try {
130             return sendRequest(message).get(attempts * attemptMsDelay, TimeUnit.MILLISECONDS);
131         } finally {
132             stopwatch.stop();
133             logger.debug("Total time spent waiting for response from {}: {} ms", address, stopwatch.elapsed(TimeUnit.MILLISECONDS));
134         }
135     }
136
137     @Override
138     public void close() throws IOException {
139         clientSession.close();
140     }
141
142     public NetconfClientDispatcher getNetconfClientDispatcher() {
143         return dispatch;
144     }
145
146     private static ReconnectStrategy getReconnectStrategy(int connectionAttempts, int attemptMsTimeout) {
147         return new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, attemptMsTimeout, 1000, 1.0, null,
148                 Long.valueOf(connectionAttempts), null);
149     }
150
151     @Override
152     public String toString() {
153         final StringBuffer sb = new StringBuffer("NetconfClient{");
154         sb.append("label=").append(label);
155         sb.append(", sessionId=").append(sessionId);
156         sb.append('}');
157         return sb.toString();
158     }
159
160     public long getSessionId() {
161         return sessionId;
162     }
163
164     public Set<String> getCapabilities() {
165         Preconditions.checkState(clientSession != null, "Client was not initialized successfully");
166         return Sets.newHashSet(clientSession.getServerCapabilities());
167     }
168
169     public NetconfClientSession getClientSession() {
170         return clientSession;
171     }
172 }