0
# Profiling Services
1
2
The SkyWalking profiling system provides distributed performance profiling capabilities for Java applications, including trace-based profiling, thread snapshots, and performance analysis. It enables detailed method-level performance monitoring with minimal overhead.
3
4
## Core Profiling Services
5
6
### ProfileTaskQueryService
7
8
Service for querying profiling tasks and retrieving profiling results.
9
10
```java { .api }
11
public class ProfileTaskQueryService implements Service {
12
13
/**
14
* Queries profiling tasks with pagination and filtering
15
* @param serviceId Service identifier to filter tasks
16
* @param endpointName Endpoint name filter (optional)
17
* @param startTimeBucket Start time bucket for task query
18
* @param endTimeBucket End time bucket for task query
19
* @param paging Pagination configuration
20
* @return Paginated list of profiling tasks
21
* @throws IOException If query fails
22
*/
23
public ProfileTaskList getTaskList(String serviceId, String endpointName,
24
long startTimeBucket, long endTimeBucket,
25
Pagination paging) throws IOException;
26
27
/**
28
* Gets detailed information about specific profiling task
29
* @param taskId Profiling task identifier
30
* @return Detailed task information
31
* @throws IOException If query fails
32
*/
33
public ProfileTask getTaskDetail(String taskId) throws IOException;
34
35
/**
36
* Gets profiling task logs for monitoring task execution
37
* @param taskId Profiling task identifier
38
* @param paging Pagination configuration
39
* @return Paginated task execution logs
40
* @throws IOException If query fails
41
*/
42
public ProfileTaskLogList getTaskLogs(String taskId, Pagination paging) throws IOException;
43
44
/**
45
* Gets thread snapshots for profiling task
46
* @param taskId Profiling task identifier
47
* @param segmentId Trace segment identifier
48
* @param paging Pagination configuration
49
* @return List of thread snapshots
50
* @throws IOException If query fails
51
*/
52
public List<ProfiledSegment> getProfiledSegments(String taskId, String segmentId,
53
Pagination paging) throws IOException;
54
55
/**
56
* Analyzes thread snapshots to generate profiling tree
57
* @param segmentId Trace segment identifier
58
* @param timeRanges Time ranges within segment for analysis
59
* @return Profiling analysis tree with method call hierarchy
60
* @throws IOException If analysis fails
61
*/
62
public ProfileAnalyzeTimeRange getProfileAnalyzeTimeRange(String segmentId,
63
List<ProfileAnalyzeTimeRange> timeRanges)
64
throws IOException;
65
66
/**
67
* Gets thread snapshot details for specific time range
68
* @param segmentId Trace segment identifier
69
* @param threadId Thread identifier
70
* @param startTime Start time for snapshot range
71
* @param endTime End time for snapshot range
72
* @return Thread snapshot data
73
* @throws IOException If query fails
74
*/
75
public List<ThreadSnapshot> getThreadSnapshots(String segmentId, String threadId,
76
long startTime, long endTime) throws IOException;
77
}
78
```
79
80
### ProfileTaskMutationService
81
82
Service for creating and managing profiling tasks.
83
84
```java { .api }
85
public class ProfileTaskMutationService implements Service {
86
87
/**
88
* Creates new profiling task
89
* @param creationRequest Profiling task creation parameters
90
* @return Created task result with task ID
91
* @throws IOException If task creation fails
92
*/
93
public ProfileTaskCreationResult createTask(ProfileTaskCreationRequest creationRequest)
94
throws IOException;
95
96
/**
97
* Gets profiling task creation result by request ID
98
* @param requestId Task creation request identifier
99
* @return Task creation result
100
* @throws IOException If query fails
101
*/
102
public ProfileTaskCreationResult getTaskCreationResult(String requestId) throws IOException;
103
104
/**
105
* Cancels active profiling task
106
* @param taskId Profiling task identifier to cancel
107
* @return Cancellation result
108
* @throws IOException If cancellation fails
109
*/
110
public ProfileTaskCancellationResult cancelTask(String taskId) throws IOException;
111
112
/**
113
* Updates profiling task configuration
114
* @param taskId Profiling task identifier
115
* @param updateRequest Task update parameters
116
* @return Update result
117
* @throws IOException If update fails
118
*/
119
public ProfileTaskUpdateResult updateTask(String taskId, ProfileTaskUpdateRequest updateRequest)
120
throws IOException;
121
122
/**
123
* Validates profiling task parameters before creation
124
* @param request Task creation request to validate
125
* @return Validation result with error messages if invalid
126
*/
127
public ProfileTaskValidationResult validateTaskRequest(ProfileTaskCreationRequest request);
128
129
/**
130
* Gets profiling task statistics
131
* @param taskId Profiling task identifier
132
* @return Task execution statistics
133
* @throws IOException If query fails
134
*/
135
public ProfileTaskStats getTaskStats(String taskId) throws IOException;
136
}
137
```
138
139
## Profiling Data Models
140
141
### ProfileTaskRecord
142
143
Storage record for profiling task metadata and configuration.
144
145
```java { .api }
146
public class ProfileTaskRecord extends Record {
147
148
@Column(name = "task_id", dataType = Column.ValueDataType.VARCHAR, length = 255)
149
@Getter @Setter
150
private String taskId;
151
152
@Column(name = "service_id", dataType = Column.ValueDataType.VARCHAR, length = 255)
153
@Getter @Setter
154
private String serviceId;
155
156
@Column(name = "endpoint_name", dataType = Column.ValueDataType.VARCHAR, length = 512)
157
@Getter @Setter
158
private String endpointName;
159
160
@Column(name = "start_time", dataType = Column.ValueDataType.BIGINT)
161
@Getter @Setter
162
private long startTime;
163
164
@Column(name = "create_time", dataType = Column.ValueDataType.BIGINT)
165
@Getter @Setter
166
private long createTime;
167
168
@Column(name = "duration", dataType = Column.ValueDataType.INT)
169
@Getter @Setter
170
private int duration;
171
172
@Column(name = "min_duration_threshold", dataType = Column.ValueDataType.INT)
173
@Getter @Setter
174
private int minDurationThreshold;
175
176
@Column(name = "dump_period", dataType = Column.ValueDataType.INT)
177
@Getter @Setter
178
private int dumpPeriod;
179
180
@Column(name = "max_sampling_count", dataType = Column.ValueDataType.INT)
181
@Getter @Setter
182
private int maxSamplingCount;
183
184
@Override
185
public StorageID id();
186
187
public static class Builder implements StorageBuilder<ProfileTaskRecord> {
188
@Override
189
public ProfileTaskRecord storage2Entity(Convert2Entity converter);
190
191
@Override
192
public void entity2Storage(ProfileTaskRecord storageData, Convert2Storage converter);
193
}
194
}
195
```
196
197
### ProfileThreadSnapshotRecord
198
199
Storage record for thread profiling snapshots.
200
201
```java { .api }
202
public class ProfileThreadSnapshotRecord extends Record {
203
204
@Column(name = "task_id", dataType = Column.ValueDataType.VARCHAR, length = 255)
205
@Getter @Setter
206
private String taskId;
207
208
@Column(name = "segment_id", dataType = Column.ValueDataType.VARCHAR, length = 255)
209
@Getter @Setter
210
private String segmentId;
211
212
@Column(name = "dump_time", dataType = Column.ValueDataType.BIGINT)
213
@Getter @Setter
214
private long dumpTime;
215
216
@Column(name = "sequence", dataType = Column.ValueDataType.INT)
217
@Getter @Setter
218
private int sequence;
219
220
@Column(name = "stack_binary", dataType = Column.ValueDataType.SAMPLED_RECORD)
221
@Getter @Setter
222
private byte[] stackBinary;
223
224
@Override
225
public StorageID id();
226
227
/**
228
* Deserializes stack trace from binary data
229
* @return Thread stack trace
230
* @throws IOException If deserialization fails
231
*/
232
public ThreadStack deserializeStack() throws IOException;
233
234
/**
235
* Serializes stack trace to binary data
236
* @param stack Thread stack trace to serialize
237
* @throws IOException If serialization fails
238
*/
239
public void serializeStack(ThreadStack stack) throws IOException;
240
241
public static class Builder implements StorageBuilder<ProfileThreadSnapshotRecord> {
242
@Override
243
public ProfileThreadSnapshotRecord storage2Entity(Convert2Entity converter);
244
245
@Override
246
public void entity2Storage(ProfileThreadSnapshotRecord storageData, Convert2Storage converter);
247
}
248
}
249
```
250
251
## Profiling Request Types
252
253
### ProfileTaskCreationRequest
254
255
Request parameters for creating new profiling tasks.
256
257
```java { .api }
258
public class ProfileTaskCreationRequest {
259
260
private String serviceId;
261
private List<String> endpointNames;
262
private int duration;
263
private int minDurationThreshold;
264
private int dumpPeriod;
265
private int maxSamplingCount;
266
private String requestId;
267
268
/**
269
* Gets service identifier for profiling
270
* @return Service ID
271
*/
272
public String getServiceId();
273
274
/**
275
* Sets service identifier for profiling
276
* @param serviceId Service ID
277
*/
278
public void setServiceId(String serviceId);
279
280
/**
281
* Gets endpoint names to profile
282
* @return List of endpoint names
283
*/
284
public List<String> getEndpointNames();
285
286
/**
287
* Sets endpoint names to profile
288
* @param endpointNames List of endpoint names
289
*/
290
public void setEndpointNames(List<String> endpointNames);
291
292
/**
293
* Gets profiling duration in minutes
294
* @return Duration in minutes
295
*/
296
public int getDuration();
297
298
/**
299
* Sets profiling duration in minutes
300
* @param duration Duration in minutes (max 10 minutes)
301
*/
302
public void setDuration(int duration);
303
304
/**
305
* Gets minimum trace duration threshold for profiling
306
* @return Minimum duration in milliseconds
307
*/
308
public int getMinDurationThreshold();
309
310
/**
311
* Sets minimum trace duration threshold for profiling
312
* @param minDurationThreshold Minimum duration in milliseconds
313
*/
314
public void setMinDurationThreshold(int minDurationThreshold);
315
316
/**
317
* Gets thread dump period interval
318
* @return Dump period in milliseconds
319
*/
320
public int getDumpPeriod();
321
322
/**
323
* Sets thread dump period interval
324
* @param dumpPeriod Dump period in milliseconds (default 10ms)
325
*/
326
public void setDumpPeriod(int dumpPeriod);
327
328
/**
329
* Gets maximum sampling count per endpoint
330
* @return Maximum sampling count
331
*/
332
public int getMaxSamplingCount();
333
334
/**
335
* Sets maximum sampling count per endpoint
336
* @param maxSamplingCount Maximum sampling count (default 5)
337
*/
338
public void setMaxSamplingCount(int maxSamplingCount);
339
340
/**
341
* Gets unique request identifier
342
* @return Request ID
343
*/
344
public String getRequestId();
345
346
/**
347
* Sets unique request identifier
348
* @param requestId Request ID for tracking
349
*/
350
public void setRequestId(String requestId);
351
}
352
```
353
354
### ProfileTaskUpdateRequest
355
356
Request parameters for updating existing profiling tasks.
357
358
```java { .api }
359
public class ProfileTaskUpdateRequest {
360
361
private Integer duration;
362
private Integer minDurationThreshold;
363
private Integer maxSamplingCount;
364
365
/**
366
* Gets updated duration (null if no change)
367
* @return Duration in minutes or null
368
*/
369
public Integer getDuration();
370
371
/**
372
* Sets updated duration
373
* @param duration Duration in minutes
374
*/
375
public void setDuration(Integer duration);
376
377
/**
378
* Gets updated minimum duration threshold (null if no change)
379
* @return Minimum duration in milliseconds or null
380
*/
381
public Integer getMinDurationThreshold();
382
383
/**
384
* Sets updated minimum duration threshold
385
* @param minDurationThreshold Minimum duration in milliseconds
386
*/
387
public void setMinDurationThreshold(Integer minDurationThreshold);
388
389
/**
390
* Gets updated maximum sampling count (null if no change)
391
* @return Maximum sampling count or null
392
*/
393
public Integer getMaxSamplingCount();
394
395
/**
396
* Sets updated maximum sampling count
397
* @param maxSamplingCount Maximum sampling count
398
*/
399
public void setMaxSamplingCount(Integer maxSamplingCount);
400
}
401
```
402
403
## Profiling Result Types
404
405
### ProfileTask
406
407
Complete profiling task information with status and results.
408
409
```java { .api }
410
public class ProfileTask {
411
412
private String taskId;
413
private String serviceId;
414
private String serviceName;
415
private List<String> endpointNames;
416
private long createTime;
417
private long startTime;
418
private int duration;
419
private int minDurationThreshold;
420
private int dumpPeriod;
421
private int maxSamplingCount;
422
private ProfileTaskStatus status;
423
private String errorReason;
424
private List<ProfileTaskLog> logs;
425
426
/**
427
* Gets task identifier
428
* @return Task ID
429
*/
430
public String getTaskId();
431
432
/**
433
* Gets service identifier
434
* @return Service ID
435
*/
436
public String getServiceId();
437
438
/**
439
* Gets service name
440
* @return Service name
441
*/
442
public String getServiceName();
443
444
/**
445
* Gets profiled endpoint names
446
* @return List of endpoint names
447
*/
448
public List<String> getEndpointNames();
449
450
/**
451
* Gets task creation timestamp
452
* @return Creation time in milliseconds
453
*/
454
public long getCreateTime();
455
456
/**
457
* Gets task start timestamp
458
* @return Start time in milliseconds
459
*/
460
public long getStartTime();
461
462
/**
463
* Gets profiling duration
464
* @return Duration in minutes
465
*/
466
public int getDuration();
467
468
/**
469
* Gets task status
470
* @return Current task status
471
*/
472
public ProfileTaskStatus getStatus();
473
474
/**
475
* Gets error reason if task failed
476
* @return Error message or null if successful
477
*/
478
public String getErrorReason();
479
480
/**
481
* Gets task execution logs
482
* @return List of task logs
483
*/
484
public List<ProfileTaskLog> getLogs();
485
486
/**
487
* Checks if task is currently active
488
* @return True if task is running
489
*/
490
public boolean isActive();
491
492
/**
493
* Checks if task completed successfully
494
* @return True if task finished without errors
495
*/
496
public boolean isCompleted();
497
498
/**
499
* Gets estimated completion time
500
* @return Estimated completion timestamp or -1 if not applicable
501
*/
502
public long getEstimatedCompletionTime();
503
}
504
```
505
506
### ProfiledSegment
507
508
Profiled trace segment with thread snapshots and analysis.
509
510
```java { .api }
511
public class ProfiledSegment {
512
513
private String segmentId;
514
private String traceId;
515
private List<String> endpointNames;
516
private int duration;
517
private long startTime;
518
private long endTime;
519
private List<ThreadSnapshot> snapshots;
520
private ProfileAnalysis analysis;
521
522
/**
523
* Gets trace segment identifier
524
* @return Segment ID
525
*/
526
public String getSegmentId();
527
528
/**
529
* Gets trace identifier
530
* @return Trace ID
531
*/
532
public String getTraceId();
533
534
/**
535
* Gets endpoint names in segment
536
* @return List of endpoint names
537
*/
538
public List<String> getEndpointNames();
539
540
/**
541
* Gets segment duration
542
* @return Duration in milliseconds
543
*/
544
public int getDuration();
545
546
/**
547
* Gets segment start time
548
* @return Start timestamp in milliseconds
549
*/
550
public long getStartTime();
551
552
/**
553
* Gets segment end time
554
* @return End timestamp in milliseconds
555
*/
556
public long getEndTime();
557
558
/**
559
* Gets thread snapshots for this segment
560
* @return List of thread snapshots
561
*/
562
public List<ThreadSnapshot> getSnapshots();
563
564
/**
565
* Gets profiling analysis results
566
* @return Profile analysis or null if not analyzed
567
*/
568
public ProfileAnalysis getAnalysis();
569
570
/**
571
* Gets snapshot count
572
* @return Number of thread snapshots
573
*/
574
public int getSnapshotCount();
575
}
576
```
577
578
### ThreadSnapshot
579
580
Individual thread stack snapshot at specific time point.
581
582
```java { .api }
583
public class ThreadSnapshot {
584
585
private String taskId;
586
private String segmentId;
587
private long dumpTime;
588
private int sequence;
589
private ThreadStack stack;
590
591
/**
592
* Gets profiling task identifier
593
* @return Task ID
594
*/
595
public String getTaskId();
596
597
/**
598
* Gets trace segment identifier
599
* @return Segment ID
600
*/
601
public String getSegmentId();
602
603
/**
604
* Gets snapshot dump time
605
* @return Dump timestamp in milliseconds
606
*/
607
public long getDumpTime();
608
609
/**
610
* Gets snapshot sequence number within segment
611
* @return Sequence number
612
*/
613
public int getSequence();
614
615
/**
616
* Gets thread stack trace
617
* @return Thread stack information
618
*/
619
public ThreadStack getStack();
620
621
/**
622
* Sets thread stack trace
623
* @param stack Thread stack information
624
*/
625
public void setStack(ThreadStack stack);
626
}
627
```
628
629
### ThreadStack
630
631
Thread stack trace information with method call hierarchy.
632
633
```java { .api }
634
public class ThreadStack {
635
636
private String threadName;
637
private String threadId;
638
private List<StackElement> elements;
639
640
/**
641
* Gets thread name
642
* @return Thread name
643
*/
644
public String getThreadName();
645
646
/**
647
* Sets thread name
648
* @param threadName Thread name
649
*/
650
public void setThreadName(String threadName);
651
652
/**
653
* Gets thread identifier
654
* @return Thread ID
655
*/
656
public String getThreadId();
657
658
/**
659
* Sets thread identifier
660
* @param threadId Thread ID
661
*/
662
public void setThreadId(String threadId);
663
664
/**
665
* Gets stack trace elements
666
* @return List of stack elements (bottom to top)
667
*/
668
public List<StackElement> getElements();
669
670
/**
671
* Sets stack trace elements
672
* @param elements List of stack elements
673
*/
674
public void setElements(List<StackElement> elements);
675
676
/**
677
* Gets stack depth
678
* @return Number of stack elements
679
*/
680
public int getDepth();
681
682
/**
683
* Gets top stack element (current method)
684
* @return Top stack element or null if empty
685
*/
686
public StackElement getTopElement();
687
}
688
```
689
690
### StackElement
691
692
Individual method call in thread stack trace.
693
694
```java { .api }
695
public class StackElement {
696
697
private String className;
698
private String methodName;
699
private String fileName;
700
private int lineNumber;
701
702
/**
703
* Gets class name
704
* @return Fully qualified class name
705
*/
706
public String getClassName();
707
708
/**
709
* Sets class name
710
* @param className Fully qualified class name
711
*/
712
public void setClassName(String className);
713
714
/**
715
* Gets method name
716
* @return Method name
717
*/
718
public String getMethodName();
719
720
/**
721
* Sets method name
722
* @param methodName Method name
723
*/
724
public void setMethodName(String methodName);
725
726
/**
727
* Gets source file name
728
* @return File name or null if unknown
729
*/
730
public String getFileName();
731
732
/**
733
* Sets source file name
734
* @param fileName File name
735
*/
736
public void setFileName(String fileName);
737
738
/**
739
* Gets line number in source file
740
* @return Line number or -1 if unknown
741
*/
742
public int getLineNumber();
743
744
/**
745
* Sets line number in source file
746
* @param lineNumber Line number
747
*/
748
public void setLineNumber(int lineNumber);
749
750
/**
751
* Gets formatted stack element string
752
* @return Formatted string like "className.methodName(fileName:lineNumber)"
753
*/
754
public String getFormattedString();
755
}
756
```
757
758
## Profiling Analysis Types
759
760
### ProfileAnalysis
761
762
Analysis results of profiling data with performance metrics.
763
764
```java { .api }
765
public class ProfileAnalysis {
766
767
private String segmentId;
768
private List<ProfileNode> tree;
769
private Map<String, MethodStats> methodStats;
770
private long totalDuration;
771
private int totalSamples;
772
773
/**
774
* Gets analyzed segment identifier
775
* @return Segment ID
776
*/
777
public String getSegmentId();
778
779
/**
780
* Gets profiling tree structure
781
* @return List of root profile nodes
782
*/
783
public List<ProfileNode> getTree();
784
785
/**
786
* Gets method statistics
787
* @return Map of method name to statistics
788
*/
789
public Map<String, MethodStats> getMethodStats();
790
791
/**
792
* Gets total analysis duration
793
* @return Total duration in milliseconds
794
*/
795
public long getTotalDuration();
796
797
/**
798
* Gets total sample count
799
* @return Total number of samples analyzed
800
*/
801
public int getTotalSamples();
802
803
/**
804
* Gets top CPU consuming methods
805
* @param limit Maximum number of methods to return
806
* @return List of top methods by CPU usage
807
*/
808
public List<MethodStats> getTopCpuMethods(int limit);
809
810
/**
811
* Gets method call tree depth
812
* @return Maximum depth of call tree
813
*/
814
public int getMaxDepth();
815
}
816
```
817
818
### ProfileNode
819
820
Node in profiling analysis tree representing method call hierarchy.
821
822
```java { .api }
823
public class ProfileNode {
824
825
private String methodName;
826
private String className;
827
private long inclusiveTime;
828
private long exclusiveTime;
829
private int sampleCount;
830
private double cpuPercentage;
831
private List<ProfileNode> children;
832
private ProfileNode parent;
833
834
/**
835
* Gets method name
836
* @return Method name
837
*/
838
public String getMethodName();
839
840
/**
841
* Gets class name
842
* @return Class name
843
*/
844
public String getClassName();
845
846
/**
847
* Gets inclusive time (including child calls)
848
* @return Inclusive time in milliseconds
849
*/
850
public long getInclusiveTime();
851
852
/**
853
* Gets exclusive time (excluding child calls)
854
* @return Exclusive time in milliseconds
855
*/
856
public long getExclusiveTime();
857
858
/**
859
* Gets sample count for this method
860
* @return Number of samples
861
*/
862
public int getSampleCount();
863
864
/**
865
* Gets CPU percentage relative to total
866
* @return CPU usage percentage (0-100)
867
*/
868
public double getCpuPercentage();
869
870
/**
871
* Gets child method calls
872
* @return List of child profile nodes
873
*/
874
public List<ProfileNode> getChildren();
875
876
/**
877
* Gets parent method call
878
* @return Parent profile node or null if root
879
*/
880
public ProfileNode getParent();
881
882
/**
883
* Adds child method call
884
* @param child Child profile node to add
885
*/
886
public void addChild(ProfileNode child);
887
888
/**
889
* Gets full method signature
890
* @return "className.methodName" format
891
*/
892
public String getFullMethodName();
893
}
894
```
895
896
### MethodStats
897
898
Statistical information about method performance.
899
900
```java { .api }
901
public class MethodStats {
902
903
private String methodName;
904
private String className;
905
private long totalInclusiveTime;
906
private long totalExclusiveTime;
907
private int callCount;
908
private long avgInclusiveTime;
909
private long avgExclusiveTime;
910
private long maxInclusiveTime;
911
private long minInclusiveTime;
912
private double cpuPercentage;
913
914
/**
915
* Gets method name
916
* @return Method name
917
*/
918
public String getMethodName();
919
920
/**
921
* Gets class name
922
* @return Class name
923
*/
924
public String getClassName();
925
926
/**
927
* Gets total inclusive time across all calls
928
* @return Total inclusive time in milliseconds
929
*/
930
public long getTotalInclusiveTime();
931
932
/**
933
* Gets total exclusive time across all calls
934
* @return Total exclusive time in milliseconds
935
*/
936
public long getTotalExclusiveTime();
937
938
/**
939
* Gets total number of method calls
940
* @return Call count
941
*/
942
public int getCallCount();
943
944
/**
945
* Gets average inclusive time per call
946
* @return Average inclusive time in milliseconds
947
*/
948
public long getAvgInclusiveTime();
949
950
/**
951
* Gets average exclusive time per call
952
* @return Average exclusive time in milliseconds
953
*/
954
public long getAvgExclusiveTime();
955
956
/**
957
* Gets maximum inclusive time for single call
958
* @return Maximum inclusive time in milliseconds
959
*/
960
public long getMaxInclusiveTime();
961
962
/**
963
* Gets minimum inclusive time for single call
964
* @return Minimum inclusive time in milliseconds
965
*/
966
public long getMinInclusiveTime();
967
968
/**
969
* Gets CPU usage percentage
970
* @return CPU percentage (0-100)
971
*/
972
public double getCpuPercentage();
973
974
/**
975
* Gets full method name
976
* @return "className.methodName" format
977
*/
978
public String getFullMethodName();
979
}
980
```
981
982
## Usage Examples
983
984
### Creating Profiling Task
985
986
```java
987
// Get profiling mutation service
988
ProfileTaskMutationService profilingService = moduleDefineHolder.find(CoreModule.NAME)
989
.provider().getService(ProfileTaskMutationService.class);
990
991
// Create profiling task request
992
ProfileTaskCreationRequest request = new ProfileTaskCreationRequest();
993
request.setServiceId("user-service-id");
994
request.setEndpointNames(Arrays.asList("/api/users", "/api/users/{id}"));
995
request.setDuration(5); // 5 minutes
996
request.setMinDurationThreshold(100); // 100ms minimum
997
request.setDumpPeriod(10); // 10ms dump interval
998
request.setMaxSamplingCount(5); // 5 samples per endpoint
999
request.setRequestId(UUID.randomUUID().toString());
1000
1001
// Validate request before creation
1002
ProfileTaskValidationResult validation = profilingService.validateTaskRequest(request);
1003
if (!validation.isValid()) {
1004
System.out.println("Invalid request: " + validation.getErrorMessages());
1005
return;
1006
}
1007
1008
// Create profiling task
1009
ProfileTaskCreationResult result = profilingService.createTask(request);
1010
if (result.isSuccessful()) {
1011
System.out.println("Created profiling task: " + result.getTaskId());
1012
} else {
1013
System.out.println("Failed to create task: " + result.getErrorReason());
1014
}
1015
```
1016
1017
### Querying Profiling Results
1018
1019
```java
1020
// Get profiling query service
1021
ProfileTaskQueryService queryService = moduleDefineHolder.find(CoreModule.NAME)
1022
.provider().getService(ProfileTaskQueryService.class);
1023
1024
// Query profiling tasks
1025
long startTime = System.currentTimeMillis() - TimeUnit.HOURS.toMillis(24);
1026
long endTime = System.currentTimeMillis();
1027
Pagination paging = new Pagination();
1028
paging.setPageNum(1);
1029
paging.setPageSize(20);
1030
1031
ProfileTaskList taskList = queryService.getTaskList(
1032
"user-service-id",
1033
null, // all endpoints
1034
TimeBucket.getMinuteTimeBucket(startTime),
1035
TimeBucket.getMinuteTimeBucket(endTime),
1036
paging
1037
);
1038
1039
System.out.println("Found " + taskList.getTasks().size() + " profiling tasks");
1040
1041
// Get detailed task information
1042
for (ProfileTask task : taskList.getTasks()) {
1043
System.out.println("Task " + task.getTaskId() + ":");
1044
System.out.println(" Status: " + task.getStatus());
1045
System.out.println(" Duration: " + task.getDuration() + " minutes");
1046
System.out.println(" Endpoints: " + task.getEndpointNames());
1047
1048
if (task.getStatus() == ProfileTaskStatus.FINISHED) {
1049
// Query profiled segments for completed task
1050
List<ProfiledSegment> segments = queryService.getProfiledSegments(
1051
task.getTaskId(),
1052
null, // all segments
1053
paging
1054
);
1055
1056
System.out.println(" Found " + segments.size() + " profiled segments");
1057
1058
// Analyze each segment
1059
for (ProfiledSegment segment : segments) {
1060
analyzeProfiledSegment(segment, queryService);
1061
}
1062
}
1063
}
1064
```
1065
1066
### Analyzing Profiling Data
1067
1068
```java
1069
private void analyzeProfiledSegment(ProfiledSegment segment, ProfileTaskQueryService queryService)
1070
throws IOException {
1071
1072
System.out.println("Analyzing segment " + segment.getSegmentId() + ":");
1073
System.out.println(" Trace ID: " + segment.getTraceId());
1074
System.out.println(" Duration: " + segment.getDuration() + "ms");
1075
System.out.println(" Snapshots: " + segment.getSnapshotCount());
1076
1077
// Get thread snapshots
1078
List<ThreadSnapshot> snapshots = queryService.getThreadSnapshots(
1079
segment.getSegmentId(),
1080
null, // all threads
1081
segment.getStartTime(),
1082
segment.getEndTime()
1083
);
1084
1085
// Analyze thread snapshots
1086
Map<String, List<ThreadSnapshot>> snapshotsByThread = snapshots.stream()
1087
.collect(Collectors.groupingBy(s -> s.getStack().getThreadId()));
1088
1089
for (Map.Entry<String, List<ThreadSnapshot>> entry : snapshotsByThread.entrySet()) {
1090
String threadId = entry.getKey();
1091
List<ThreadSnapshot> threadSnapshots = entry.getValue();
1092
1093
System.out.println(" Thread " + threadId + ":");
1094
System.out.println(" Snapshots: " + threadSnapshots.size());
1095
1096
// Analyze method calls
1097
Map<String, Integer> methodCounts = new HashMap<>();
1098
for (ThreadSnapshot snapshot : threadSnapshots) {
1099
ThreadStack stack = snapshot.getStack();
1100
for (StackElement element : stack.getElements()) {
1101
String methodKey = element.getClassName() + "." + element.getMethodName();
1102
methodCounts.merge(methodKey, 1, Integer::sum);
1103
}
1104
}
1105
1106
// Show top methods by frequency
1107
methodCounts.entrySet().stream()
1108
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
1109
.limit(10)
1110
.forEach(e -> System.out.println(" " + e.getKey() + ": " + e.getValue() + " samples"));
1111
}
1112
1113
// Generate profiling analysis if needed
1114
if (segment.getAnalysis() == null) {
1115
List<ProfileAnalyzeTimeRange> timeRanges = Arrays.asList(
1116
new ProfileAnalyzeTimeRange(segment.getStartTime(), segment.getEndTime())
1117
);
1118
1119
ProfileAnalyzeTimeRange analysis = queryService.getProfileAnalyzeTimeRange(
1120
segment.getSegmentId(),
1121
timeRanges
1122
);
1123
1124
if (analysis != null) {
1125
displayProfileAnalysis(analysis);
1126
}
1127
}
1128
}
1129
1130
private void displayProfileAnalysis(ProfileAnalyzeTimeRange analysis) {
1131
System.out.println("Profile Analysis:");
1132
System.out.println(" Total samples: " + analysis.getTotalSamples());
1133
System.out.println(" Duration: " + analysis.getTotalDuration() + "ms");
1134
1135
// Display method statistics
1136
Map<String, MethodStats> methodStats = analysis.getMethodStats();
1137
if (methodStats != null && !methodStats.isEmpty()) {
1138
System.out.println(" Top CPU consuming methods:");
1139
1140
methodStats.values().stream()
1141
.sorted(Comparator.comparingDouble(MethodStats::getCpuPercentage).reversed())
1142
.limit(10)
1143
.forEach(stats -> {
1144
System.out.printf(" %s: %.2f%% CPU, %d calls, avg %.2fms%n",
1145
stats.getFullMethodName(),
1146
stats.getCpuPercentage(),
1147
stats.getCallCount(),
1148
stats.getAvgExclusiveTime() / 1000.0);
1149
});
1150
}
1151
1152
// Display call tree
1153
List<ProfileNode> tree = analysis.getTree();
1154
if (tree != null && !tree.isEmpty()) {
1155
System.out.println(" Call tree:");
1156
for (ProfileNode root : tree) {
1157
displayProfileNode(root, 0);
1158
}
1159
}
1160
}
1161
1162
private void displayProfileNode(ProfileNode node, int depth) {
1163
String indent = " " + " ".repeat(depth);
1164
System.out.printf("%s%s: %.2f%% CPU, %dms exclusive, %d samples%n",
1165
indent,
1166
node.getFullMethodName(),
1167
node.getCpuPercentage(),
1168
node.getExclusiveTime(),
1169
node.getSampleCount());
1170
1171
// Recursively display children (limit depth to avoid too much output)
1172
if (depth < 5) {
1173
for (ProfileNode child : node.getChildren()) {
1174
displayProfileNode(child, depth + 1);
1175
}
1176
}
1177
}
1178
```
1179
1180
### Managing Profiling Tasks
1181
1182
```java
1183
// Update profiling task
1184
ProfileTaskUpdateRequest updateRequest = new ProfileTaskUpdateRequest();
1185
updateRequest.setMaxSamplingCount(10); // Increase sampling count
1186
updateRequest.setMinDurationThreshold(50); // Lower threshold
1187
1188
ProfileTaskUpdateResult updateResult = profilingService.updateTask(taskId, updateRequest);
1189
if (updateResult.isSuccessful()) {
1190
System.out.println("Task updated successfully");
1191
} else {
1192
System.out.println("Failed to update task: " + updateResult.getErrorReason());
1193
}
1194
1195
// Get task statistics
1196
ProfileTaskStats stats = profilingService.getTaskStats(taskId);
1197
System.out.println("Task Statistics:");
1198
System.out.println(" Total segments profiled: " + stats.getTotalSegments());
1199
System.out.println(" Total snapshots: " + stats.getTotalSnapshots());
1200
System.out.println(" Average snapshots per segment: " + stats.getAvgSnapshotsPerSegment());
1201
System.out.println(" Data size: " + stats.getDataSizeInBytes() + " bytes");
1202
1203
// Cancel running task if needed
1204
if (task.isActive()) {
1205
ProfileTaskCancellationResult cancelResult = profilingService.cancelTask(taskId);
1206
if (cancelResult.isSuccessful()) {
1207
System.out.println("Task cancelled successfully");
1208
} else {
1209
System.out.println("Failed to cancel task: " + cancelResult.getErrorReason());
1210
}
1211
}
1212
```
1213
1214
## Core Profiling Types
1215
1216
```java { .api }
1217
/**
1218
* Profiling task status enumeration
1219
*/
1220
public enum ProfileTaskStatus {
1221
PENDING, RUNNING, FINISHED, CANCELLED, ERROR
1222
}
1223
1224
/**
1225
* Profile analysis time range
1226
*/
1227
public class ProfileAnalyzeTimeRange {
1228
private long startTime;
1229
private long endTime;
1230
private List<ProfileNode> tree;
1231
private Map<String, MethodStats> methodStats;
1232
private long totalDuration;
1233
private int totalSamples;
1234
1235
public ProfileAnalyzeTimeRange(long startTime, long endTime);
1236
1237
public long getStartTime();
1238
public long getEndTime();
1239
public List<ProfileNode> getTree();
1240
public Map<String, MethodStats> getMethodStats();
1241
public long getTotalDuration();
1242
public int getTotalSamples();
1243
}
1244
1245
/**
1246
* Profiling task creation result
1247
*/
1248
public class ProfileTaskCreationResult {
1249
private boolean successful;
1250
private String taskId;
1251
private String errorReason;
1252
1253
public boolean isSuccessful();
1254
public String getTaskId();
1255
public String getErrorReason();
1256
}
1257
1258
/**
1259
* Profiling task validation result
1260
*/
1261
public class ProfileTaskValidationResult {
1262
private boolean valid;
1263
private List<String> errorMessages;
1264
1265
public boolean isValid();
1266
public List<String> getErrorMessages();
1267
}
1268
```