2 * Copyright © 2017-2019 AT&T, Bell Canada
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.core
19 import com.google.common.collect.ImmutableList
20 import com.google.common.collect.ImmutableSet
21 import org.apache.sshd.client.SshClient
22 import org.apache.sshd.client.channel.ClientChannel
23 import org.apache.sshd.client.session.ClientSession
24 import org.apache.sshd.common.FactoryManager
25 import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.*
26 import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.NetconfMessageUtils
27 import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.RpcMessageUtils
28 import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.RpcStatus
29 import org.slf4j.LoggerFactory
30 import java.io.IOException
32 import java.util.concurrent.*
34 class NetconfSessionImpl(private val deviceInfo: DeviceInfo, private val rpcService: NetconfRpcService) :
37 private val log = LoggerFactory.getLogger(NetconfSessionImpl::class.java)
39 private val errorReplies: MutableList<String> = Collections.synchronizedList(mutableListOf())
40 private val replies: MutableMap<String, CompletableFuture<String>> = ConcurrentHashMap()
41 private val deviceCapabilities = mutableSetOf<String>()
43 private var connectionTimeout: Long = 0
44 private var replyTimeout: Int = 0
45 private var idleTimeout: Int = 0
46 private var sessionId: String? = null
48 private lateinit var session: ClientSession
49 private lateinit var client: SshClient
50 private lateinit var channel: ClientChannel
51 private lateinit var streamHandler: NetconfDeviceCommunicator
53 private var capabilities =
54 ImmutableList.of(RpcMessageUtils.NETCONF_10_CAPABILITY, RpcMessageUtils.NETCONF_11_CAPABILITY)
56 override fun connect() {
58 log.info("$deviceInfo: Connecting to Netconf Device with timeouts C:${deviceInfo.connectTimeout}, " +
59 "R:${deviceInfo.replyTimeout}, I:${deviceInfo.idleTimeout}")
61 log.info("$deviceInfo: Connected to Netconf Device")
62 } catch (e: NetconfException) {
63 log.error("$deviceInfo: Netconf Device Connection Failed. ${e.message}")
64 throw NetconfException(e)
68 override fun disconnect() {
69 if (rpcService.closeSession(false).status.equals(
70 RpcStatus.FAILURE, true)) {
71 rpcService.closeSession(true)
75 } catch (ioe: IOException) {
76 log.warn("$deviceInfo: Error closing session($sessionId) for host($deviceInfo)", ioe)
80 override fun reconnect() {
85 override fun syncRpc(request: String, messageId: String): String {
86 val formattedRequest = NetconfMessageUtils.formatRPCRequest(request, messageId, deviceCapabilities)
91 return streamHandler.getFutureFromSendMessage(streamHandler.sendMessage(formattedRequest, messageId),
92 replyTimeout.toLong(), TimeUnit.SECONDS)
93 } catch (e: InterruptedException) {
94 throw NetconfException("$deviceInfo: Interrupted while waiting for reply for request: $formattedRequest", e)
95 } catch (e: TimeoutException) {
96 throw NetconfException("$deviceInfo: Timed out while waiting for reply for request $formattedRequest after $replyTimeout sec.",
98 } catch (e: ExecutionException) {
99 log.warn("$deviceInfo: Closing session($sessionId) due to unexpected Error", e)
102 } catch (ioe: IOException) {
103 log.warn("$deviceInfo: Error closing session($sessionId) for host($deviceInfo)", ioe)
108 throw NetconfException("$deviceInfo: Closing session $sessionId for request $formattedRequest", e)
112 override fun asyncRpc(request: String, messageId: String): CompletableFuture<String> {
113 val formattedRequest = NetconfMessageUtils.formatRPCRequest(request, messageId, deviceCapabilities)
115 checkAndReestablish()
117 return streamHandler.sendMessage(formattedRequest, messageId).handleAsync { reply, t ->
119 throw NetconfException(messageId, t)
125 override fun checkAndReestablish() {
129 log.info("Trying to restart the whole SSH connection with {}", deviceInfo)
133 session.isClosed -> {
134 log.info("Trying to restart the session with {}", deviceInfo)
138 channel.isClosed -> {
139 log.info("Trying to reopen the channel with {}", deviceInfo)
145 } catch (e: IOException) {
146 log.error("Can't reopen connection for device {} error: {}", deviceInfo, e.message)
147 throw NetconfException(String.format("Cannot re-open the connection with device (%s)", deviceInfo), e)
148 } catch (e: IllegalStateException) {
149 log.error("Can't reopen connection for device {} error: {}", deviceInfo, e.message)
150 throw NetconfException(String.format("Cannot re-open the connection with device (%s)", deviceInfo), e)
154 override fun getDeviceInfo(): DeviceInfo {
158 override fun getSessionId(): String {
159 return this.sessionId!!
162 override fun getDeviceCapabilitiesSet(): Set<String> {
163 return Collections.unmodifiableSet(deviceCapabilities)
166 private fun startConnection() {
167 connectionTimeout = deviceInfo.connectTimeout
168 replyTimeout = deviceInfo.replyTimeout
169 idleTimeout = deviceInfo.idleTimeout
172 } catch (e: Exception) {
173 throw NetconfException("$deviceInfo: Failed to establish SSH session", e)
178 //Needed to unit test connect method interacting with client.start in startClient() below
179 private fun setupNewSSHClient() {
180 client = SshClient.setUpDefaultClient()
183 private fun startClient() {
186 client.properties.putIfAbsent(FactoryManager.IDLE_TIMEOUT, TimeUnit.SECONDS.toMillis(idleTimeout.toLong()))
187 client.properties.putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT, TimeUnit.SECONDS.toMillis(idleTimeout + 15L))
193 private fun startSession() {
194 log.info("$deviceInfo: Starting SSH session")
195 val connectFuture = client.connect(deviceInfo.username, deviceInfo.ipAddress, deviceInfo.port)
196 .verify(connectionTimeout, TimeUnit.SECONDS)
197 session = connectFuture.session
198 log.info("$deviceInfo: SSH session created")
203 private fun authSession() {
204 session.addPasswordIdentity(deviceInfo.password)
205 session.auth().verify(connectionTimeout, TimeUnit.SECONDS)
206 val event = session.waitFor(ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH,
207 ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.AUTHED), 0)
208 if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) {
209 throw NetconfException("$deviceInfo: Failed to authenticate session.")
211 log.info("$deviceInfo: SSH session authenticated")
216 private fun openChannel() {
217 channel = session.createSubsystemChannel("netconf")
218 val channelFuture = channel.open()
219 if (channelFuture.await(connectionTimeout, TimeUnit.SECONDS) && channelFuture.isOpened) {
220 log.info("$deviceInfo: SSH NETCONF subsystem channel opened")
223 throw NetconfException("$deviceInfo: Failed to open SSH subsystem channel")
227 private fun setupHandler() {
228 val sessionListener: NetconfSessionListener = NetconfSessionListenerImpl(this)
229 streamHandler = NetconfDeviceCommunicator(channel.invertedOut, channel.invertedIn, deviceInfo,
230 sessionListener, replies)
232 exchangeHelloMessage()
235 private fun exchangeHelloMessage() {
239 val serverHelloResponse = syncRpc(NetconfMessageUtils.createHelloString(capabilities), messageId)
240 val sessionIDMatcher = NetconfMessageUtils.SESSION_ID_REGEX_PATTERN.matcher(serverHelloResponse)
242 if (sessionIDMatcher.find()) {
243 sessionId = sessionIDMatcher.group(1)
245 throw NetconfException("$deviceInfo: Missing sessionId in server hello message: $serverHelloResponse")
248 val capabilityMatcher = NetconfMessageUtils.CAPABILITY_REGEX_PATTERN.matcher(serverHelloResponse)
249 while (capabilityMatcher.find()) { //TODO: refactor to add unit test easily for device capability accumulation.
250 deviceCapabilities.add(capabilityMatcher.group(1))
254 internal fun setStreamHandler(streamHandler: NetconfDeviceCommunicator) {
255 this.streamHandler = streamHandler
260 * Used by {@link NetconfSessionListenerImpl}
262 internal fun addDeviceErrorReply(errReply: String) {
263 errorReplies.add(errReply)
267 * Add a reply from the device
268 * Used by {@link NetconfSessionListenerImpl}
270 internal fun addDeviceReply(messageId: String, replyMsg: String) {
271 replies[messageId]?.complete(replyMsg)
275 * Closes the session/channel/client
277 @Throws(IOException::class)
278 private fun close() {
280 // Closes the socket which should interrupt the streamHandler
286 * Internal function for accessing replies for testing.
288 internal fun getReplies() = replies
291 * internal function for accessing errorReplies for testing.
293 internal fun getErrorReplies() = errorReplies
294 internal fun clearErrorReplies() = errorReplies.clear()
295 internal fun clearReplies() = replies.clear()
296 internal fun setClient(client: SshClient) { this.client = client }
297 internal fun setSession(session: ClientSession) { this.session = session }
298 internal fun setChannel(channel: ClientChannel) { this.channel = channel }