View Javadoc
1   /**
2    * This Source Code Form is subject to the terms of the Mozilla Public
3    * License, v. 2.0. If a copy of the MPL was not distributed with this
4    * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5    *
6    * If it is not possible or desirable to put the notice in a particular
7    * file, then You may include the notice in a location (such as a LICENSE
8    * file in a relevant directory) where a recipient would be likely to look
9    * for such a notice.
10  
11   * 
12   */
13   
14  /*  ---------------------------------------------------------------------------
15   *  U.S. Government, Department of the Army
16   *  Army Materiel Command
17   *  Research Development Engineering Command
18   *  Communications Electronics Research Development and Engineering Center
19   *  ---------------------------------------------------------------------------
20   */
21  
22  package org.miloss.fgsms.osagent.callbacks;
23  
24  import java.io.BufferedInputStream;
25  import java.io.File;
26  import java.io.InputStream;
27  import java.util.GregorianCalendar;
28  import java.util.Queue;
29  import java.util.concurrent.ConcurrentLinkedQueue;
30  import javax.jws.WebMethod;
31  import javax.jws.WebParam;
32  import javax.jws.WebResult;
33  import javax.jws.WebService;
34  import javax.xml.bind.annotation.XmlSeeAlso;
35  import javax.xml.datatype.DatatypeFactory;
36  import javax.xml.ws.RequestWrapper;
37  import javax.xml.ws.ResponseWrapper;
38  import org.miloss.fgsms.common.Constants;
39  import org.miloss.fgsms.services.interfaces.agentcallbackservice.AccessDeniedException;
40  import org.miloss.fgsms.services.interfaces.agentcallbackservice.RemoteAgentCallbackPort;
41  import org.miloss.fgsms.services.interfaces.agentcallbackservice.ServiceUnavailableException;
42  import org.miloss.fgsms.services.interfaces.common.GetOperatingStatusRequestMessage;
43  import org.miloss.fgsms.services.interfaces.common.GetOperatingStatusResponseMessage;
44  import org.miloss.fgsms.osagent.OSAgent;
45  import org.apache.log4j.Level;
46  import org.miloss.fgsms.common.Logger;;
47  
48  /**
49   * Remote Agent Callback Port Type. This provides callback from the fgsms
50   * instance
51   *
52   * This class was generated by the JAX-WS RI. JAX-WS RI 2.1.7-04/11/2011 03:11
53   * PM(mockbuild)- Generated source version: 2.1
54   *
55   * @author AO
56   * @since 6.3
57   */
58  @Deprecated
59  
60  @WebService(name = "remoteAgentCallbackPort", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:agentCallbackService")
61  @XmlSeeAlso({
62      org.miloss.fgsms.services.interfaces.faults.ObjectFactory.class,
63      org.miloss.fgsms.services.interfaces.agentcallbackservice.ObjectFactory.class,
64      us.gov.ic.ism.v2.ObjectFactory.class,
65      org.miloss.fgsms.services.interfaces.common.ObjectFactory.class
66  })
67  public class RemoteAgentCallbackImpl implements RemoteAgentCallbackPort, Runnable {
68  
69      public RemoteAgentCallbackImpl(OSAgent ref) {
70          if (ref == null) {
71              throw new IllegalArgumentException();
72          }
73          INTERNAL_REFERENCE = ref;
74  
75      }
76      protected boolean acceptingcommands = true;
77      private OSAgent INTERNAL_REFERENCE = null;
78  
79      /**
80       * Executes a set of tasks via command line
81       *
82       *
83       * @param id
84       * @param waitforexit
85       * @param authorizationcode
86       * @param command
87       * @param workingDir
88       * @return returns boolean
89       * @throws ServiceUnavailableException
90       * @throws AccessDeniedException
91       */
92      @WebMethod(operationName = "ExecuteTasks", action = "urn:org:miloss:fgsms:services:interfaces:remoteAgentCallbackService/ExecuteTasks")
93      @WebResult(name = "Accepted", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:agentCallbackService")
94      @RequestWrapper(localName = "ExecuteTasks", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:agentCallbackService", className = "org.miloss.fgsms.services.interfaces.agentcallbackservice.ExecuteTasks")
95      @ResponseWrapper(localName = "ExecuteTasksResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:agentCallbackService", className = "org.miloss.fgsms.services.interfaces.agentcallbackservice.ExecuteTasksResponse")
96      public boolean executeTasks(
97              @WebParam(name = "authorizationcode", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:agentCallbackService") String authorizationcode,
98              @WebParam(name = "id", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:agentCallbackService") String id,
99              @WebParam(name = "working_dir", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:agentCallbackService") String workingDir,
100             @WebParam(name = "command", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:agentCallbackService") String command,
101             @WebParam(name = "waitforexit", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:agentCallbackService") boolean waitforexit)
102             throws AccessDeniedException, ServiceUnavailableException {
103         if (acceptingcommands) {
104             //enqueue the task
105             AdminCommand c = new AdminCommand(this);
106             c.authcode = authorizationcode;
107             c.id = id;
108             c.enqueuedat = System.currentTimeMillis();
109             c.workingdir = workingDir;
110             c.command = command;
111             c.waitfor = waitforexit;
112             the_queue.add(c);
113             if (currentthread < maxthreads) {
114                 Thread t = new Thread(this);
115                 t.start();
116             }
117             return true;
118         } else {
119             return false;
120         }
121     }
122 
123     @Override
124     public void run() {
125         currentthread++;
126         while (!the_queue.isEmpty()) {
127             Object j = the_queue.remove();
128             if (j instanceof AdminCommand) {
129                 AdminCommand command = (AdminCommand) j;
130                 try {
131                     authorizeCommand(command);
132                     Runtime run = Runtime.getRuntime();
133                     Process pr = null;
134                     log.log(Level.INFO, "starting command " + command.id + " " + command.command);
135                     pr = run.exec(command.command, null, new File(command.workingdir));
136 
137                     if (command.waitfor) {
138                         command.exitcode = pr.waitFor();
139                         log.log(Level.INFO, "completed command " + command.id + " exit code " + command.exitcode);
140                         InputStream os = pr.getInputStream();
141                         InputStream err = pr.getErrorStream();
142                         BufferedInputStream bos = new BufferedInputStream(os);
143                         byte[] buffer = new byte[1024];
144                         int k = -1;
145                         k = bos.read(buffer);
146                         while (k > 0 && k < 1024) {
147                             command.result_stdout += new String(buffer, 0, k,Constants.CHARSET);
148                             k = bos.read(buffer);
149                         }
150                         bos.close();
151                         os.close();
152 
153                         bos = new BufferedInputStream(err);
154                         k = bos.read(buffer);
155                         while (k > 0 && bos.read(buffer) < 1024) {
156                             command.result_stderr += new String(buffer, 0, k);
157                             k = bos.read(buffer);
158                         }
159                         bos.close();
160                         err.close();
161 
162 
163                         pr.destroy();
164                     }
165                 } catch (Exception ex) {
166                     log.log(Level.WARN, "error running job " + command.id, ex);
167                     command.exitcode = 1000;
168                     command.result_stderr = ex.getMessage();
169                 }
170                 TaskDone(command);
171             }
172         }
173         currentthread--;
174     }
175 
176     private void authorizeCommand(AdminCommand command) {
177         //TODO find out how to authorize this command. prove it came from fgsms.
178     }
179     int maxthreads = 10;
180     int currentthread = 0;
181     private Queue<Object> the_queue = new ConcurrentLinkedQueue<Object>();
182 
183     private void TaskDone(AdminCommand command) {
184         //call fgsms service to notify that the task is done, success or fail, send output
185         log.log(Level.INFO, "task done " + command.id + " status " + command.exitcode);
186     }
187     static Logger log = Logger.getLogger("fgsms.fgsmsOSAgent.Callbacks");
188 
189     /**
190      *
191      * Gets the operating status of an remove agent
192      *
193      *
194      * @param request
195      * @return returns
196      * org.miloss.fgsms.services.interfaces.agentcallbackservice.GetOperatingStatusResponseMessage
197      * @throws ServiceUnavailableException
198      * @throws AccessDeniedException
199      */
200     @WebMethod(operationName = "GetOperatingStatus", action = "urn:org:miloss:fgsms:services:interfaces:remoteAgentCallbackService/GetOperatingStatus")
201     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:agentCallbackService")
202     @RequestWrapper(localName = "GetOperatingStatus", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:agentCallbackService", className = "org.miloss.fgsms.services.interfaces.agentcallbackservice.GetOperatingStatus")
203     @ResponseWrapper(localName = "GetOperatingStatusResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:agentCallbackService", className = "org.miloss.fgsms.services.interfaces.agentcallbackservice.GetOperatingStatusResponse")
204     public GetOperatingStatusResponseMessage getOperatingStatus(
205             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:agentCallbackService") GetOperatingStatusRequestMessage request)
206             throws AccessDeniedException, ServiceUnavailableException {
207         if (request == null || request.getClassification() == null || request.getClassification().getClassification() == null) {
208             throw new IllegalArgumentException("Must specify a classification level");
209         }
210         if (INTERNAL_REFERENCE == null) {
211             throw new IllegalStateException("Agent reference is null");
212         }
213         GetOperatingStatusResponseMessage res = new GetOperatingStatusResponseMessage();
214 
215         GregorianCalendar gcal = new GregorianCalendar();
216         gcal.setTimeInMillis(INTERNAL_REFERENCE.startedat);
217         try {
218             res.setStartedAt((gcal));
219         } catch (Exception ex) {
220         }
221         res.setClassification(INTERNAL_REFERENCE.getClassLevelAsCopy());
222 
223         res.setDataSentSuccessfully(new Long(INTERNAL_REFERENCE.datasend_success));
224 
225         res.setDataNotSentSuccessfully(new Long(INTERNAL_REFERENCE.datasend_failures));
226 
227         res.setVersionInfo(new GetOperatingStatusResponseMessage.VersionInfo());
228         res.getVersionInfo().setVersionData(org.miloss.fgsms.common.Constants.Version);
229         res.getVersionInfo().setVersionSource(org.miloss.fgsms.common.Constants.class.getCanonicalName());
230 
231         res.setStatus(acceptingcommands);
232         return res;
233     }
234 }