RobotCore 1.0
WPILib port to raspberry Pi
Loading...
Searching...
No Matches
LaunchRemote.java
1/*
2 * Copyright (c) 2013 Creative Sphere Limited.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 * http://www.apache.org/licenses/LICENSE-2.0
7 *
8 * Unless required by applicable law or agreed to in writing,
9 * software distributed under the License is distributed on an "AS IS" BASIS,
10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 * See the License for the specific language governing permissions and
12 * limitations under the License.
13 *
14 * Contributors:
15 *
16 * Creative Sphere - initial API and implementation
17 *
18 */
19package org.ah.java.remotevmlauncher.client;
20
21import java.io.DataInputStream;
22import java.io.DataOutputStream;
23import java.io.File;
24import java.io.FileInputStream;
25import java.io.IOException;
26import java.io.InputStream;
27import java.io.OutputStream;
28import java.net.ConnectException;
29import java.net.InetSocketAddress;
30import java.net.Socket;
31import java.net.URI;
32import java.net.URL;
33import java.net.URLClassLoader;
34import java.util.LinkedHashSet;
35import java.util.List;
36import java.util.Map;
37import java.util.Set;
38import java.util.logging.Level;
39import java.util.logging.Logger;
40
41import org.ah.java.remotevmlauncher.ClassLoaderType;
42import org.ah.java.remotevmlauncher.ClasspathUtils;
43import org.ah.java.remotevmlauncher.JavaLoggingUtils;
44import org.ah.java.remotevmlauncher.PathUtils;
45import org.ah.java.remotevmlauncher.protocol.ArgumentsProcessor;
46import org.ah.java.remotevmlauncher.protocol.CacheResponseProcessor;
47import org.ah.java.remotevmlauncher.protocol.CacheResponseProcessor.ResourceResponse;
48
49import io.github.classgraph.ClassGraph;
50
51import org.ah.java.remotevmlauncher.protocol.LocalClasspathProcessor;
52import org.ah.java.remotevmlauncher.protocol.MainClassProcessor;
53import org.ah.java.remotevmlauncher.protocol.ProtocolStateMachine;
54import org.ah.java.remotevmlauncher.protocol.ReadyProcessor;
55import org.ah.java.remotevmlauncher.protocol.RemoteClasspathProcessor;
56import org.ah.java.remotevmlauncher.protocol.ResourceProcessor;
57import org.ah.java.remotevmlauncher.protocol.ResourceRequestProcessor;
58import org.ah.java.remotevmlauncher.protocol.StartApplicationProcessor;
59import org.ah.java.remotevmlauncher.protocol.StartRemoteVMProcessor;
60import org.ah.java.remotevmlauncher.protocol.StreamProcessor;
61
67public class LaunchRemote {
68
69 public static Logger LOGGER = Logger.getLogger("");
70 public static Logger CLIENT_LOGGER = Logger.getLogger("> Client: ");
71
72 protected static StreamProcessor DEFAULT_STREAM_PROCESSOR = new StreamProcessor() {
73 @Override
74 public void invoke() {
75 System.out.print(getReceived());
76 }
77 };
78
79 private InetSocketAddress remoteAgentSocketAddress;
80
81 @SuppressWarnings("unused")
82 private ClassLoaderType classLoaderType = ClassLoaderType.CACHED_RESOURCES;
83
84 private Socket socket;
85 private InputStream inputStream;
86 private DataInputStream dataInputStream;
87 private OutputStream outputStream;
88 private DataOutputStream dataOutputStream;
89 private ProtocolStateMachine stateMachine;
90 private ReadyProcessor readyProcessor;
91
92 private ResourceRequestProcessor resourceRequestProcessor;
93 private StreamProcessor streamProcessor = DEFAULT_STREAM_PROCESSOR;
94 private ResourceProcessor resourceProcessor = new ResourceProcessor();
95 private LocalClasspathProcessor localClasspathProcessor = new LocalClasspathProcessor();
96 private CacheResponseProcessor cacheResponseProcessor = new CacheResponseProcessor();
97 private ArgumentsProcessor argumentsProcessor = new ArgumentsProcessor();
98 private RemoteClasspathProcessor remoteClasspathProcessor = new RemoteClasspathProcessor();
99 private MainClassProcessor mainClassProcessor = new MainClassProcessor();
100 private StartApplicationProcessor startApplicationProcessor = new StartApplicationProcessor();
101 private StartRemoteVMProcessor startRemoteVMProcessor = new StartRemoteVMProcessor();
102
103 private Set<String> excludeClassPath = new LinkedHashSet<String>();
104
105 public LaunchRemote() {
106 }
107
108 public InetSocketAddress getRemoteAgentSocketAddress() {
109 return remoteAgentSocketAddress;
110 }
111
112 public void setRemoteAgentSocketAddress(InetSocketAddress remoteAgentSocketAddress) {
113 this.remoteAgentSocketAddress = remoteAgentSocketAddress;
114 }
115
116 public void setup() throws IOException {
117 try {
118 socket = new Socket(remoteAgentSocketAddress.getAddress(), remoteAgentSocketAddress.getPort());
119 } catch (ConnectException e) {
120 System.err.println("Cannot connect to " + remoteAgentSocketAddress.getAddress() + ":"
121 + remoteAgentSocketAddress.getPort());
122 System.err.println("The Agent is probably not running on the remote machine.");
123 System.err.println("Get agent.jar and run it with: ");
124 System.err.println(" java -jar agent.jar ");
125 if (remoteAgentSocketAddress.getPort() == 8999) {
126 System.err.println("for default port 8999. Or if you want to run it at alternative port run it with:");
127 System.err.println(" java -jar agent.jar -l <new-port>");
128 System.err.println("But then you need to run this side launcher with that port as well.");
129 } else {
130 System.err.println(
131 "for default port 8999. Or if you want to run it at alternative port (as specified here) run it with:");
132 System.err.println(" java -jar agent.jar -l " + remoteAgentSocketAddress.getPort());
133 }
134 System.exit(1);
135 }
136
137 inputStream = socket.getInputStream();
138 dataInputStream = new DataInputStream(inputStream);
139
140 outputStream = socket.getOutputStream();
141 dataOutputStream = new DataOutputStream(outputStream);
142
143 stateMachine = new ProtocolStateMachine(CLIENT_LOGGER);
144
145 readyProcessor = new ReadyProcessor();
146 stateMachine.getProcessorMap().put(ReadyProcessor.ID, readyProcessor);
147
148 stateMachine.getProcessorMap().put("S0", streamProcessor);
149
150 resourceRequestProcessor = new ResourceRequestProcessor() {
151 @Override
152 public void processRequest(String pathId, String resourceName) throws IOException {
153 String pathString = localClasspathProcessor.getLocalClasspath().get(pathId);
154 File path = new File(pathString);
155 File resource = new File(path, resourceName);
156 if (!resource.exists()) {
157 resourceProcessor.send(dataOutputStream, null, -1);
158 } else {
159 FileInputStream fis = new FileInputStream(resource);
160 try {
161 resourceProcessor.send(dataOutputStream, fis, (int) resource.length());
162 } finally {
163 fis.close();
164 }
165 }
166 }
167 };
168 stateMachine.getProcessorMap().put(ResourceRequestProcessor.ID, resourceRequestProcessor);
169 }
170
171 public void start() throws IOException {
172 LOGGER.info("Collecting classpath...");
173 collectClasspath();
174 LOGGER.info("Collecting resources...");
175 collectResources();
176 LOGGER.info("Starting remote VM...");
177 if (StartRemoteVMProcessor.IMPLEMENTED) {
178 startRemoteVMProcessor.send(dataOutputStream);
179 if (LOGGER.isLoggable(Level.FINE)) {
180 LOGGER.fine(" With remote VM arguments:");
181 for (String a : startRemoteVMProcessor.getVmArgs()) {
182 LOGGER.fine(" " + a);
183 }
184 LOGGER.fine(" With launcher arguments:");
185 for (String a : startRemoteVMProcessor.getLauncherArgs()) {
186 LOGGER.fine(" " + a);
187 }
188 }
189 }
190 LOGGER.info("Waiting for remote client to start...");
191 synchronized (readyProcessor) {
192 while (!readyProcessor.isReady()) {
193 stateMachine.processInput(dataInputStream);
194 }
195 }
196 LOGGER.info("Remote client started.");
197
198 LOGGER.info("Sending remote classpath...");
199 remoteClasspathProcessor.send(dataOutputStream);
200
201 LOGGER.info("Sending classpath...");
202 localClasspathProcessor.send(dataOutputStream);
203
204 LOGGER.info("Sending resource details...");
205 cacheResponseProcessor.send(dataOutputStream);
206
207 LOGGER.info("Sending arguments...");
208 argumentsProcessor.send(dataOutputStream);
209 if (LOGGER.isLoggable(Level.FINE)) {
210 for (String a : argumentsProcessor.getArguments()) {
211 LOGGER.fine(" " + a);
212 }
213 }
214
215 LOGGER.info("Sending main class \"" + mainClassProcessor.getMainClass() + "\"...");
216 mainClassProcessor.send(dataOutputStream);
217
218 LOGGER.info("Sending signal for client to start application...");
219 startApplicationProcessor.send(dataOutputStream);
220
221 LOGGER.info("Output form the client:");
222 LOGGER.info("----------------------------------------------------------------------------------------------");
223
224 try {
225 while (true) {
226 stateMachine.processInput(dataInputStream);
227 }
228 } catch (IOException e) {
229 }
230
231 LOGGER.info("----------------------------------------------------------------------------------------------");
232 LOGGER.info("Finished.");
233 }
234
235 private URI[] getClassList() {
236 String path = System.getProperty("user.dir").replace('\\', '/');
237 int idx = path.lastIndexOf('/');
238 String root = path.substring(idx) + "/";
239 List<URI> classpath = new ClassGraph().getClasspathURIs();
240
241 // System.out.println(String.format("root=%s", root));
242
243 // Remove all items not in root folder
244
245 for (int i = classpath.size() - 1; i >= 0; i--) {
246 URI uri = classpath.get(i);
247 String file = uri.getPath();
248
249 if ((file == null) || !file.contains(root)) {
250 classpath.remove(i);
251 }
252 // else if (file != null);
253 // {
254 // System.out.println(file);
255 // }
256 }
257
258 URI[] items = new URI[classpath.size()];
259 return (classpath.toArray(items));
260 }
261
262 protected int addFile(String[] rootComponents, String filePath, int nextId) {
263 filePath = filePath.replace("\\", "/");
264 String[] filePathComponents = filePath.split("/");
265 String relPath = PathUtils.relativisePath(rootComponents, filePathComponents);
266 // System.out.println(relPath);
267
268 String pathId = localClasspathProcessor.getLocalClasspath().get(relPath);
269 if (pathId == null) {
270 pathId = Integer.toString(nextId);
271 localClasspathProcessor.getLocalClasspath().put(pathId, relPath);
272 nextId = nextId + 1;
273 }
274
275 return nextId;
276 }
277
278 protected int collectDeployFiles(String[] rootComponents, String path, int nextId) {
279 File folder = new File(path);
280 if (folder != null)
281 {
282 File[] files = folder.listFiles();
283 if (files != null) {
284 for (File file : files) {
285 // System.out.println(file.getAbsolutePath());
286 nextId = addFile(rootComponents, file.getAbsolutePath(), nextId);
287 if (file.isDirectory()) {
288 nextId = collectDeployFiles(rootComponents, file.getAbsolutePath(), nextId);
289 }
290 }
291 }
292 }
293
294 return nextId;
295 }
296
297 protected void collectClasspath() throws IOException {
298 // URI[] list = getClassList();
299
300 int nextId = 1;
301 File hereDir = new File("");
302 String herePath = hereDir.getAbsolutePath().replace("\\", "/");
303 // localClasspathProcessor.getLocalClasspath().put("HOME", herePath);
304 String[] herePathComponents = herePath.split("/");
305 String launchersPath = ClasspathUtils.obtainPathOfClass(getClass());
306 if (!launchersPath.endsWith(".jar")) {
307 launchersPath = null;
308 }
309 // ClassLoader classLoader = LaunchRemote.class.getClassLoader();
310 // if (classLoader instanceof URLClassLoader)
311 {
312 // URLClassLoader urlClassLoader = (URLClassLoader)classLoader;
313 // URL[] urls = urlClassLoader.getURLs();
314 URI[] urls = getClassList();
315 for (URI url : urls) {
316 // if (!url.getProtocol().equals("file")) {
317 // throw new UnsupportedOperationException("Only file: protocol URLs in
318 // classpath are implemented at this point in time.");
319 // }
320 File file = new File(url.getPath());
321 String filePath = file.getAbsolutePath().replace("\\", "/");
322 // Don't sent remotevm-client*.jar over the wire.
323 if (!filePath.equals(launchersPath)) {
324 String[] filePathComponents = filePath.split("/");
325 String relativisedPath = PathUtils.relativisePath(herePathComponents, filePathComponents);
326
327 if (!excludeClassPath.contains(relativisedPath) && !excludeClassPath.contains(filePath)) {
328 String pathId = localClasspathProcessor.getLocalClasspath().get(relativisedPath);
329 if (pathId == null) {
330 pathId = Integer.toString(nextId);
331 localClasspathProcessor.getLocalClasspath().put(pathId, relativisedPath);
332 nextId = nextId + 1;
333 }
334 }
335 }
336 }
337 if (LOGGER.isLoggable(Level.FINE)) {
338 for (Map.Entry<String, String> cpe : localClasspathProcessor.getLocalClasspath().entrySet()) {
339 LOGGER.fine(" " + cpe.getKey() + ": " + cpe.getValue());
340 }
341 }
342 }
343
344 nextId = addFile(herePathComponents, herePath + "/deploy", nextId);
345 collectDeployFiles(herePathComponents, herePath + "/deploy", nextId);
346 // else {
347 // throw new UnsupportedOperationException("Class loader is not of
348 // URLClassLoader type. This type of class loader is not yet supported.");
349 // }
350 }
351
352 protected void collectResources() {
353 for (Map.Entry<String, String> entry : localClasspathProcessor.getLocalClasspath().entrySet()) {
354 collectResources(entry.getKey(), new File(entry.getValue()), "");
355 }
356 if (LOGGER.isLoggable(Level.FINER)) {
357 for (ResourceResponse r : cacheResponseProcessor.getResources()) {
358 LOGGER.finer(" " + r.pathId + ": (" + r.hash + ", " + r.length + ") " + r.name);
359 }
360 }
361 }
362
363 protected void collectResources(String pathId, File path, String resource) {
364 File file = new File(path, resource);
365 if (file.isDirectory()) {
366 for (File f : file.listFiles()) {
367 if (!f.equals(".") && !f.equals("..")) {
368 File resourceFile;
369 if (resource.equals("")) {
370 resourceFile = new File(f.getName());
371 } else {
372 resourceFile = new File(new File(resource), f.getName());
373 }
374 collectResources(pathId, path, resourceFile.getPath());
375 }
376 }
377 } else {
378 ResourceResponse rr = new ResourceResponse();
379 rr.pathId = pathId;
380 rr.name = resource.replace("\\", "/");
381 rr.hash = file.lastModified();
382 rr.length = file.length();
383 cacheResponseProcessor.getResources().add(rr);
384 }
385 }
386
387 public void run(String[] args) throws Exception {
388 LaunchRemote client = this; // new LaunchRemote();
389
390 int debugLevel = 0;
391
392 boolean remoteClasspath = false;
393 boolean excludeClasspath = false;
394 boolean addressAndPort = true;
395 boolean mainClass = true;
396 boolean arguments = false;
397 boolean allRead = false;
398 boolean debugLevelFlag = false;
399 boolean remoteDebugPortFlag = false;
400 boolean remoteVMarg = false;
401 for (String arg : args) {
402 if (!arguments) {
403 if (remoteClasspath) {
404 client.remoteClasspathProcessor.getRemoteClasspath().add(arg);
405 remoteClasspath = false;
406 } else if (excludeClasspath) {
407 client.excludeClassPath.add(arg);
408 excludeClasspath = false;
409 } else if (debugLevelFlag) {
410 debugLevel = Integer.parseInt(arg);
411 client.startRemoteVMProcessor.getLauncherArgs().add("-d");
412 client.startRemoteVMProcessor.getLauncherArgs().add(Integer.toString(Integer.parseInt(arg)));
413 debugLevelFlag = false;
414 } else if (remoteDebugPortFlag) {
415 client.startRemoteVMProcessor.setRemoteDebugPort(Integer.parseInt(arg));
416 remoteDebugPortFlag = false;
417 } else if (remoteVMarg) {
418 client.startRemoteVMProcessor.getVmArgs().add(arg);
419 remoteVMarg = false;
420 } else if ("-rcp".equals(arg) || "--remote-classpath".equals(arg)) {
421 remoteClasspath = true;
422 } else if ("-ecp".equals(arg) || "--exclude-classpath".equals(arg)) {
423 excludeClasspath = true;
424 } else if ("-d".equals(arg) || "--debug".equals(arg)) {
425 debugLevelFlag = true;
426 } else if ("-rdp".equals(arg) || "--remote-debug-port".equals(arg)) {
427 remoteDebugPortFlag = true;
428 } else if ("-rds".equals(arg) || "--remote-debug-suspend".equals(arg)) {
429 client.startRemoteVMProcessor.setRemoteDebugSuspendAtStart(true);
430 } else if ("-rvma".equals(arg) || "--remote-VM-argment".equals(arg)) {
431 remoteVMarg = true;
432 } else if ("-h".equals(arg) || "--help".equals(arg)) {
433 printHelp();
434 System.exit(0);
435 } else if (addressAndPort) {
436 int i = arg.indexOf(':');
437 if (i < 0) {
438 client.setRemoteAgentSocketAddress(new InetSocketAddress(Integer.parseInt(arg)));
439 } else {
440 client.setRemoteAgentSocketAddress(
441 new InetSocketAddress(arg.substring(0, i), Integer.parseInt(arg.substring(i + 1))));
442 }
443 addressAndPort = false;
444 mainClass = true;
445 } else if (mainClass) {
446 client.mainClassProcessor.setMainClass(arg);
447 mainClass = false;
448 allRead = true;
449 } else if (allRead) {
450 if ("--".equals(arg)) {
451 allRead = false;
452 arguments = true;
453 } else {
454 System.out.println("ERROR: unknown argument '" + arg + "'");
455 System.out.println();
456 printHelp();
457 System.exit(1);
458 }
459 } else {
460 System.out.println("ERROR: unknown argument '" + arg + "'");
461 System.out.println();
462 printHelp();
463 System.exit(1);
464 }
465 } else {
466 client.argumentsProcessor.getArguments().add(arg);
467 }
468 }
469 if (addressAndPort) {
470 System.out.println("ERROR: missing address and port argument.");
471 System.out.println();
472 printHelp();
473 System.exit(1);
474 }
475 if (mainClass) {
476 System.out.println("ERROR: missing main class argument.");
477 System.out.println();
478 printHelp();
479 System.exit(1);
480 }
481
482 JavaLoggingUtils.setupSimpleConsoleLogging(debugLevel);
483
484 client.setup();
485
486 client.start();
487 }
488
489 public static void printHelp() {
490 System.out.println("Remote VM Launcher usage:");
491 System.out.println("");
492 System.out.println("java -jar remotevmlauncher-client.jar {options} [address:]port mainClass");
493 System.out.println("");
494 System.out.println("Options:");
495 System.out.println("");
496 System.out.println(" -rcp|--remote-classpath classpath-entry");
497 System.out.println(" classpath entry as seen from remote machine");
498 System.out.println(" where agent is running.");
499 System.out.println(" -ecp|--exclude-classpath classpath-entry");
500 System.out.println(" classpath entry not to be send to the remote");
501 System.out.println(" machine where agent is running.");
502 System.out.println(" -d|--debug level debug level from 0 to 4. Default: 0");
503 System.out.println(" -rdp|--remote-debug-port port ");
504 System.out.println(" If port is specified remote VM will be launched");
505 System.out.println(" in debug mode at the specified port.");
506 System.out.println(" -rds|--remote-debug-suspend ");
507 System.out.println(" If port is specified and if this flag as well");
508 System.out.println(" remote VM will be suspended.");
509 System.out.println(" -h|--help this help.");
510 System.out.println("");
511 System.out.println("If launcher is used from an IDE, and ");
512 System.out.println(" org.ah.java.remotevmlauncher.client.LaunchRemote class is directly used as");
513 System.out.println("main class, then supplied classpath will automatically used (provided that it");
514 System.out.println("is defined as URLClassLoader or descendant class) on the remote side.");
515 System.out.println("");
516 System.out.println("Note: if remote debug port is specified launcher's VM is started with:");
517 System.out.println("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=(y|n),address=<port>");
518 System.out.println("depending on port and if suspend is specified or not.");
519 }
520
521}