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