67d5d5153e22c0a932649dd85043a8a4ddccd85d
[ccsdk/cds.git] /
1 /*
2  *  Copyright © 2019 IBM.
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package org.onap.ccsdk.cds.blueprintsprocessor.ssh.service
18
19 import org.apache.sshd.client.SshClient
20 import org.apache.sshd.client.channel.ChannelExec
21 import org.apache.sshd.client.channel.ClientChannel
22 import org.apache.sshd.client.channel.ClientChannelEvent
23 import org.apache.sshd.client.keyverifier.AcceptAllServerKeyVerifier
24 import org.apache.sshd.client.session.ClientSession
25 import org.onap.ccsdk.cds.blueprintsprocessor.ssh.BasicAuthSshClientProperties
26 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
27 import org.slf4j.LoggerFactory
28 import java.io.ByteArrayOutputStream
29 import java.util.*
30
31
32 open class BasicAuthSshClientService(private val basicAuthSshClientProperties: BasicAuthSshClientProperties)
33     : BlueprintSshClientService {
34
35     private val log = LoggerFactory.getLogger(BasicAuthSshClientService::class.java)!!
36
37     private lateinit var sshClient: SshClient
38     private lateinit var clientSession: ClientSession
39
40     override suspend fun startSessionNB(): ClientSession {
41         sshClient = SshClient.setUpDefaultClient()
42         sshClient.serverKeyVerifier = AcceptAllServerKeyVerifier.INSTANCE
43         sshClient.start()
44         log.debug("SSH Client Service started successfully")
45         clientSession = sshClient.connect(basicAuthSshClientProperties.username, basicAuthSshClientProperties.host,
46                 basicAuthSshClientProperties.port)
47                 .verify(basicAuthSshClientProperties.connectionTimeOut)
48                 .session
49
50         clientSession.addPasswordIdentity(basicAuthSshClientProperties.password)
51         clientSession.auth().verify(basicAuthSshClientProperties.connectionTimeOut)
52         log.info("SSH client session($clientSession) created")
53         return clientSession
54     }
55
56     override suspend fun executeCommandsNB(commands: List<String>, timeOut: Long): String {
57         val buffer = StringBuffer()
58         try {
59             commands.forEach { command ->
60                 buffer.append("\nCommand : $command")
61                 buffer.append("\n" + executeCommandNB(command, timeOut))
62             }
63         } catch (e: Exception) {
64             throw BluePrintProcessorException("Failed to execute commands, below the output : $buffer")
65         }
66         return buffer.toString()
67     }
68
69     override suspend fun executeCommandNB(command: String, timeOut: Long): String {
70         log.debug("Executing host($clientSession) command($command)")
71
72         var channel: ChannelExec? = null
73         try {
74             channel = clientSession.createExecChannel(command)
75             //TODO("Convert to streaming ")
76             val outputStream = ByteArrayOutputStream()
77             channel.out = outputStream
78             channel.err = outputStream
79             channel.open().await()
80             val waitMask = channel.waitFor(Collections.unmodifiableSet(EnumSet.of(ClientChannelEvent.CLOSED)), timeOut)
81             if (waitMask.contains(ClientChannelEvent.TIMEOUT)) {
82                 throw BluePrintProcessorException("Failed to retrieve command result in time: $command")
83             }
84             val exitStatus = channel.exitStatus
85             ClientChannel.validateCommandExitStatusCode(command, exitStatus!!)
86             return outputStream.toString()
87         } finally {
88             if (channel != null)
89                 channel.close()
90         }
91     }
92
93     override suspend fun closeSessionNB() {
94         if (sshClient.isStarted) {
95             sshClient.stop()
96             log.debug("SSH Client Service stopped successfully")
97         }
98     }
99 }