2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2018 Samsung Electronics. All rights
9 * ================================================================================
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
14 * http://www.apache.org/licenses/LICENSE-2.0
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
21 * ============LICENSE_END=========================================================
24 package org.onap.ccsdk.sli.plugins.sshapicall.model;
26 import com.google.common.base.Strings;
27 import org.json.JSONException;
28 import org.json.JSONObject;
29 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
30 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
34 import java.io.ByteArrayInputStream;
35 import java.io.ByteArrayOutputStream;
37 import java.io.FileInputStream;
38 import java.io.FileNotFoundException;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.nio.charset.StandardCharsets;
42 import java.util.Collections;
43 import java.util.HashSet;
45 import java.util.Properties;
48 public class ParseParam {
49 private static final Logger log = LoggerFactory.getLogger(ParseParam.class);
51 * Default SSH command timeout
53 private long dEF_timeout = 12000;
55 * Default SSH connection port.
57 private int dEF_port = 22;
59 * Default SSH command timeout
61 private final String FILE_PARAMETERS_OPT_KEY = "FileParameters";
62 public final String SSH_ResponsePrefix = "ResponsePrefix";
64 * Default SSH connection port.
66 private final String ENV_PARAMETERS_OPT_KEY = "EnvParameters";
67 private Parameters p = new Parameters();
69 public Parameters getParameters(Map<String, String> paramMap) throws SvcLogicException {
70 p.sshapiUrl = parseParam(paramMap, "Url", true, null);
71 p.sshapiPort = Integer.parseInt(parseParam(paramMap, "Port", true, Integer.toString(dEF_port)));
72 p.sshapiUser = parseParam(paramMap, "User", false, null);
73 p.sshapiPassword = parseParam(paramMap, "Password", false, null);
74 p.sshKey = parseParam(paramMap, "SshKey", false, null);
75 p.sshExecTimeout = Long.parseLong(parseParam(paramMap, "ExecTimeout", false, Long.toString(dEF_timeout)));
76 p.sshWithRetry = Boolean.valueOf(parseParam(paramMap, "Retry", false, "false"));
77 p.cmd = parseParam(paramMap, "Cmd", true, null);
78 p.responsePrefix = parseParam(paramMap, SSH_ResponsePrefix, false, null);
79 p.responseType = Format.fromString(parseParam(paramMap, "ResponseType", false, "none"));
80 p.listNameList = getListNameList(paramMap);
81 p.convertResponse = Boolean.valueOf(parseParam(paramMap, "ConvertResponse", false, "true"));
82 p.authtype = AuthType.fromString(parseParam(paramMap, "AuthType", false, "unspecified"));
87 public String getStringParameters(Map<String, String> paramMap, String paramName) throws SvcLogicException {
88 return parseParam(paramMap, SSH_ResponsePrefix, false, null);
91 public void parseOutput (SvcLogicContext ctx, String outMessage) throws SvcLogicException {
92 if (p.convertResponse) {
93 if (p.responseType == Format.NONE) {
94 classifyOutput(ctx, outMessage);
95 } else if (p.responseType == Format.JSON) {
96 classifyOutput(ctx, outMessage);
97 } else if (p.responseType == Format.XML) {
98 classifyOutput(ctx, outMessage, p.listNameList);
103 private void classifyOutput(SvcLogicContext ctx, String outMessage, Set<String> listNameList) throws SvcLogicException {
104 Map<String, String> mm = XmlParser.convertToProperties(outMessage, p.listNameList);
108 private void toCtx (SvcLogicContext ctx, Map<String, String> mm) {
110 for (Map.Entry<String, String> entry : mm.entrySet()) {
111 if (p.responsePrefix != null) {
112 ctx.setAttribute(p.responsePrefix + "." + entry.getKey(), entry.getValue());
113 log.info("+++ " + p.responsePrefix + "." + entry.getKey() + ": [" + entry.getValue() + "]");
115 ctx.setAttribute(entry.getKey(), entry.getValue());
116 log.info("+++ " + entry.getKey() + ": [" + entry.getValue() + "]");
122 private void classifyOutput(SvcLogicContext ctx, String outMessage) throws SvcLogicException {
124 Map<String, String> mm = JsonParser.convertToProperties(outMessage);
126 } catch (org.codehaus.jettison.json.JSONException e) {
127 log.info("Output not in JSON format");
128 putToProperties(ctx, p.responsePrefix);
129 } catch (Exception e) {
130 throw new SvcLogicException("error parsing response file");
134 private void putToProperties(SvcLogicContext ctx, String outMessage) throws SvcLogicException {
137 Properties prop = new Properties();
138 prop.load(new ByteArrayInputStream(outMessage.getBytes(StandardCharsets.UTF_8)));
139 for (Object key : prop.keySet()) {
140 String name = (String) key;
141 String value = prop.getProperty(name);
142 if (value != null && value.trim().length() > 0) {
143 if (p.responsePrefix != null) {
144 ctx.setAttribute(p.responsePrefix + "." + name, value.trim());
145 log.info("+++ " + p.responsePrefix + "." + name + ": [" + value + "]");
147 ctx.setAttribute(name, value.trim());
148 log.info("+++ " + name + ": [" + value + "]");
152 } catch (Exception e) {
153 throw new SvcLogicException( "Error parsing response file.");
157 public String makeCommand (Map<String, String> params) {
158 JSONObject jsonPayload = new JSONObject();
159 final String[] optionalTestParams = {ENV_PARAMETERS_OPT_KEY, FILE_PARAMETERS_OPT_KEY};
160 parseParam(params, optionalTestParams, jsonPayload);
161 JSONObject envParams = (JSONObject) jsonPayload.remove(ENV_PARAMETERS_OPT_KEY);
162 JSONObject fileParams = (JSONObject) jsonPayload.remove(FILE_PARAMETERS_OPT_KEY);
164 StringBuilder constructedCommand = new StringBuilder();
165 constructedCommand.append(parseFileParam(fileParams)).append(p.cmd).append(" ").append(parseEnvParam(envParams));
167 return constructedCommand.toString();
170 private String parseEnvParam(JSONObject envParams) {
171 StringBuilder envParamBuilder = new StringBuilder();
172 if (envParams != null) {
173 for (Object key : envParams.keySet()) {
174 if (envParamBuilder.length() > 0) {
175 envParamBuilder.append(", ");
177 envParamBuilder.append(key + "=" + envParams.get((String) key));
180 return envParamBuilder.toString();
183 private String parseFileParam(JSONObject fileParams) {
184 StringBuilder fileParamBuilder = new StringBuilder();
185 if (fileParams != null) {
186 for (Object key : fileParams.keySet()) {
187 fileParamBuilder.append("echo -e \"" + fileParams.get((String) key) + "\" > /srv/salt/" + key).append("; ");
190 return fileParamBuilder.toString();
193 private void parseParam(Map<String, String> params, String[] optionalTestParams, JSONObject jsonPayload)
194 throws JSONException {
196 Set<String> optionalParamsSet = new HashSet<>();
197 Collections.addAll(optionalParamsSet, optionalTestParams);
202 .filter(entry -> optionalParamsSet.contains(entry.getKey()))
203 .filter(entry -> !Strings.isNullOrEmpty(entry.getValue()))
204 .forEach(entry -> parseParam(entry, jsonPayload));
208 private void parseParam(Map.Entry<String, String> params, JSONObject jsonPayload)
209 throws JSONException {
210 String key = params.getKey();
211 String payload = params.getValue();
214 case ENV_PARAMETERS_OPT_KEY:
215 JSONObject paramsJson = new JSONObject(payload);
216 jsonPayload.put(key, paramsJson);
219 case FILE_PARAMETERS_OPT_KEY:
220 jsonPayload.put(key, getFilePayload(payload));
229 * Return payload with escaped newlines
231 private JSONObject getFilePayload(String payload) {
232 String formattedPayload = payload.replace("\n", "\\n").replace("\r", "\\r");
233 return new JSONObject(formattedPayload);
236 private Set<String> getListNameList(Map<String, String> paramMap) {
237 Set<String> ll = new HashSet<>();
238 for (Map.Entry<String,String> entry : paramMap.entrySet())
239 if (entry.getKey().startsWith("listName"))
240 ll.add(entry.getValue());
244 private String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
245 throws SvcLogicException {
246 String s = paramMap.get(name);
248 if (s == null || s.trim().length() == 0) {
251 throw new SvcLogicException("Parameter " + name + " is required in sshapiCallNode");
255 StringBuilder value = new StringBuilder();
257 int i1 = s.indexOf('%');
259 int i2 = s.indexOf('%', i1 + 1);
263 String varName = s.substring(i1 + 1, i2);
264 String varValue = System.getenv(varName);
265 if (varValue == null)
266 varValue = "%" + varName + "%";
268 value.append(s.substring(i, i1));
269 value.append(varValue);
272 i1 = s.indexOf('%', i);
274 value.append(s.substring(i));
276 log.info("Parameter {}: [{}]", name, value);
277 return value.toString();