Saltstack now aligned with APPC
[ccsdk/sli/adaptors.git] / saltstack-adapter / saltstack-adapter-provider / src / main / java / org / onap / ccsdk / sli / adaptors / saltstack / impl / ConnectionBuilder.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : CCSDK
4  * ================================================================================
5  * Copyright (C) 2018 Samsung Electronics. All rights reserved.
6  * ================================================================================
7  *
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
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
21  *
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.ccsdk.sli.adaptors.saltstack.impl;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import org.onap.appc.adapter.ssh.SshException;
30 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResult;
31 import org.onap.ccsdk.sli.adaptors.saltstack.model.SaltstackResultCodes;
32
33 import java.io.ByteArrayOutputStream;
34 import java.io.IOException;
35
36 //import org.onap.appc.adapter.ssh.SshConnection;
37 //import org.onap.appc.adapter.ssh.SshAdapter;
38
39 /**
40  * Returns a custom SSH client
41  * - based on options
42  * - can create one with ssl using an X509 certificate that does NOT have a known CA
43  * - create one which trusts ALL SSL certificates
44  * - return default sshclient (which only trusts known CAs from default cacerts file for process) this is the default
45  * option
46  **/
47 public class ConnectionBuilder {
48
49     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConnectionBuilder.class);
50     SshConnection sshConnection;
51
52     /**
53      * Constructor that initializes an ssh client based on username and password
54      **/
55     public ConnectionBuilder(String host, String port, String userName, String userPasswd) {
56         sshConnection = new SshConnection(host, Integer.parseInt(port), userName, userPasswd);
57     }
58
59     /**
60      * Constructor that initializes an ssh client based on ssh certificate
61      * This is still not supported in 1.3.0 version
62      **/
63     public ConnectionBuilder(String host, String port, String certFile) {
64         sshConnection = new SshConnection(host, Integer.parseInt(port), certFile);
65     }
66
67
68     /**
69      * 1. Connect to SSH server.
70      * 2. Exec remote command over SSH. Return command execution status.
71      * Command output is written to out or err stream.
72      *
73      * @param cmd Commands to execute
74      * @return command execution status
75      */
76     public SaltstackResult connectNExecute(String cmd, long execTimeout) throws IOException {
77         return connectNExecute(cmd, false, execTimeout);
78     }
79
80     /**
81      * 1. Connect to SSH server with retry enabled.
82      * 2. Exec remote command over SSH. Return command execution status.
83      * Command output is written to out or err stream.
84      *
85      * @param cmd       Commands to execute
86      * @param withRetry make a SSH connection with default retry.
87      * @return command execution status
88      */
89     public SaltstackResult connectNExecute(String cmd, boolean withRetry, long execTimeout)
90             throws IOException {
91
92         SaltstackResult result = new SaltstackResult();
93         ByteArrayOutputStream out = null;
94         ByteArrayOutputStream errs = null;
95         if (execTimeout >= 0) {
96             sshConnection.setExecTimeout(execTimeout);
97         }
98
99         try {
100             if (withRetry) {
101                 sshConnection.connectWithRetry();
102             } else {
103                 sshConnection.connect();
104             }
105             out = new ByteArrayOutputStream();
106             errs = new ByteArrayOutputStream();
107             int resultCode = sshConnection.execCommand(cmd, out, errs);
108             sshConnection.disconnect();
109             if (resultCode != 0) {
110                 return sortExitStatus(resultCode, errs.toString(), cmd);
111             }
112             result.setStatusCode(SaltstackResultCodes.SUCCESS.getValue());
113             result.setStatusMessage("Success");
114             result.setOutputMessage(out);
115         } catch (SshException io) {
116             if (io.toString().equalsIgnoreCase("Authentication failed")) {
117                 logger.error(io.toString());
118                 result.setStatusCode(SaltstackResultCodes.USER_UNAUTHORIZED.getValue());
119                 result.setStatusMessage(io.toString());
120                 return result;
121             }
122             logger.error("Caught Exception", io);
123             result.setStatusCode(SaltstackResultCodes.SSH_EXCEPTION.getValue());
124             result.setStatusMessage(io.getMessage());
125         } catch (Exception io) {
126             logger.error("Caught Exception", io);
127             result.setStatusCode(SaltstackResultCodes.SSH_EXCEPTION.getValue());
128             result.setStatusMessage(io.getMessage());
129         } finally {
130             if (out != null) {
131                 out.close();
132             }
133             if (errs != null) {
134                 errs.close();
135             }
136         }
137         return result;
138     }
139
140     public SaltstackResult sortExitStatus(int exitStatus, String errMess, String cmd) {
141         SaltstackResult result = new SaltstackResult();
142         if (exitStatus == 255 || exitStatus == 1) {
143             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
144                     + "]. Exit Code " + exitStatus + " and Error message : " +
145                     "Malformed configuration. " + errMess;
146             logger.error(errMessage);
147             result.setStatusCode(SaltstackResultCodes.INVALID_COMMAND.getValue());
148             result.setStatusMessage(errMessage);
149         } else if (exitStatus == 5 || exitStatus == 65) {
150             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
151                     + "]. Exit Code " + exitStatus + " and Error message : " +
152                     "Host not allowed to connect. " + errMess;
153             logger.error(errMessage);
154             result.setStatusCode(SaltstackResultCodes.USER_UNAUTHORIZED.getValue());
155             result.setStatusMessage(errMessage);
156         } else if (exitStatus == 67 || exitStatus == 73) {
157             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
158                     + "]. Exit Code " + exitStatus + " and Error message : " +
159                     "Key exchange failed. " + errMess;
160             logger.error(errMessage);
161             result.setStatusCode(SaltstackResultCodes.CERTIFICATE_ERROR.getValue());
162             result.setStatusMessage(errMessage);
163         } else {
164             String errMessage = "Error executing command [" + cmd + "] over SSH [" + sshConnection.toString()
165                     + "]. Exit Code " + exitStatus + " and Error message : " + errMess;
166             logger.error(errMessage);
167             result.setStatusCode(SaltstackResultCodes.UNKNOWN_EXCEPTION.getValue());
168             result.setStatusMessage(errMessage);
169         }
170         return result;
171     }
172 }