File D:\maven-qcr-plugin-testsunitaires\qcr4java\jenkins-master\target\site\qc\core\src\main\java\hudson\util\RemotingDiagnostics.java.html

1 /*
2 * The MIT License
3 *
4 * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 package hudson.util;
25
26 import groovy.lang.Binding;
27 import groovy.lang.GroovyShell;
28 import hudson.FilePath;
29 import hudson.Functions;
30 import jenkins.model.Jenkins;
31 import hudson.remoting.AsyncFutureImpl;
32 import hudson.remoting.Callable;
33 import hudson.remoting.DelegatingCallable;
34 import hudson.remoting.Future;
35 import hudson.remoting.VirtualChannel;
36 import hudson.security.AccessControlled;
37 import org.codehaus.groovy.control.CompilerConfiguration;
38 import org.codehaus.groovy.control.customizers.ImportCustomizer;
39 import org.kohsuke.stapler.StaplerRequest;
40 import org.kohsuke.stapler.StaplerResponse;
41 import org.kohsuke.stapler.WebMethod;
42
43 import javax.management.JMException;
44 import javax.management.MBeanServer;
45 import javax.management.ObjectName;
46 import java.io.File;
47 import java.io.IOException;
48 import java.io.PrintWriter;
49 import java.io.StringWriter;
50 import java.lang.management.ManagementFactory;
51 import java.lang.management.ThreadInfo;
52 import java.util.Collections;
53 import java.util.LinkedHashMap;
54 import java.util.Map;
55 import java.util.TreeMap;
56
57 /**
58 * Various remoting operations related to diagnostics.
59 *
60 * <p>
61 * These code are useful wherever {@link VirtualChannel} is used, such as master, slaves, Maven JVMs, etc.
62 *
63 * @author Kohsuke Kawaguchi
64 * @since 1.175
65 */
66 public final class RemotingDiagnostics {
67 public static Map<Object,Object> getSystemProperties(VirtualChannel channel) throws IOException, InterruptedException {
68 if(channel==null)
69 return Collections.<Object,Object>singletonMap("N/A","N/A");
70 return channel.call(new GetSystemProperties());
71 }
72
73 private static final class GetSystemProperties implements Callable<Map<Object,Object>,RuntimeException> {
74 public Map<Object,Object> call() {
75 return new TreeMap<Object,Object>(System.getProperties());
76 }
77 private static final long serialVersionUID = 1L;
78 }
79
80 public static Map<String,String> getThreadDump(VirtualChannel channel) throws IOException, InterruptedException {
81 if(channel==null)
82 return Collections.singletonMap("N/A","N/A");
83 return channel.call(new GetThreadDump());
84 }
85
86 public static Future<Map<String,String>> getThreadDumpAsync(VirtualChannel channel) throws IOException, InterruptedException {
87 if(channel==null)
88 return new AsyncFutureImpl<Map<String, String>>(Collections.singletonMap("N/A","offline"));
89 return channel.callAsync(new GetThreadDump());
90 }
91
92 private static final class GetThreadDump implements Callable<Map<String,String>,RuntimeException> {
93 public Map<String,String> call() {
94 Map<String,String> r = new LinkedHashMap<String,String>();
95 try {
96 ThreadInfo[] data = Functions.getThreadInfos();
97 Functions.ThreadGroupMap map = Functions.sortThreadsAndGetGroupMap(data);
98 for (ThreadInfo ti : data)
99 r.put(ti.getThreadName(),Functions.dumpThreadInfo(ti,map));
100 } catch (LinkageError _) {
101 // not in JDK6. fall back to JDK5
102 r.clear();
103 for (Map.Entry<Thread,StackTraceElement[]> t : Functions.dumpAllThreads().entrySet()) {
104 StringBuilder buf = new StringBuilder();
105 for (StackTraceElement e : t.getValue())
106 buf.append(e).append('\n');
107 r.put(t.getKey().getName(),buf.toString());
108 }
109 }
110 return r;
111 }
112 private static final long serialVersionUID = 1L;
113 }
114
115 /**
116 * Executes Groovy script remotely.
117 */
118 public static String executeGroovy(String script, VirtualChannel channel) throws IOException, InterruptedException {
119 return channel.call(new Script(script));
120 }
121
122 private static final class Script implements DelegatingCallable<String,RuntimeException> {
123 private final String script;
124 private transient ClassLoader cl;
125
126 private Script(String script) {
127 this.script = script;
128 cl = getClassLoader();
129 }
130
131 public ClassLoader getClassLoader() {
132 return Jenkins.getInstance().getPluginManager().uberClassLoader;
133 }
134
135 public String call() throws RuntimeException {
136 // if we run locally, cl!=null. Otherwise the delegating classloader will be available as context classloader.
137 if (cl==null) cl = Thread.currentThread().getContextClassLoader();
138 CompilerConfiguration cc = new CompilerConfiguration();
139 cc.addCompilationCustomizers(new ImportCustomizer().addStarImports(
140 "jenkins",
141 "jenkins.model",
142 "hudson",
143 "hudson.model"));
144 GroovyShell shell = new GroovyShell(cl,new Binding(),cc);
145
146 StringWriter out = new StringWriter();
147 PrintWriter pw = new PrintWriter(out);
148 shell.setVariable("out", pw);
149 try {
150 Object output = shell.evaluate(script);
151 if(output!=null)
152 pw.println("Result: "+output);
153 } catch (Throwable t) {
154 t.printStackTrace(pw);
155 }
156 return out.toString();
157 }
158 }
159
160 /**
161 * Obtains the heap dump in an HPROF file.
162 */
163 public static FilePath getHeapDump(VirtualChannel channel) throws IOException, InterruptedException {
164 return channel.call(new Callable<FilePath, IOException>() {
165 public FilePath call() throws IOException {
166 final File hprof = File.createTempFile("hudson-heapdump", "hprof");
167 hprof.delete();
168 try {
169 MBeanServer server = ManagementFactory.getPlatformMBeanServer();
170 server.invoke(new ObjectName("com.sun.management:type=HotSpotDiagnostic"), "dumpHeap",
171 new Object[]{hprof.getAbsolutePath(), true}, new String[]{String.class.getName(), boolean.class.getName()});
172
173 return new FilePath(hprof);
174 } catch (JMException e) {
175 throw new IOException2(e);
176 }
177 }
178
179 private static final long serialVersionUID = 1L;
180 });
181 }
182
183 /**
184 * Heap dump, exposable to URL via Stapler.
185 *
186 */
187 public static class HeapDump {
188 private final AccessControlled owner;
189 private final VirtualChannel channel;
190
191 public HeapDump(AccessControlled owner, VirtualChannel channel) {
192 this.owner = owner;
193 this.channel = channel;
194 }
195
196 /**
197 * Obtains the heap dump.
198 */
199 public void doIndex(StaplerResponse rsp) throws IOException {
200 rsp.sendRedirect("heapdump.hprof");
201 }
202
203 @WebMethod(name="heapdump.hprof")
204 public void doHeapDump(StaplerRequest req, StaplerResponse rsp) throws IOException, InterruptedException {
205 owner.checkPermission(Jenkins.ADMINISTER);
206 rsp.setContentType("application/octet-stream");
207
208 FilePath dump = obtain();
209 try {
210 dump.copyTo(rsp.getCompressedOutputStream(req));
211 } finally {
212 dump.delete();
213 }
214 }
215
216 public FilePath obtain() throws IOException, InterruptedException {
217 return RemotingDiagnostics.getHeapDump(channel);
218 }
219 }
220 }
221