-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathBenchmark.java
More file actions
405 lines (357 loc) · 13.6 KB
/
Benchmark.java
File metadata and controls
405 lines (357 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package jdiskmark;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Convert;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityManager;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import java.io.IOException;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import jakarta.persistence.Enumerated;
import jakarta.persistence.EnumType;
import java.util.UUID;
/**
* A read or write benchmark
*/
@Entity
@Table(name="Benchmark")
@NamedQueries({
@NamedQuery(name="Benchmark.findAll",
query="SELECT b FROM Benchmark b JOIN FETCH b.operations")
})
public class Benchmark implements Serializable {
static final DecimalFormat DF = new DecimalFormat("###.##");
static final DecimalFormat DFT = new DecimalFormat("###");
static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public enum BenchmarkType {
READ {
@Override
public String toString() { return "Read"; }
},
WRITE {
@Override
public String toString() { return "Write"; }
},
READ_WRITE {
@Override
public String toString() { return "Read & Write"; }
}
}
public enum IOMode {
READ {
@Override
public String toString() { return "Read"; }
},
WRITE {
@Override
public String toString() { return "Write"; }
}
}
public enum BlockSequence {
SEQUENTIAL {
@Override
public String toString() { return "Sequential"; }
},
RANDOM {
@Override
public String toString() { return "Random"; }
}
}
/**
* Jackson custom serializer to convert the Java UUID into a plain string.
*
* IMPORTANT NOTE on UUID vs ObjectId:
* - UUID is a 16-byte value (36-character string representation).
* - MongoDB ObjectId is a 12-byte value (24-character hex string).
* Since they are different lengths and structures, a direct conversion
* is non-standard. The industry best practice for external clients sending
* their own primary key is to send the UUID as a simple string, and the MERN
* backend will store it as the document's _id (usually as a string, not a native ObjectId object).
* This serializer performs that essential conversion.
*/
public static class UuidToMongoIdSerializer extends JsonSerializer<UUID> {
@Override
public void serialize(UUID value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (value == null) {
gen.writeNull();
} else {
// Serializes the UUID into its standard string representation.
// Example: "a1b2c3d4-e5f6-7890-1234-567890abcdef"
gen.writeString(value.toString());
}
}
}
// surrogate key
/**
* The unique identifier for this benchmark run.
* Mapped as the primary key for JPA/Derby.
* The GenerationType.UUID tells JPA to use the database's UUID generation
* mechanism (or an equivalent strategy provided by the JPA vendor).
*/
@Id
@GeneratedValue(strategy = GenerationType.UUID)
// --- JSON Serialization for MERN App ---
/**
* @JsonProperty("_id"): Ensures that when this object is serialized to JSON,
* the key name for this field is "_id", matching the standard MongoDB primary key convention.
*
* @JsonSerialize(using = UuidToMongoIdSerializer.class): Tells Jackson to use
* our custom inner class serializer to handle the conversion logic of UUID -> JSON string.
*/
@JsonProperty("_id")
@JsonSerialize(using = UuidToMongoIdSerializer.class)
private UUID id;
// user account
@Column
String username = "anonymous"; // "user" is reserved in Derby
public String getUsername() { return username; }
// system data
@Column
String os;
public String getOs() { return os; }
@Column
String arch;
public String getArch() { return arch; }
@Column
String processorName;
public String getProcessorName() { return processorName; }
@Column
String jdk;
public String getJdk() { return jdk; }
@Column
String locationDir;
public String getLocationDir() { return locationDir; }
// drive info
@Column
String driveModel = null;
public String getDriveModel() { return driveModel; }
@Column
String partitionId; // on windows the drive letter
public String getPartitionId() { return partitionId; }
@Column
long percentUsed;
public long getPercentUsed() { return percentUsed; }
@Column
double usedGb;
public double getUsedGb() { return usedGb; }
@Column
double totalGb;
public double getTotalGb() { return totalGb; }
// benchmark configuration
// app version performing the benchmark
@Column
String appVersion;
public String getAppVersion() { return appVersion; }
// name of the profile used
@Column
String profileName;
public String getProfileName() { return profileName; }
// benchmark parameters
@Column
BenchmarkType benchmarkType;
public BenchmarkType getBenchmarkType() { return benchmarkType; }
public enum CachePurgeMethod {
NONE,
DROP_CACHE,
SOFT_PURGE;
@Override
public String toString() {
return switch (this) {
case DROP_CACHE -> "Drop Cache (OS Flush)";
case SOFT_PURGE -> "Soft Purge (Read-Through)";
case NONE -> "None";
};
}
}
// ---------------------------------------------------
// Cache purge metadata (for read-after-write benchmarks)
// ---------------------------------------------------
@Column
boolean cachePurgePerformed;
@Column
long cachePurgeSizeBytes;
@Column
long cachePurgeDurationMs;
@Column
@Enumerated(EnumType.STRING)
CachePurgeMethod cachePurgeMethod;
// timestamps
@Convert(converter = LocalDateTimeAttributeConverter.class)
@Column(name = "startTime", columnDefinition = "TIMESTAMP")
LocalDateTime startTime;
@Convert(converter = LocalDateTimeAttributeConverter.class)
@Column
LocalDateTime endTime = null;
@OneToMany(mappedBy = "benchmark", cascade = CascadeType.ALL, orphanRemoval = true)
List<BenchmarkOperation> operations = new ArrayList<>();
public List<BenchmarkOperation> getOperations() {
return operations;
}
// get the first operation of that type
public BenchmarkOperation getOperation(IOMode mode) {
for (BenchmarkOperation operation : operations) {
if (operation.ioMode == mode) {
return operation;
}
}
return null;
}
@Override
public String toString() {
return "Benchmark(" + benchmarkType + ") start=" + startTime + "numOps=" + operations.size();
}
/**
* Use for command line output
* @return the result string
*/
public String toResultString() {
StringBuilder sb = new StringBuilder();
sb.append("\n");
sb.append("-------------------------------------------\n");
sb.append("JDiskMark Benchmark Results (v").append(App.VERSION).append(")\n");
sb.append("-------------------------------------------\n");
sb.append("Benchmark: ").append(benchmarkType).append("\n");
sb.append("Drive: ").append(App.getDriveModel()).append("\n");
sb.append("Capacity: ").append(App.getDriveCapacity()).append("\n");
sb.append("Timestamp: ").append(startTime).append("\n");
sb.append("CPU: ").append(processorName).append("\n");
sb.append("System: ").append(os).append(" / ").append((arch)).append("\n");
sb.append("Java: ").append(jdk).append("\n");
sb.append("Path: ").append(locationDir).append("\n");
for (BenchmarkOperation o : operations) {
sb.append("-------------------------------------------\n");
sb.append("Order: ").append(o.blockOrder).append("\n");
sb.append("IOMode: ").append(o.ioMode).append("\n");
sb.append("Thread(s): ").append(o.numThreads).append("\n");
sb.append("Blocks(size): ").append(o.numBlocks).append("(").append(o.blockSize).append(")").append("\n");
sb.append("Samples: ").append(o.numSamples).append("\n");
sb.append("TxSize(KB): ").append(o.txSize).append("\n");
sb.append("Speed(MB/s): ").append(DF.format(o.bwAvg)).append("\n");
sb.append("SpeedMin(MB/s): ").append(DF.format(o.bwMin)).append("\n");
sb.append("SpeedMax(MB/s): ").append(DF.format(o.bwMax)).append("\n");
sb.append("Latency(ms): ").append(DF.format(o.accAvg)).append("\n");
sb.append("IOPS: ").append(o.iops).append("\n");
}
sb.append("-------------------------------------------\n");
return sb.toString();
}
public Benchmark() {
startTime = LocalDateTime.now();
cachePurgePerformed = false;
cachePurgeSizeBytes = 0L;
cachePurgeDurationMs = 0L;
cachePurgeMethod = CachePurgeMethod.NONE;
appVersion = App.VERSION;
profileName = App.activeProfile.getName();
}
Benchmark(BenchmarkType type) {
startTime = LocalDateTime.now();
benchmarkType = type;
cachePurgePerformed = false;
cachePurgeSizeBytes = 0L;
cachePurgeDurationMs = 0L;
cachePurgeMethod = CachePurgeMethod.NONE;
appVersion = App.VERSION;
profileName = App.activeProfile.getName();
}
// basic getters and setters
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getDriveInfo() {
return driveModel + " - " + partitionId + ": " + getUsageTitleDisplay();
}
public String getUsageTitleDisplay() {
return percentUsed + "% (" + DFT.format(usedGb) + "/" + DFT.format(totalGb) + " GB)";
}
public String getUsageColumnDisplay() {
return percentUsed + "%";
}
public String getStartTimeString() {
return startTime.format(DATE_FORMAT);
}
public String getDuration() {
if (endTime == null) {
return "unknown";
}
long diffMs = Duration.between(startTime, endTime).toMillis();
return String.valueOf(diffMs);
}
// cache purge getters (for UI / JSON)
public boolean isCachePurgePerformed() {
return cachePurgePerformed;
}
public long getCachePurgeSizeBytes() {
return cachePurgeSizeBytes;
}
public long getCachePurgeDurationMs() {
return cachePurgeDurationMs;
}
public CachePurgeMethod getCachePurgeMethod() {
return cachePurgeMethod;
}
// utility methods for collection
@JsonIgnore
static List<Benchmark> findAll() {
EntityManager em = EM.getEntityManager();
return em.createNamedQuery("Benchmark.findAll", Benchmark.class).getResultList();
}
@JsonIgnore
static int deleteAll() {
EntityManager em = EM.getEntityManager();
em.getTransaction().begin();
int deletedOperationsCount = em.createQuery("DELETE FROM BenchmarkOperation").executeUpdate();
int deletedBenchmarksCount = em.createQuery("DELETE FROM Benchmark").executeUpdate();
if (App.verbose) {
App.msg("deletedOperations=" + deletedOperationsCount);
App.msg("deletedBenchmarks=" + deletedBenchmarksCount);
}
em.getTransaction().commit();
return deletedBenchmarksCount;
}
@JsonIgnore
static int delete(List<UUID> benchmarkIds) {
if (benchmarkIds.isEmpty()) {
return 0;
}
EntityManager em = EM.getEntityManager();
em.getTransaction().begin();
// delete the child BenchmarkOperation records.
String deleteOperationsJpql = "DELETE FROM BenchmarkOperation bo WHERE bo.benchmark.id IN :benchmarkIds";
int deletedOperationsCount = em.createQuery(deleteOperationsJpql)
.setParameter("benchmarkIds", benchmarkIds)
.executeUpdate();
// delete the parent Benchmark records
String deleteBenchmarksJpql = "DELETE FROM Benchmark b WHERE b.id IN :benchmarkIds";
int deletedBenchmarksCount = em.createQuery(deleteBenchmarksJpql)
.setParameter("benchmarkIds", benchmarkIds)
.executeUpdate();
if (App.verbose) {
App.msg("deletedOperations=" + deletedOperationsCount);
App.msg("deletedBenchmarks=" + deletedBenchmarksCount);
}
em.getTransaction().commit();
return deletedBenchmarksCount;
}
}