1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.giraph.utils;
20
21 import org.apache.hadoop.mapreduce.Mapper;
22 import org.apache.log4j.Logger;
23
24 import com.google.common.base.Joiner;
25 import com.google.common.io.Files;
26 import com.yourkit.api.Controller;
27 import com.yourkit.api.ProfilingModes;
28
29 import java.io.File;
30 import java.io.IOException;
31
32
33
34
35
36 public class YourKitContext {
37
38 private static final Logger LOG = Logger.getLogger(YourKitContext.class);
39
40
41 private static Joiner SLASH_JOINER = Joiner.on("/");
42
43
44 private final Controller yourKitController;
45
46
47
48
49
50 YourKitContext(Controller yourKitController) {
51 this.yourKitController = yourKitController;
52 }
53
54
55
56
57
58
59 private void snapshot(long flags, String destPath) {
60 if (yourKitController != null) {
61 String path;
62 try {
63 path = yourKitController.captureSnapshot(flags);
64
65 } catch (Exception e) {
66
67 return;
68 }
69 try {
70 File destFile = new File(destPath);
71 Files.createParentDirs(destFile);
72 Files.move(new File(path), destFile);
73 } catch (IOException e) {
74 LOG.error("Failed to move YourKit snapshot file from " + path +
75 " to " + destPath, e);
76 }
77 }
78 }
79
80
81
82
83
84
85
86
87 public void snapshotWithMemory(String destPath) {
88 snapshot(ProfilingModes.SNAPSHOT_WITH_HEAP, destPath);
89 }
90
91
92
93
94
95
96
97
98
99
100 public void snapshotWithMemory(Mapper.Context context, String name) {
101 snapshot(ProfilingModes.SNAPSHOT_WITH_HEAP,
102 SLASH_JOINER.join(System.getProperty("hadoop.log.dir", "/tmp"),
103 "userlogs", context.getTaskAttemptID(), name + ".snapshot"));
104 }
105
106
107
108
109
110
111 public void snapshotCPUOnly(String destPath) {
112 snapshot(ProfilingModes.SNAPSHOT_WITHOUT_HEAP, destPath);
113 }
114
115
116
117
118
119
120
121
122 public void snapshotCPUOnly(Mapper.Context context, String name) {
123 snapshot(ProfilingModes.SNAPSHOT_WITHOUT_HEAP,
124 SLASH_JOINER.join(System.getProperty("hadoop.log.dir", "/tmp"),
125 "userlogs", context.getTaskAttemptID(), name + ".snapshot"));
126 }
127
128
129
130
131 public void stop() {
132 if (yourKitController != null) {
133 try {
134 yourKitController.disableStackTelemetry();
135 LOG.info("Disabled YourKit stack telemetry");
136
137 } catch (Exception e) {
138
139 LOG.error("Failed to stop stack telemetry", e);
140 }
141
142 try {
143 yourKitController.stopCPUProfiling();
144 LOG.info("Stopped Yourkit CPU profiling");
145
146 } catch (Exception e) {
147
148 LOG.error("Failed to stop YourKit profiling", e);
149 }
150
151 try {
152 yourKitController.stopAllocationRecording();
153 LOG.info("Stopped Yourkit allocation recording");
154
155 } catch (Exception e) {
156
157 LOG.error("Failed to stop YourKit allocation recording", e);
158 }
159 }
160 }
161 }