Update gvnfm-driver .gitreview file
[vfc/nfvo/driver/vnfm/gvnfm.git] / juju / juju-vnfmadapter / Juju-vnfmadapterService / service / src / main / java / org / openo / nfvo / jujuvnfmadapter / common / LocalComandUtils.java
1 /*
2  * Copyright 2016 Huawei Technologies Co., Ltd.
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.openo.nfvo.jujuvnfmadapter.common;
18
19 import java.io.File;
20 import java.io.InputStream;
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.concurrent.TimeoutException;
24
25 import org.apache.commons.lang3.StringUtils;
26 import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 /**
31  * For execute local command
32  * (support control overtime)
33  * <br/>
34  * <p>
35  * </p>
36  * 
37  * @author quanzhong@huawei.com
38  * @version NFVO 0.5 Sep 19, 2016
39  */
40 public class LocalComandUtils {
41     private LocalComandUtils(){
42         
43     }
44
45     private static final Logger log = LoggerFactory.getLogger(LocalComandUtils.class);
46
47
48     /**
49      * <br>
50      * 
51      * @param command
52      * @return String
53      */
54     public static String formatCommand(List<String> command) {
55         StringBuilder builder = new StringBuilder();
56         if(command != null) {
57             for(String cmd : command) {
58                 builder.append(cmd).append(" "); // NOSONAR
59             }
60         }
61         return builder.toString();
62
63     }
64
65     /**
66      * <br>
67      * 
68      * @param dir
69      * @param command
70      * @return
71      */
72     public static ExeRes execute(String dir, String... command) {
73         List<String> commands = new ArrayList<>(command.length);
74         for(String arg : command) {
75             commands.add(arg);
76         }
77         return execute(dir, commands);
78
79     }
80
81     /**
82      * execute local command
83      * <br/>
84      * 
85      * @param dir the command path
86      * @param command
87      * @param timeout  millis
88      * @return response msg
89      * @since NFVO 0.5
90      */
91     public static ExeRes execute(String dir, List<String> command,long timeout) {
92         ExeRes er = new ExeRes();
93         StringBuilder sb = new StringBuilder();
94         try {
95             if(SwitchController.isDebugModel()) {
96                 command.set(0, "juju.bat");
97             }
98             ProcessBuilder pb = new ProcessBuilder(command);
99             if(StringUtils.isNotBlank(dir)) {
100                 pb.directory(new File(dir));
101             }
102             pb.redirectErrorStream(true);
103             Process p = pb.start();
104
105             // wait the process result
106             buildProcessResult(er, p, timeout);
107
108             InputStream in = p.getInputStream();
109             byte[] buffer = new byte[1024];
110             int length;
111             while((length = in.read(buffer)) > 0) {
112                 sb.append(new String(buffer, 0, length));
113             }
114             in.close();
115             er.setBody(sb.toString());
116         } catch(Exception e) {
117             er.setCode(ExeRes.FAILURE);
118             er.setBody(e.getMessage());
119             log.error("execute the command failed:{}", command, e);
120         }
121         return er;
122     }
123     
124     /**
125      * execute local command
126      * <br/>
127      * 
128      * @param dir the command path
129      * @param command
130      * @return response msg
131      * @since NFVO 0.5
132      */
133     public static ExeRes execute(String dir, List<String> command) {  
134         return execute(dir,command,Constant.PROCESS_WAIT_MILLIS);
135     }
136
137     /**
138      * <br/>
139      * 
140      * @param er
141      * @param p
142      * @param timeout millis
143      * @throws TimeoutException
144      * @throws InterruptedException
145      * @since NFVO 0.5
146      */
147     private static void buildProcessResult(ExeRes er, Process p,long timeout) throws TimeoutException, InterruptedException {
148         Worker worker = new Worker(p);
149         worker.start();
150         try {
151             worker.join(timeout);
152             if(worker.exitValue != null) {
153                 int exit = worker.exitValue;
154                 if(exit != 0) {
155                     er.setCode(ExeRes.FAILURE);
156                     log.warn("the process exit non-normal");
157                 } else {
158                     er.setCode(ExeRes.SUCCESS);
159                 }
160             } else {
161                 er.setCode(ExeRes.FAILURE);
162                 log.warn("the process execute timeout.");
163                 throw new TimeoutException();
164             }
165         } catch(InterruptedException e) {
166             worker.interrupt();
167             Thread.currentThread().interrupt();
168             throw e;
169         }
170     }
171
172     /**
173      * 
174      * <br/>
175      * <p>
176      * </p>
177      * 
178      * @author          quanzhong@huawei.com
179      * @version     NFVO 0.5  Sep 19, 2016
180      */
181     private static class Worker extends Thread {
182
183         private final Process process;
184
185         private Integer exitValue;
186
187         private Worker(Process process) {
188             this.process = process;
189         }
190
191         /**
192          * <br/>
193          * 
194          * @since NFVO 0.5
195          */
196         @Override
197         public void run() {
198             try {
199                 exitValue = process.waitFor();
200             } catch(InterruptedException e) {
201                 return;
202             }
203         }
204
205     }
206
207     /**
208      * <br>
209      * <p>
210      * </p>
211      * 
212      * @author
213      */
214     public static class ExeRes {
215
216         public static final int SUCCESS = 0;
217
218         public static final int FAILURE = -1;
219
220         private int code;
221
222         private String body;
223
224         /**
225          * @return Returns the code.
226          */
227         public int getCode() {
228             return code;
229         }
230
231         /**
232          * @param code The code to set.
233          */
234         public void setCode(int code) {
235             this.code = code;
236         }
237
238         /**
239          * @return Returns the body.
240          */
241         public String getBody() {
242             return body;
243         }
244
245         /**
246          * @param body The body to set.
247          */
248         public void setBody(String body) {
249             this.body = body;
250         }
251
252         @Override
253         public String toString() {
254             try {
255                 return EntityUtils.toString(this, this.getClass());
256             } catch(Exception e) {
257                 log.error("to string error:", e);
258                 return "code:" + this.getCode() + ",body:" + this.getBody();
259             }
260         }
261
262     }
263 }