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 * Modifications Copyright © 2018 IBM
11 * ================================================================================
12 * Licensed under the Apache License, Version 2.0 (the "License");
13 * you may not use this file except in compliance with the License.
14 * You may obtain a copy of the License at
16 * http://www.apache.org/licenses/LICENSE-2.0
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
23 * ============LICENSE_END=========================================================
26 package org.onap.ccsdk.sli.plugins.sshapicall.model;
28 import com.google.common.base.Strings;
29 import org.json.JSONException;
30 import org.json.JSONObject;
31 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
32 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
36 import java.io.ByteArrayInputStream;
37 import java.nio.charset.StandardCharsets;
38 import java.util.Collections;
39 import java.util.HashSet;
41 import java.util.Properties;
44 public class ParseParam {
45 private static final Logger log = LoggerFactory.getLogger(ParseParam.class);
47 * Default SSH command timeout
49 private long dEF_timeout = 12000;
51 * Default SSH connection port.
53 private int dEF_port = 22;
55 * Default SSH command timeout
57 private final String FILE_PARAMETERS_OPT_KEY = "FileParameters";
58 public final String SSH_ResponsePrefix = "ResponsePrefix";
60 * Default SSH connection port.
62 private final String ENV_PARAMETERS_OPT_KEY = "EnvParameters";
63 private Parameters p = new Parameters();
65 public Parameters getParameters(Map<String, String> paramMap) throws SvcLogicException {
66 p.sshapiUrl = parseParam(paramMap, "Url", true, null);
67 p.sshapiPort = Integer.parseInt(parseParam(paramMap, "Port", true, Integer.toString(dEF_port)));
68 p.sshapiUser = parseParam(paramMap, "User", false, null);
69 p.sshapiPassword = parseParam(paramMap, "Password", false, null);
70 p.sshKey = parseParam(paramMap, "SshKey", false, null);
71 p.sshExecTimeout = Long.parseLong(parseParam(paramMap, "ExecTimeout", false, Long.toString(dEF_timeout)));
72 p.sshWithRetry = Boolean.valueOf(parseParam(paramMap, "Retry", false, "false"));
73 p.cmd = parseParam(paramMap, "Cmd", true, null);
74 p.responsePrefix = parseParam(paramMap, SSH_ResponsePrefix, false, null);
75 p.responseType = Format.fromString(parseParam(paramMap, "ResponseType", false, "none"));
76 p.listNameList = getListNameList(paramMap);
77 p.convertResponse = Boolean.valueOf(parseParam(paramMap, "ConvertResponse", false, "true"));
78 p.authtype = AuthType.fromString(parseParam(paramMap, "AuthType", false, "unspecified"));
83 public String getStringParameters(Map<String, String> paramMap, String paramName) throws SvcLogicException {
84 return parseParam(paramMap, SSH_ResponsePrefix, false, null);
87 public void parseOutput (SvcLogicContext ctx, String outMessage) throws SvcLogicException {
88 if (p.convertResponse) {
89 if (p.responseType == Format.NONE) {
90 classifyOutput(ctx, outMessage);
91 } else if (p.responseType == Format.JSON) {
92 classifyOutput(ctx, outMessage);
93 } else if (p.responseType == Format.XML) {
94 classifyOutput(ctx, outMessage, p.listNameList);
99 private void classifyOutput(SvcLogicContext ctx, String outMessage, Set<String> listNameList) throws SvcLogicException {
100 Map<String, String> mm = XmlParser.convertToProperties(outMessage, p.listNameList);
104 private void toCtx (SvcLogicContext ctx, Map<String, String> mm) {
106 for (Map.Entry<String, String> entry : mm.entrySet()) {
107 if (p.responsePrefix != null) {
108 ctx.setAttribute(p.responsePrefix + "." + entry.getKey(), entry.getValue());
109 log.info("+++ " + p.responsePrefix + "." + entry.getKey() + ": [" + entry.getValue() + "]");
111 ctx.setAttribute(entry.getKey(), entry.getValue());
112 log.info("+++ " + entry.getKey() + ": [" + entry.getValue() + "]");
118 private void classifyOutput(SvcLogicContext ctx, String outMessage) throws SvcLogicException {
120 Map<String, String> mm = JsonParser.convertToProperties(outMessage);
122 } catch (org.codehaus.jettison.json.JSONException e) {
123 log.info("Output not in JSON format");
124 putToProperties(ctx, p.responsePrefix);
125 } catch (Exception e) {
126 throw new SvcLogicException("error parsing response file");
130 private void putToProperties(SvcLogicContext ctx, String outMessage) throws SvcLogicException {
133 Properties prop = new Properties();
134 prop.load(new ByteArrayInputStream(outMessage.getBytes(StandardCharsets.UTF_8)));
135 for (Object key : prop.keySet()) {
136 String name = (String) key;
137 String value = prop.getProperty(name);
138 if (value != null && value.trim().length() > 0) {
139 if (p.responsePrefix != null) {
140 ctx.setAttribute(p.responsePrefix + "." + name, value.trim());
141 log.info("+++ " + p.responsePrefix + "." + name + ": [" + value + "]");
143 ctx.setAttribute(name, value.trim());
144 log.info("+++ " + name + ": [" + value + "]");
148 } catch (Exception e) {
149 throw new SvcLogicException( "Error parsing response file.");
153 public String makeCommand (Map<String, String> params) {
154 JSONObject jsonPayload = new JSONObject();
155 final String[] optionalTestParams = {ENV_PARAMETERS_OPT_KEY, FILE_PARAMETERS_OPT_KEY};
156 parseParam(params, optionalTestParams, jsonPayload);
157 JSONObject envParams = (JSONObject) jsonPayload.remove(ENV_PARAMETERS_OPT_KEY);
158 JSONObject fileParams = (JSONObject) jsonPayload.remove(FILE_PARAMETERS_OPT_KEY);
160 StringBuilder constructedCommand = new StringBuilder();
161 constructedCommand.append(parseFileParam(fileParams)).append(p.cmd).append(" ").append(parseEnvParam(envParams));
163 return constructedCommand.toString();
166 private String parseEnvParam(JSONObject envParams) {
167 StringBuilder envParamBuilder = new StringBuilder();
168 if (envParams != null) {
169 for (Object key : envParams.keySet()) {
170 if (envParamBuilder.length() > 0) {
171 envParamBuilder.append(", ");
173 envParamBuilder.append(key + "=" + envParams.get((String) key));
176 return envParamBuilder.toString();
179 private String parseFileParam(JSONObject fileParams) {
180 StringBuilder fileParamBuilder = new StringBuilder();
181 if (fileParams != null) {
182 for (Object key : fileParams.keySet()) {
183 fileParamBuilder.append("echo -e \"" + fileParams.get((String) key) + "\" > /srv/salt/" + key).append("; ");
186 return fileParamBuilder.toString();
189 private void parseParam(Map<String, String> params, String[] optionalTestParams, JSONObject jsonPayload)
190 throws JSONException {
192 Set<String> optionalParamsSet = new HashSet<>();
193 Collections.addAll(optionalParamsSet, optionalTestParams);
198 .filter(entry -> optionalParamsSet.contains(entry.getKey()))
199 .filter(entry -> !Strings.isNullOrEmpty(entry.getValue()))
200 .forEach(entry -> parseParam(entry, jsonPayload));
204 private void parseParam(Map.Entry<String, String> params, JSONObject jsonPayload)
205 throws JSONException {
206 String key = params.getKey();
207 String payload = params.getValue();
210 case ENV_PARAMETERS_OPT_KEY:
211 JSONObject paramsJson = new JSONObject(payload);
212 jsonPayload.put(key, paramsJson);
215 case FILE_PARAMETERS_OPT_KEY:
216 jsonPayload.put(key, getFilePayload(payload));
225 * Return payload with escaped newlines
227 private JSONObject getFilePayload(String payload) {
228 String formattedPayload = payload.replace("\n", "\\n").replace("\r", "\\r");
229 return new JSONObject(formattedPayload);
232 private Set<String> getListNameList(Map<String, String> paramMap) {
233 Set<String> ll = new HashSet<>();
234 for (Map.Entry<String,String> entry : paramMap.entrySet())
235 if (entry.getKey().startsWith("listName"))
236 ll.add(entry.getValue());
240 private String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
241 throws SvcLogicException {
242 String s = paramMap.get(name);
244 if (s == null || s.trim().length() == 0) {
247 throw new SvcLogicException("Parameter " + name + " is required in sshapiCallNode");
251 StringBuilder value = new StringBuilder();
253 int i1 = s.indexOf('%');
255 int i2 = s.indexOf('%', i1 + 1);
259 String varName = s.substring(i1 + 1, i2);
260 String varValue = System.getenv(varName);
261 if (varValue == null)
262 varValue = "%" + varName + "%";
264 value.append(s.substring(i, i1));
265 value.append(varValue);
268 i1 = s.indexOf('%', i);
270 value.append(s.substring(i));
272 log.info("Parameter {}: [{}]", name, value);
273 return value.toString();