2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.onap.ccsdk.sli.adaptors.saltstack.impl;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import org.apache.commons.io.IOUtils;
30 import org.apache.commons.lang.RandomStringUtils;
31 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResult;
32 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResultCodes;
35 import java.io.FileInputStream;
36 import java.io.FileNotFoundException;
37 import java.io.FileOutputStream;
38 import java.io.IOException;
39 import java.io.OutputStream;
40 import java.io.StringWriter;
43 * Returns a custom SSH client
45 * - can create one with ssl using an X509 certificate that does NOT have a known CA
46 * - create one which trusts ALL SSL certificates
47 * - return default sshclient (which only trusts known CAs from default cacerts file for process) this is the default
50 //TODO: This class is to be altered completely based on the SALTSTACK server communication.
51 public class ConnectionBuilder {
53 private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConnectionBuilder.class);
54 SshConnection sshConnection;
57 * Constructor that initializes an ssh client based on username and password
59 public ConnectionBuilder(String host, String port, String userName, String userPasswd) {
60 sshConnection = new SshConnection(host, Integer.parseInt(port), userName, userPasswd);
64 * Constructor that initializes an ssh client based on ssh certificate
66 public ConnectionBuilder(String host, String port, String certFile) {
67 sshConnection = new SshConnection(host, Integer.parseInt(port), certFile);
71 * Constructor that initializes an ssh client based on ssh username password and certificate
73 public ConnectionBuilder(String host, String port, String userName, String userPasswd,
76 sshConnection = new SshConnection(host, Integer.parseInt(port), userName, userPasswd, certFile);
80 * 1. Connect to SSH server.
81 * 2. Exec remote command over SSH. Return command execution status.
82 * Command output is written to out or err stream.
84 * @param cmd Commands to execute
85 * @return command execution status
87 public SaltstackResult connectNExecute(String cmd) {
88 return connectNExecute(cmd, -1, -1);
92 * 1. Connect to SSH server with retry enabled.
93 * 2. Exec remote command over SSH. Return command execution status.
94 * Command output is written to out or err stream.
96 * @param cmd Commands to execute
97 * @param retryDelay delay between retry to make a SSH connection.
98 * @param retryCount number of count retry to make a SSH connection.
99 * @return command execution status
101 public SaltstackResult connectNExecute(String cmd, int retryCount, int retryDelay) {
103 SaltstackResult result = new SaltstackResult();
105 if (retryCount != -1) {
106 result = sshConnection.connectWithRetry(retryCount, retryDelay);
108 result = sshConnection.connect();
110 if (result.getStatusCode() != SaltstackResultCodes.SUCCESS.getValue()) {
113 String outFilePath = "/tmp/" + RandomStringUtils.random(5, true, true);
114 String errFilePath = "/tmp/" + RandomStringUtils.random(5, true, true);
115 OutputStream out = new FileOutputStream(outFilePath);
116 OutputStream errs = new FileOutputStream(errFilePath);
117 result = sshConnection.execCommand(cmd, out, errs);
118 sshConnection.disconnect();
121 if (result.getSshExitStatus() != 0) {
122 return sortExitStatus(result.getSshExitStatus(), errFilePath, cmd);
124 if (result.getStatusCode() != SaltstackResultCodes.SUCCESS.getValue()) {
127 result.setStatusMessage("Success");
128 result.setOutputFileName(outFilePath);
129 } catch (Exception io) {
130 logger.error("Caught Exception", io);
131 result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
132 result.setStatusMessage(io.getMessage());
137 public SaltstackResult sortExitStatus(int exitStatus, String errFilePath, String cmd) {
138 SaltstackResult result = new SaltstackResult();
140 StringWriter writer = new StringWriter();
142 IOUtils.copy(new FileInputStream(new File(errFilePath)), writer, "UTF-8");
143 err = writer.toString();
144 } catch (FileNotFoundException e){
145 logger.info("Error stream file doesn't exist");
146 } catch (IOException e){
147 logger.info("Error stream file doesn't exist");
149 if (exitStatus == 255 || exitStatus == 1) {
150 String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
151 + "]. Exit Code " + exitStatus + " and Error message : " +
152 "Malformed configuration. " + err;
153 logger.error(errMessage);
154 result.setStatusCode(SaltstackResultCodes.INVALID_COMMAND.getValue());
155 result.setStatusMessage(errMessage);
156 } else if (exitStatus == 5 || exitStatus == 65) {
157 String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
158 + "]. Exit Code " + exitStatus + " and Error message : " +
159 "Host not allowed to connect. " + err;
160 logger.error(errMessage);
161 result.setStatusCode(SaltstackResultCodes.USER_UNAUTHORIZED.getValue());
162 result.setStatusMessage(errMessage);
163 } else if (exitStatus == 67 || exitStatus == 73) {
164 String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
165 + "]. Exit Code " + exitStatus + " and Error message : " +
166 "Key exchange failed. " + err;
167 logger.error(errMessage);
168 result.setStatusCode(SaltstackResultCodes.CERTIFICATE_ERROR.getValue());
169 result.setStatusMessage(errMessage);
171 String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
172 + "]. Exit Code " + exitStatus + " and Error message : " + err;
173 logger.error(errMessage);
174 result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
175 result.setStatusMessage(errMessage);
181 * 1. Connect to SSH server.
182 * 2. Exec remote command over SSH. Return command execution status.
183 * Command output is written to out or err stream.
185 * @param commands list of commands to execute
186 * @param payloadSLS has the SLS file location that is to be sent to server
187 * @param retryDelay delay between retry to make a SSH connection.
188 * @param retryCount number of count retry to make a SSH connection.
189 * @return command execution status
191 public SaltstackResult connectNExecuteSLS(String commands, String payloadSLS, int retryDelay, int retryCount) {
193 SaltstackResult result = new SaltstackResult();
195 //TODO: to implement SSH connected client to Saltstack Server
196 } catch (Exception io) {
197 logger.error("Caught Exception", io);
198 result.setStatusCode(SaltstackResultCodes.IO_EXCEPTION.getValue());
199 result.setStatusMessage(io.getMessage());
205 * Disconnect from SSH server.
207 public SaltstackResult disConnect() {
209 SaltstackResult result = new SaltstackResult();
211 //TODO: to implement SSH connected client to Saltstack Server
212 } catch (Exception io) {
213 logger.error("Caught Exception", io);
214 result.setStatusCode(SaltstackResultCodes.IO_EXCEPTION.getValue());
215 result.setStatusMessage(io.getMessage());
221 * Exec remote command over SSH. Return command execution status.
222 * Command output is written to out or err stream.
224 * @param cmd command to execute
225 * @return command execution status
227 public SaltstackResult connectNExecuteLog(String cmd) {
229 SaltstackResult result = new SaltstackResult();
232 //TODO: to implement SSH command execute
233 } catch (Exception io) {
234 result.setStatusCode(SaltstackResultCodes.IO_EXCEPTION.getValue());
235 result.setStatusMessage(io.getMessage());
236 logger.error("Caught IOException", io);