• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
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  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 package ohos.devtools.datasources.transport.grpc;
17 
18 import com.google.protobuf.ByteString;
19 import io.grpc.StatusRuntimeException;
20 
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Objects;
27 import java.util.Optional;
28 
29 import ohos.devtools.datasources.transport.grpc.service.BytracePluginConfigOuterClass;
30 import ohos.devtools.datasources.transport.grpc.service.CommonTypes;
31 import ohos.devtools.datasources.transport.grpc.service.HilogPluginConfig;
32 import ohos.devtools.datasources.transport.grpc.service.HiperfCallPluginConfigOuterClass;
33 import ohos.devtools.datasources.transport.grpc.service.MemoryPluginCommon;
34 import ohos.devtools.datasources.transport.grpc.service.MemoryPluginConfig;
35 import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes;
36 import ohos.devtools.datasources.transport.grpc.service.TracePluginConfigOuterClass;
37 import ohos.devtools.datasources.transport.hdc.HdcWrapper;
38 import ohos.devtools.datasources.utils.common.GrpcException;
39 import ohos.devtools.datasources.utils.common.util.BeanUtil;
40 import ohos.devtools.datasources.utils.common.util.CommonUtil;
41 import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo;
42 import ohos.devtools.datasources.utils.device.entity.DeviceType;
43 import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager;
44 import ohos.devtools.datasources.utils.quartzmanager.QuartzManager;
45 import ohos.devtools.datasources.utils.session.KeepSession;
46 import ohos.devtools.datasources.utils.session.entity.SessionInfo;
47 import ohos.devtools.datasources.utils.session.service.SessionManager;
48 import ohos.devtools.services.systemconfig.SystemConfigData;
49 import ohos.devtools.views.common.LayoutConstants;
50 import ohos.devtools.views.layout.utils.TraceStreamerUtils;
51 import org.apache.logging.log4j.LogManager;
52 import org.apache.logging.log4j.Logger;
53 
54 import java.io.File;
55 import java.io.FileOutputStream;
56 import java.io.IOException;
57 import java.util.stream.Collectors;
58 
59 import static ohos.devtools.datasources.transport.grpc.HiProfilerClient.getSTDSha256;
60 import static ohos.devtools.datasources.transport.grpc.HiProfilerClient.getSha256;
61 import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_CLEAR_COMMAND_CMD;
62 import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_PUSH_FILE_SHELL;
63 import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_PUSH_FILE_SHELL;
64 import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_ROOT_CLEAR_COMMAND;
65 import static ohos.devtools.datasources.transport.hdc.HdcWrapper.conversionCommand;
66 import static ohos.devtools.datasources.utils.device.entity.DeviceType.LEAN_HOS_DEVICE;
67 import static ohos.devtools.views.common.Constant.IS_SUPPORT_NEW_HDC;
68 
69 /**
70  * get trace data
71  *
72  * @since 2021/5/19 16:39
73  */
74 public class SystemTraceHelper {
75     private static final Logger LOGGER = LogManager.getLogger(SystemTraceHelper.class);
76     private static final int KEEP_SESSION_REQUEST_TIME = 2500;
77     private static final String PROMPT_INFORMATION = "请连接设备";
78     private static final String PROMPT_MISSING_FILE = "缺失相关so文件";
79     private static final String SYSTEM_PROBES_KIND_IN_MEMORY = "inMemoryValue";
80     private static final String SYSTEM_PROBES_KIND_MAX_DURATION = "maxDuration";
81     private static final String SYSTEM_PROBES_KIND_FTRACE_EVENT = "ftrace_events";
82     private static final int ACQUISITION_FREQUENCY_BOUNDARY = 20;
83     private static final int MAX_ACQUISITION_FREQUENCY = 5;
84     private static final int MIN_ACQUISITION_FREQUENCY = 2;
85     private static final String FILE_PATH = "/data/local/tmp";
86     private static final int SECOND_TO_MS = 1000;
87     private static final int MEMORY_MB_TO_KB = 1024;
88     private static final int ZERO = 0;
89     private static ArrayList<String> MEM_INFO = new ArrayList<String>(Arrays
90         .asList("MEMINFO_ACTIVE", "MEMINFO_ACTIVE_ANON", "MEMINFO_ACTIVE_FILE", "MEMINFO_ANON_PAGES", "MEMINFO_BUFFERS",
91             "MEMINFO_CACHED", "MEMINFO_CMA_FREE", "MEMINFO_CMA_TOTAL", "MEMINFO_COMMIT_LIMIT", "MEMINFO_COMMITED_AS",
92             "MEMINFO_DIRTY", "MEMINFO_INACTIVE", "MEMINFO_INACTIVE_ANON", "MEMINFO_INACTIVE_FILE",
93             "MEMINFO_KERNEL_STACK", "MEMINFO_MAPPED", "MEMINFO_MEM_AVAILABLE", "MEMINFO_MEM_FREE", "MEMINFO_MEM_TOTAL",
94             "MEMINFO_MLOCKED", "MEMINFO_PAGE_TABLES", "MEMINFO_SHMEM", "MEMINFO_SLAB", "MEMINFO_SLAB_RECLAIMABLE",
95             "MEMINFO_SLAB_UNRECLAIMABLE", "MEMINFO_SWAP_CACHED", "MEMINFO_SWAP_FREE", "MEMINFO_SWAP_TOTAL",
96             "MEMINFO_UNEVICTABLE", "MEMINFO_VMALLOC_CHUNK", "MEMINFO_VMALLOC_TOTAL", "MEMINFO_VMALLOC_USED",
97             "MEMINFO_WRITEBACK"));
98     private static ArrayList<String> VMEM_INFO = new ArrayList<>(Arrays
99         .asList("VMEMINFO_UNSPECIFIED", "VMEMINFO_NR_FREE_PAGES", "VMEMINFO_NR_ALLOC_BATCH",
100             "VMEMINFO_NR_INACTIVE_ANON", "VMEMINFO_NR_ACTIVE_ANON", "VMEMINFO_NR_INACTIVE_FILE",
101             "VMEMINFO_NR_ACTIVE_FILE", "VMEMINFO_NR_UNEVICTABLE", "VMEMINFO_NR_MLOCK", "VMEMINFO_NR_ANON_PAGES",
102             "VMEMINFO_NR_MAPPED", "VMEMINFO_NR_FILE_PAGES", "VMEMINFO_NR_DIRTY", "VMEMINFO_NR_WRITEBACK",
103             "VMEMINFO_NR_SLAB_RECLAIMABLE", "VMEMINFO_NR_SLAB_UNRECLAIMABLE", "VMEMINFO_NR_PAGE_TABLE_PAGES",
104             "VMEMINFO_NR_KERNEL_STACK", "VMEMINFO_NR_OVERHEAD", "VMEMINFO_NR_UNSTABLE", "VMEMINFO_NR_BOUNCE",
105             "VMEMINFO_NR_VMSCAN_WRITE", "VMEMINFO_NR_VMSCAN_IMMEDIATE_RECLAIM", "VMEMINFO_NR_WRITEBACK_TEMP",
106             "VMEMINFO_NR_ISOLATED_ANON", "VMEMINFO_NR_ISOLATED_FILE", "VMEMINFO_NR_SHMEM", "VMEMINFO_NR_DIRTIED",
107             "VMEMINFO_NR_WRITTEN", "VMEMINFO_NR_PAGES_SCANNED", "VMEMINFO_WORKINGSET_REFAULT",
108             "VMEMINFO_WORKINGSET_ACTIVATE", "VMEMINFO_WORKINGSET_NODERECLAIM", "VMEMINFO_NR_ANON_TRANSPARENT_HUGEPAGES",
109             "VMEMINFO_NR_FREE_CMA", "VMEMINFO_NR_SWAPCACHE", "VMEMINFO_NR_DIRTY_THRESHOLD",
110             "VMEMINFO_NR_DIRTY_BACKGROUND_THRESHOLD", "VMEMINFO_PGPGIN", "VMEMINFO_PGPGOUT", "VMEMINFO_PGPGOUTCLEAN",
111             "VMEMINFO_PSWPIN", "VMEMINFO_PSWPOUT", "VMEMINFO_PGALLOC_DMA"));
112 
113     private static ArrayList<String> VMEM_INFO_SECOND = new ArrayList<String>(Arrays
114         .asList("VMEMINFO_PGALLOC_NORMAL", "VMEMINFO_PGALLOC_MOVABLE", "VMEMINFO_PGFREE", "VMEMINFO_PGACTIVATE",
115             "VMEMINFO_PGDEACTIVATE", "VMEMINFO_PGFAULT", "VMEMINFO_PGMAJFAULT", "VMEMINFO_PGREFILL_DMA",
116             "VMEMINFO_PGREFILL_NORMAL", "VMEMINFO_PGREFILL_MOVABLE", "VMEMINFO_PGSTEAL_KSWAPD_DMA",
117             "VMEMINFO_PGSTEAL_KSWAPD_NORMAL", "VMEMINFO_PGSTEAL_KSWAPD_MOVABLE", "VMEMINFO_PGSTEAL_DIRECT_DMA",
118             "VMEMINFO_PGSTEAL_DIRECT_NORMAL", "VMEMINFO_PGSTEAL_DIRECT_MOVABLE", "VMEMINFO_PGSCAN_KSWAPD_DMA",
119             "VMEMINFO_PGSCAN_KSWAPD_NORMAL", "VMEMINFO_PGSCAN_KSWAPD_MOVABLE", "VMEMINFO_PGSCAN_DIRECT_DMA",
120             "VMEMINFO_PGSCAN_DIRECT_NORMAL", "VMEMINFO_PGSCAN_DIRECT_MOVABLE", "VMEMINFO_PGSCAN_DIRECT_THROTTLE",
121             "VMEMINFO_PGINODESTEAL", "VMEMINFO_SLABS_SCANNED", "VMEMINFO_KSWAPD_INODESTEAL",
122             "VMEMINFO_KSWAPD_LOW_WMARK_HIT_QUICKLY", "VMEMINFO_KSWAPD_HIGH_WMARK_HIT_QUICKLY", "VMEMINFO_PAGEOUTRUN",
123             "VMEMINFO_ALLOCSTALL", "VMEMINFO_PGROTATED", "VMEMINFO_DROP_PAGECACHE", "VMEMINFO_DROP_SLAB",
124             "VMEMINFO_PGMIGRATE_SUCCESS", "VMEMINFO_PGMIGRATE_FAIL", "VMEMINFO_COMPACT_MIGRATE_SCANNED",
125             "VMEMINFO_COMPACT_FREE_SCANNED", "VMEMINFO_COMPACT_ISOLATED", "VMEMINFO_COMPACT_STALL",
126             "VMEMINFO_COMPACT_FAIL", "VMEMINFO_COMPACT_SUCCESS", "VMEMINFO_COMPACT_DAEMON_WAKE",
127             "VMEMINFO_UNEVICTABLE_PGS_CULLED", "VMEMINFO_UNEVICTABLE_PGS_SCANNED", "VMEMINFO_UNEVICTABLE_PGS_RESCUED",
128             "VMEMINFO_UNEVICTABLE_PGS_MLOCKED", "VMEMINFO_UNEVICTABLE_PGS_MUNLOCKED"));
129 
130     private static ArrayList<String> VMEM_INFO_THIRD = new ArrayList<String>(Arrays
131         .asList("VMEMINFO_UNEVICTABLE_PGS_CLEARED", "VMEMINFO_UNEVICTABLE_PGS_STRANDED", "VMEMINFO_NR_ZSPAGES",
132             "VMEMINFO_NR_ION_HEAP", "VMEMINFO_NR_GPU_HEAP", "VMEMINFO_ALLOCSTALL_DMA", "VMEMINFO_ALLOCSTALL_MOVABLE",
133             "VMEMINFO_ALLOCSTALL_NORMAL", "VMEMINFO_COMPACT_DAEMON_FREE_SCANNED",
134             "VMEMINFO_COMPACT_DAEMON_MIGRATE_SCANNED", "VMEMINFO_NR_FASTRPC", "VMEMINFO_NR_INDIRECTLY_RECLAIMABLE",
135             "VMEMINFO_NR_ION_HEAP_POOL", "VMEMINFO_NR_KERNEL_MISC_RECLAIMABLE", "VMEMINFO_NR_SHADOW_CALL_STACK_BYTES",
136             "VMEMINFO_NR_SHMEM_HUGEPAGES", "VMEMINFO_NR_SHMEM_PMDMAPPED", "VMEMINFO_NR_UNRECLAIMABLE_PAGES",
137             "VMEMINFO_NR_ZONE_ACTIVE_ANON", "VMEMINFO_NR_ZONE_ACTIVE_FILE", "VMEMINFO_NR_ZONE_INACTIVE_ANON",
138             "VMEMINFO_NR_ZONE_INACTIVE_FILE", "VMEMINFO_NR_ZONE_UNEVICTABLE", "VMEMINFO_NR_ZONE_WRITE_PENDING",
139             "VMEMINFO_OOM_KILL", "VMEMINFO_PGLAZYFREE", "VMEMINFO_PGLAZYFREED", "VMEMINFO_PGREFILL",
140             "VMEMINFO_PGSCAN_DIRECT", "VMEMINFO_PGSCAN_KSWAPD", "VMEMINFO_PGSKIP_DMA", "VMEMINFO_PGSKIP_MOVABLE",
141             "VMEMINFO_PGSKIP_NORMAL", "VMEMINFO_PGSTEAL_DIRECT", "VMEMINFO_PGSTEAL_KSWAPD", "VMEMINFO_SWAP_RA",
142             "VMEMINFO_SWAP_RA_HIT", "VMEMINFO_WORKINGSET_RESTORE"));
143 
144     /**
145      * 单例进程对象
146      */
147     private static SystemTraceHelper singleton;
148 
149     /**
150      * SystemTraceHelper
151      */
SystemTraceHelper()152     private SystemTraceHelper() {
153         super();
154     }
155 
156     /**
157      * 获取实例
158      *
159      * @return TraceManager
160      */
getSingleton()161     public static SystemTraceHelper getSingleton() {
162         if (singleton == null) {
163             if (ProfilerLogManager.isInfoEnabled()) {
164                 LOGGER.info("getSingleton");
165             }
166             synchronized (SystemTraceHelper.class) {
167                 if (singleton == null) {
168                     singleton = new SystemTraceHelper();
169                 }
170             }
171         }
172         return singleton;
173     }
174 
175     /**
176      * createSession startSession
177      *
178      * @param deviceIPPortInfoParam deviceIPPortInfoParam
179      * @param sessionConfigParam sessionConfigParam
180      * @param plugConfig plugConfig
181      * @param systemConfigData systemConfigData
182      * @param hilogLevel hilogLevel
183      * @return String
184      */
createAndStartSession(DeviceIPPortInfo deviceIPPortInfoParam, ProfilerServiceTypes.ProfilerSessionConfig sessionConfigParam, CommonTypes.ProfilerPluginConfig plugConfig, SystemConfigData systemConfigData, String hilogLevel)185     public String createAndStartSession(DeviceIPPortInfo deviceIPPortInfoParam,
186         ProfilerServiceTypes.ProfilerSessionConfig sessionConfigParam, CommonTypes.ProfilerPluginConfig plugConfig,
187         SystemConfigData systemConfigData, String hilogLevel) {
188         long localSessionID = CommonUtil.getLocalSessionId();
189         ProfilerServiceTypes.CreateSessionRequest.Builder request = null;
190         request = ProfilerServiceTypes.CreateSessionRequest.newBuilder().setRequestId(CommonUtil.getRequestId())
191             .setSessionConfig(sessionConfigParam).addPluginConfigs(plugConfig);
192         if (systemConfigData != null && (systemConfigData.isMemoryInfo() || systemConfigData.isVmemoryInfo())) {
193             // memory
194             Optional<String> memoryPluginNameOption = getPluginName(deviceIPPortInfoParam, "libmem");
195             if (memoryPluginNameOption.isPresent()) {
196                 byte[] memoryConfigByte =
197                     BeanUtil.serializeByCodedOutPutStream(memoryEventConfiguration(systemConfigData));
198                 CommonTypes.ProfilerPluginConfig memoryPlugConfig =
199                     plugConfig(deviceIPPortInfoParam, memoryPluginNameOption.get(), memoryConfigByte,
200                         systemConfigData.getMaxDuration());
201                 request = request.addPluginConfigs(memoryPlugConfig);
202             } else {
203                 return "";
204             }
205         }
206         // hilog
207         if (hilogLevel != null) {
208             Optional<String> hilogPluginNameOption = getPluginName(deviceIPPortInfoParam, "libhilog");
209             if (hilogPluginNameOption.isPresent()) {
210                 byte[] hilogconfigByte =
211                     BeanUtil.serializeByCodedOutPutStream(hilogEventConfiguration(deviceIPPortInfoParam, hilogLevel));
212                 CommonTypes.ProfilerPluginConfig hilogPlugConfig =
213                     plugConfig(deviceIPPortInfoParam, hilogPluginNameOption.get(), hilogconfigByte,
214                         systemConfigData.getMaxDuration());
215                 request = request.addPluginConfigs(hilogPlugConfig);
216             } else {
217                 return "";
218             }
219         }
220         HiProfilerClient hiprofiler = HiProfilerClient.getInstance();
221         ProfilerServiceTypes.CreateSessionResponse createSessionResponse = hiprofiler
222             .requestCreateSession(deviceIPPortInfoParam.getIp(), deviceIPPortInfoParam.getForwardPort(),
223                 request.build());
224         if (createSessionResponse.getSessionId() > 0) {
225             startKeepLiveSession(deviceIPPortInfoParam, createSessionResponse.getSessionId(), localSessionID);
226             if (ProfilerLogManager.isInfoEnabled()) {
227                 LOGGER.info("Htrace Session created successfully.");
228             }
229         } else {
230             if (ProfilerLogManager.isInfoEnabled()) {
231                 LOGGER.info("Failed to create Htrace Session");
232             }
233         }
234         // 调用哪些进程(采集数据)
235         hiprofiler.requestStartSession(deviceIPPortInfoParam.getIp(), deviceIPPortInfoParam.getForwardPort(),
236             createSessionResponse.getSessionId());
237         return String.valueOf(createSessionResponse.getSessionId());
238     }
239 
240     /**
241      * plugConfig
242      *
243      * @param deviceIPPortInfoParam deviceIPPortInfoParam
244      * @param pluginName pluginName
245      * @param configByteParam configByteParam
246      * @param maxDuration maxDuration
247      * @return CommonTypes.ProfilerPluginConfi
248      */
plugConfig(DeviceIPPortInfo deviceIPPortInfoParam, String pluginName, byte[] configByteParam, int maxDuration)249     public CommonTypes.ProfilerPluginConfig plugConfig(DeviceIPPortInfo deviceIPPortInfoParam, String pluginName,
250         byte[] configByteParam, int maxDuration) {
251         int reportingFrequency;
252         if (maxDuration > ACQUISITION_FREQUENCY_BOUNDARY) {
253             reportingFrequency = MAX_ACQUISITION_FREQUENCY;
254         } else {
255             reportingFrequency = MIN_ACQUISITION_FREQUENCY;
256         }
257         String Sha256;
258         if (IS_SUPPORT_NEW_HDC && deviceIPPortInfoParam.getDeviceType() == LEAN_HOS_DEVICE) {
259             Sha256 = getSTDSha256(pluginName);
260         } else {
261             Sha256 = getSha256(pluginName);
262         }
263         return CommonTypes.ProfilerPluginConfig.newBuilder().setPluginSha256(Sha256).setName(pluginName)
264             .setSampleInterval(reportingFrequency * SECOND_TO_MS).setConfigData(ByteString.copyFrom(configByteParam))
265             .build();
266     }
267 
268     /**
269      * stopSession、destroySessionRequest
270      *
271      * @param deviceIPPortInfo deviceIPPortInfo
272      * @param sessionIdParam sessionIdParam
273      */
stopAndDestroySession(DeviceIPPortInfo deviceIPPortInfo, String sessionIdParam)274     public void stopAndDestroySession(DeviceIPPortInfo deviceIPPortInfo, String sessionIdParam) {
275         if (ProfilerLogManager.isInfoEnabled()) {
276             LOGGER.info("stopAndDestroySession");
277         }
278         int sessionId = Integer.valueOf(sessionIdParam);
279         try {
280             HiProfilerClient.getInstance()
281                 .requestStopSession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId, true);
282             HiProfilerClient.getInstance()
283                 .requestDestroySession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId);
284             String keepSessionName = getKeepSessionName(deviceIPPortInfo, Integer.valueOf(sessionIdParam));
285             QuartzManager.getInstance().deleteExecutor(keepSessionName);
286             if (ProfilerLogManager.isInfoEnabled()) {
287                 LOGGER.info("Htrace Session destroy successfully");
288             }
289         } catch (StatusRuntimeException exception) {
290             if (ProfilerLogManager.isErrorEnabled()) {
291                 LOGGER.info("destroy session Exception: {}", exception.getMessage());
292             }
293         }
294     }
295 
296     /**
297      * stopSession、destroySessionRequest
298      *
299      * @param deviceIPPortInfo deviceIPPortInfo
300      * @param sessionIdParam sessionIdParam
301      */
stopSession(DeviceIPPortInfo deviceIPPortInfo, String sessionIdParam)302     public void stopSession(DeviceIPPortInfo deviceIPPortInfo, String sessionIdParam) {
303         if (ProfilerLogManager.isInfoEnabled()) {
304             LOGGER.info("stopSession");
305         }
306         int sessionId = Integer.valueOf(sessionIdParam);
307         HiProfilerClient hiprofiler = HiProfilerClient.getInstance();
308         ProfilerClient client =
309             hiprofiler.getProfilerClient(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort());
310         ProfilerServiceTypes.StopSessionRequest stopSession =
311             ProfilerServiceHelper.stopSessionRequest(CommonUtil.getRequestId(), sessionId);
312         HiProfilerClient.getInstance()
313             .requestStopSession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId, true);
314     }
315 
316     /**
317      * destroySessionRequest
318      *
319      * @param deviceIPPortInfo deviceIPPortInfo
320      * @param sessionIdParam sessionIdParam
321      */
cancelActionDestroySession(DeviceIPPortInfo deviceIPPortInfo, String sessionIdParam)322     public void cancelActionDestroySession(DeviceIPPortInfo deviceIPPortInfo, String sessionIdParam) {
323         if (ProfilerLogManager.isInfoEnabled()) {
324             LOGGER.info("cancelActionDestroySession");
325         }
326         int sessionId = Integer.valueOf(sessionIdParam);
327         HiProfilerClient hiprofiler = HiProfilerClient.getInstance();
328         try {
329             String keepSessionName = getKeepSessionName(deviceIPPortInfo, Integer.valueOf(sessionIdParam));
330             QuartzManager.getInstance().deleteExecutor(keepSessionName);
331             hiprofiler.requestDestroySession(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort(), sessionId);
332             if (ProfilerLogManager.isInfoEnabled()) {
333                 LOGGER.info("Htrace Session destroy successfully.");
334             }
335         } catch (StatusRuntimeException exception) {
336             if (ProfilerLogManager.isErrorEnabled()) {
337                 LOGGER.error("destroy session Exception: {}", exception.getMessage());
338             }
339         }
340     }
341 
342     /**
343      * request start session
344      *
345      * @param deviceIPPortInfo device IP Port Info
346      * @param userCheckBoxForPerfettoStr userCheckBoxForPerfettoStr
347      * @param maxDurationParam maxDurationParam
348      * @param inMemoryValue inMemoryValue
349      * @param outFileName outFileName
350      * @param isRoot isRoot
351      * @return String
352      * @throws GrpcException GrpcException
353      */
createSessionByTraceRequest(DeviceIPPortInfo deviceIPPortInfo, String userCheckBoxForPerfettoStr, int maxDurationParam, int inMemoryValue, String outFileName, boolean isRoot)354     public String createSessionByTraceRequest(DeviceIPPortInfo deviceIPPortInfo, String userCheckBoxForPerfettoStr,
355         int maxDurationParam, int inMemoryValue, String outFileName, boolean isRoot) throws GrpcException {
356         if (ProfilerLogManager.isInfoEnabled()) {
357             LOGGER.info("createSessionByTraceRequest");
358         }
359         BytracePluginConfigOuterClass.BytracePluginConfig.Builder build =
360             BytracePluginConfigOuterClass.BytracePluginConfig.newBuilder();
361         build.setBuffeSize(inMemoryValue * MEMORY_MB_TO_KB);
362         build.setClock("mono");
363         if (userCheckBoxForPerfettoStr != null && userCheckBoxForPerfettoStr.length() > 0) {
364             Arrays.stream(userCheckBoxForPerfettoStr.split(";")).filter(param -> param.trim().length() > 0)
365                 .forEach(param -> build.addCategories(param));
366         } else {
367             // catch All
368             build.addCategories("");
369         }
370         build.setIsRoot(isRoot);
371         build.setTime(maxDurationParam);
372         build.setOutfileName(outFileName);
373         BytracePluginConfigOuterClass.BytracePluginConfig config = build.build();
374         byte[] configByte = BeanUtil.serializeByCodedOutPutStream(config);
375         ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf =
376             ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD)
377                 .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build();
378         int keepAliveTime = maxDurationParam + 1;
379         ProfilerServiceTypes.ProfilerSessionConfig sessionConfig =
380             ProfilerServiceTypes.ProfilerSessionConfig.newBuilder()
381                 .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE).addBuffers(bf)
382                 .setKeepAliveTime(keepAliveTime * 1000).build();
383         // 获取插件名称
384         ProfilerServiceTypes.GetCapabilitiesResponse response =
385             HiProfilerClient.getInstance().getCapabilities(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort());
386         List<ProfilerServiceTypes.ProfilerPluginCapability> capabilitiesList = response.getCapabilitiesList();
387         ProfilerServiceTypes.ProfilerPluginCapability profilerPluginCapability =
388             capabilitiesList.stream().filter(item -> item.getName().contains("libbytrace")).findFirst().get();
389         String pluginName = profilerPluginCapability.getName();
390         CommonTypes.ProfilerPluginConfig bytracePlugConfig =
391             plugConfig(deviceIPPortInfo, pluginName, configByte, maxDurationParam);
392         return this.createAndStartSession(deviceIPPortInfo, sessionConfig, bytracePlugConfig, null, null);
393     }
394 
395     /**
396      * request start session
397      *
398      * @param deviceIPPortInfo device IP Port Info
399      * @param fileSuffixTimestampParam file Suffix Timestamp Param
400      * @param processNameParam processName Param
401      * @return String
402      * @throws GrpcException GrpcException
403      */
createSessionByTraceRequestNoParam(DeviceIPPortInfo deviceIPPortInfo, String fileSuffixTimestampParam, String processNameParam)404     public String createSessionByTraceRequestNoParam(DeviceIPPortInfo deviceIPPortInfo, String fileSuffixTimestampParam,
405         String processNameParam) throws GrpcException {
406         if (ProfilerLogManager.isInfoEnabled()) {
407             LOGGER.info("createSessionByTraceRequestNoParam");
408         }
409         BytracePluginConfigOuterClass.BytracePluginConfig.Builder build =
410             BytracePluginConfigOuterClass.BytracePluginConfig.newBuilder();
411         String fileStorePath = "/data/local/tmp/hiprofiler_data";
412         fileStorePath = fileStorePath.concat(fileSuffixTimestampParam).concat(".bytrace");
413         if (deviceIPPortInfo.getDeviceType() == DeviceType.LEAN_HOS_DEVICE) {
414             build.addCategories("sched");
415             build.addCategories("freq");
416             build.addCategories("idle");
417             build.addCategories("workq");
418             build.setIsRoot(true);
419         } else {
420             build.setIsRoot(false);
421             build.addCategories("gfx");
422         }
423         build.setTime(0);
424         build.setOutfileName(fileStorePath);
425         BytracePluginConfigOuterClass.BytracePluginConfig config = build.build();
426         byte[] configByte = BeanUtil.serializeByCodedOutPutStream(config);
427         ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf =
428             ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD)
429                 .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build();
430         ProfilerServiceTypes.ProfilerSessionConfig sessionConfig =
431             ProfilerServiceTypes.ProfilerSessionConfig.newBuilder()
432                 .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE).addBuffers(bf).build();
433         // 获取插件名称
434         ProfilerServiceTypes.GetCapabilitiesResponse response =
435             HiProfilerClient.getInstance().getCapabilities(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort());
436         List<ProfilerServiceTypes.ProfilerPluginCapability> capabilitiesList = response.getCapabilitiesList();
437         ProfilerServiceTypes.ProfilerPluginCapability profilerPluginCapability =
438             capabilitiesList.stream().filter(item -> item.getName().contains("libbytrace")).findFirst().get();
439         String pluginName = profilerPluginCapability.getName();
440         CommonTypes.ProfilerPluginConfig plugConfig = plugConfig(deviceIPPortInfo, pluginName, configByte, ZERO);
441         return this.createAndStartSession(deviceIPPortInfo, sessionConfig, plugConfig, null, null);
442     }
443 
444     /**
445      * request start session
446      *
447      * @param deviceIPPortInfo device IP Port Info
448      * @param fileSuffixTimestampParam file Suffix Timestamp Param
449      * @param sessionId sessionId
450      * @return String
451      * @throws GrpcException GrpcException
452      */
createSessionThirdPerfRequest(DeviceIPPortInfo deviceIPPortInfo, String fileSuffixTimestampParam, long sessionId)453     public String createSessionThirdPerfRequest(DeviceIPPortInfo deviceIPPortInfo, String fileSuffixTimestampParam,
454         long sessionId) throws GrpcException {
455         if (ProfilerLogManager.isInfoEnabled()) {
456             LOGGER.info("createSessionThirdPerfRequest");
457         }
458         SessionInfo sessionInfo = SessionManager.getInstance().getSessionInfo(sessionId);
459         String processName = sessionInfo.getProcessName();
460         int pid = sessionInfo.getPid();
461         HiperfCallPluginConfigOuterClass.HiperfCallPluginConfig.Builder build =
462             HiperfCallPluginConfigOuterClass.HiperfCallPluginConfig.newBuilder();
463         String fileStorePath = "/data/local/tmp/thirdPerf_data";
464         fileStorePath = fileStorePath.concat(fileSuffixTimestampParam).concat(".trace");
465         build.setPid(pid);
466         build.setAppName(processName);
467         build.setOutfile(fileStorePath);
468         if (deviceIPPortInfo.getDeviceType() == DeviceType.LEAN_HOS_DEVICE) {
469             build.setIsTrace(true);
470             build.setIsRoot(true);
471             build.setIsEmulator(false);
472         } else {
473             build.setIsTrace(false);
474             build.setIsRoot(false);
475             build.setIsEmulator(true);
476         }
477         HiperfCallPluginConfigOuterClass.HiperfCallPluginConfig config = build.build();
478         byte[] configByte = BeanUtil.serializeByCodedOutPutStream(config);
479         ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf =
480             ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD)
481                 .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build();
482         ProfilerServiceTypes.ProfilerSessionConfig sessionConfig =
483             ProfilerServiceTypes.ProfilerSessionConfig.newBuilder()
484                 .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE).addBuffers(bf).build();
485         // 获取插件名称
486         ProfilerServiceTypes.GetCapabilitiesResponse response =
487             HiProfilerClient.getInstance().getCapabilities(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort());
488         List<ProfilerServiceTypes.ProfilerPluginCapability> capabilitiesList = response.getCapabilitiesList();
489         ProfilerServiceTypes.ProfilerPluginCapability profilerPluginCapability =
490             capabilitiesList.stream().filter(item -> item.getName().contains("libhiperf")).findFirst().get();
491         String pluginName = profilerPluginCapability.getName();
492         CommonTypes.ProfilerPluginConfig plugConfig = plugConfig(deviceIPPortInfo, pluginName, configByte, ZERO);
493         return this.createAndStartSession(deviceIPPortInfo, sessionConfig, plugConfig, null, null);
494     }
495 
496     /**
497      * 请求启动session
498      *
499      * @param deviceIPPortInfo deviceIPPortInfo
500      * @param eventsList eventsList
501      * @param fileSuffixTimestampParam fileSuffixTimestampParam
502      * @param inMemoryValue inMemoryValue
503      * @return String
504      */
createSessionHtraceRequestForCpu(DeviceIPPortInfo deviceIPPortInfo, ArrayList<ArrayList<String>> eventsList, String fileSuffixTimestampParam, int inMemoryValue)505     public String createSessionHtraceRequestForCpu(DeviceIPPortInfo deviceIPPortInfo,
506         ArrayList<ArrayList<String>> eventsList, String fileSuffixTimestampParam, int inMemoryValue) {
507         if (ProfilerLogManager.isInfoEnabled()) {
508             LOGGER.info("createSessionHtraceRequestForCpu");
509         }
510         String fileStorePath = "/data/local/tmp/hiprofiler_data";
511         fileStorePath = fileStorePath.concat(fileSuffixTimestampParam).concat(".htrace");
512         TracePluginConfigOuterClass.TracePluginConfig.Builder build =
513             TracePluginConfigOuterClass.TracePluginConfig.newBuilder();
514         if (eventsList != null && !eventsList.isEmpty()) {
515             eventsList.forEach(events -> events.forEach(event -> {
516                 build.addFtraceEvents(event);
517             }));
518         }
519         build.setClock("mono");
520         build.setParseKsyms(true);
521         build.setBufferSizeKb(inMemoryValue * MEMORY_MB_TO_KB);
522         build.setFlushIntervalMs(1000);
523         build.setFlushThresholdKb(4096);
524         TracePluginConfigOuterClass.TracePluginConfig config = build.build();
525         byte[] configByte = BeanUtil.serializeByCodedOutPutStream(config);
526         ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf =
527             ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD)
528                 .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build();
529         ProfilerServiceTypes.ProfilerSessionConfig sessionConfig =
530             ProfilerServiceTypes.ProfilerSessionConfig.newBuilder()
531                 .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.OFFLINE).addBuffers(bf)
532                 .setResultFile(fileStorePath).build();
533         Optional<String> optional = getPluginName(deviceIPPortInfo, "libftrace");
534         if (optional.isPresent()) {
535             String pluginName = optional.get();
536             CommonTypes.ProfilerPluginConfig plugConfig = plugConfig(deviceIPPortInfo, pluginName, configByte, ZERO);
537             return this.createAndStartSession(deviceIPPortInfo, sessionConfig, plugConfig, null, null);
538         } else {
539             return "";
540         }
541     }
542 
543     /**
544      * 请求启动session
545      *
546      * @param deviceIPPortInfo deviceIPPortInfo
547      * @param systemConfigData systemConfigData
548      * @return String
549      * @throws GrpcException GrpcException
550      */
executeHtraceRecording(DeviceIPPortInfo deviceIPPortInfo, SystemConfigData systemConfigData)551     public String executeHtraceRecording(DeviceIPPortInfo deviceIPPortInfo, SystemConfigData systemConfigData)
552         throws GrpcException {
553         if (ProfilerLogManager.isInfoEnabled()) {
554             LOGGER.info("createSessionHtraceRequest");
555         }
556         TracePluginConfigOuterClass.TracePluginConfig traceEventConfiguration =
557             traceEventConfiguration(systemConfigData);
558         byte[] htraceConfigByte = BeanUtil.serializeByCodedOutPutStream(traceEventConfiguration);
559         ProfilerServiceTypes.ProfilerSessionConfig htraceSessionConfig =
560             getHtraceConfig(systemConfigData.getMaxDuration());
561         Optional<String> optional = getPluginName(deviceIPPortInfo, "libftrace");
562         if (optional.isPresent()) {
563             String htracePluginName = optional.get();
564             CommonTypes.ProfilerPluginConfig htracePlugConfig =
565                 plugConfig(deviceIPPortInfo, htracePluginName, htraceConfigByte, systemConfigData.getMaxDuration());
566             return this.createAndStartSession(deviceIPPortInfo, htraceSessionConfig, htracePlugConfig, systemConfigData,
567                 systemConfigData.getHilogLevel());
568         } else {
569             return "";
570         }
571     }
572 
573     /**
574      * 请求启动session
575      *
576      * @param deviceIPPortInfo deviceIPPortInfo
577      * @param systemConfigData systemConfigData
578      * @return String
579      * @throws GrpcException GrpcException
580      */
getHtraceExecuteCommand(DeviceIPPortInfo deviceIPPortInfo, SystemConfigData systemConfigData)581     public String getHtraceExecuteCommand(DeviceIPPortInfo deviceIPPortInfo, SystemConfigData systemConfigData) {
582         if (ProfilerLogManager.isInfoEnabled()) {
583             LOGGER.info("getHtraceTraceCommand");
584         }
585         ProfilerServiceTypes.CreateSessionRequest.Builder request;
586         byte[] htraceConfigByte = BeanUtil.serializeByCodedOutPutStream(traceEventConfiguration(systemConfigData));
587         ProfilerServiceTypes.ProfilerSessionConfig sessionConfig = getHtraceConfig(systemConfigData.getMaxDuration());
588         Optional<String> optionalFtrace = getPluginName(deviceIPPortInfo, "libftrace");
589         if (optionalFtrace.isPresent()) {
590             CommonTypes.ProfilerPluginConfig plugConfig =
591                 plugConfig(deviceIPPortInfo, optionalFtrace.get(), htraceConfigByte, systemConfigData.getMaxDuration());
592             request = ProfilerServiceTypes.CreateSessionRequest.newBuilder().setRequestId(CommonUtil.getRequestId())
593                 .setSessionConfig(sessionConfig).addPluginConfigs(plugConfig);
594         } else {
595             return PROMPT_MISSING_FILE;
596         }
597         // memory
598         if (systemConfigData != null && (systemConfigData.isMemoryInfo() || systemConfigData.isVmemoryInfo())) {
599             Optional<String> optionalMemory = getPluginName(deviceIPPortInfo, "libmem");
600             if (optionalMemory.isPresent()) {
601                 byte[] memoryConfigByte =
602                     BeanUtil.serializeByCodedOutPutStream(memoryEventConfiguration(systemConfigData));
603                 CommonTypes.ProfilerPluginConfig memoryPlugConfig =
604                     plugConfig(deviceIPPortInfo, optionalMemory.get(), memoryConfigByte,
605                         systemConfigData.getMaxDuration());
606                 request = request.addPluginConfigs(memoryPlugConfig);
607             } else {
608                 return PROMPT_MISSING_FILE;
609             }
610         }
611         // hilog
612         if (systemConfigData.getHilogLevel() != null) {
613             Optional<String> hilogPluginNameOption = getPluginName(deviceIPPortInfo, "libhilog");
614             if (hilogPluginNameOption.isPresent()) {
615                 byte[] hilogconfigByte = BeanUtil.serializeByCodedOutPutStream(
616                     hilogEventConfiguration(deviceIPPortInfo, systemConfigData.getHilogLevel()));
617                 CommonTypes.ProfilerPluginConfig hilogPlugConfig =
618                     plugConfig(deviceIPPortInfo, hilogPluginNameOption.get(), hilogconfigByte,
619                         systemConfigData.getMaxDuration());
620                 request = request.addPluginConfigs(hilogPlugConfig);
621             } else {
622                 return PROMPT_MISSING_FILE;
623             }
624         }
625         return request.build().toString();
626     }
627 
628     /**
629      * getHtraceConfig
630      *
631      * @param maxDuration maxDuration
632      * @return ProfilerServiceTypes.ProfilerSessionConfig
633      */
getHtraceConfig(int maxDuration)634     public ProfilerServiceTypes.ProfilerSessionConfig getHtraceConfig(int maxDuration) {
635         ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig bf =
636             ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder().setPages(LayoutConstants.NUMBER_THREAD)
637                 .setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE).build();
638         return ProfilerServiceTypes.ProfilerSessionConfig.newBuilder().setSampleDuration(maxDuration * SECOND_TO_MS)
639             .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.OFFLINE).addBuffers(bf)
640             .setResultFile("/data/local/tmp/hiprofiler_data.htrace").build();
641     }
642 
643     /**
644      * 获取htrace的配置信息
645      *
646      * @param systemConfigData systemConfigData
647      * @return TracePluginConfig byte[]
648      */
traceEventConfiguration(SystemConfigData systemConfigData)649     public TracePluginConfigOuterClass.TracePluginConfig traceEventConfiguration(SystemConfigData systemConfigData) {
650         TracePluginConfigOuterClass.TracePluginConfig.Builder build =
651             TracePluginConfigOuterClass.TracePluginConfig.newBuilder();
652         HashSet hashSet = new HashSet(systemConfigData.getEventsList());
653         systemConfigData.getEventsList().clear();
654         systemConfigData.getEventsList().addAll(hashSet);
655         if (systemConfigData.getEventsList() != null && !systemConfigData.getEventsList().isEmpty()) {
656             systemConfigData.getEventsList().forEach(event -> build.addFtraceEvents(event));
657         }
658         if (systemConfigData.gethTraceEventsList() != null && !systemConfigData.gethTraceEventsList().isEmpty()) {
659             systemConfigData.gethTraceEventsList().forEach(events -> events.forEach(event -> {
660                 build.addBytraceCategories(event);
661             }));
662             build.addBytraceCategories("gfx");
663         }
664         build.setClock("mono");
665         build.setParseKsyms(true);
666         build.setBufferSizeKb(systemConfigData.getInMemoryValue() * MEMORY_MB_TO_KB);
667         build.setFlushIntervalMs(1000);
668         build.setFlushThresholdKb(4096);
669         build.setTracePeriodMs(200);
670         return build.build();
671     }
672 
673     /**
674      * 获取memory的配置信息
675      *
676      * @param systemConfigData systemConfigData
677      * @return MemoryConfig byte[]
678      */
memoryEventConfiguration(SystemConfigData systemConfigData)679     public MemoryPluginConfig.MemoryConfig memoryEventConfiguration(SystemConfigData systemConfigData) {
680         MemoryPluginConfig.MemoryConfig.Builder memoryBuilder = MemoryPluginConfig.MemoryConfig.newBuilder();
681         memoryBuilder.setReportProcessTree(true);
682         memoryBuilder.setReportProcessMemInfo(true);
683         memoryBuilder.setReportSysmemMemInfo(true);
684         memoryBuilder.setReportSysmemVmemInfo(true);
685         if (systemConfigData.isMemoryInfo()) {
686             MEM_INFO.stream()
687                 .forEach(str -> memoryBuilder.addSysMeminfoCounters(MemoryPluginCommon.SysMeminfoType.valueOf(str)));
688         }
689         if (systemConfigData.isVmemoryInfo()) {
690             VMEM_INFO.stream()
691                 .forEach(str -> memoryBuilder.addSysVmeminfoCounters(MemoryPluginCommon.SysVMeminfoType.valueOf(str)));
692             VMEM_INFO_SECOND.stream()
693                 .forEach(str -> memoryBuilder.addSysVmeminfoCounters(MemoryPluginCommon.SysVMeminfoType.valueOf(str)));
694             VMEM_INFO_THIRD.stream()
695                 .forEach(str -> memoryBuilder.addSysVmeminfoCounters(MemoryPluginCommon.SysVMeminfoType.valueOf(str)));
696         }
697         return memoryBuilder.build();
698     }
699 
700     /**
701      * getHilogConfigByte
702      *
703      * @param deviceIPPortInfo deviceIPPortInfo
704      * @param hilogLevel hilogLevel
705      * @return byte[]
706      */
hilogEventConfiguration(DeviceIPPortInfo deviceIPPortInfo, String hilogLevel)707     public HilogPluginConfig.HilogConfig hilogEventConfiguration(DeviceIPPortInfo deviceIPPortInfo, String hilogLevel) {
708         HilogPluginConfig.HilogConfig.Builder hilogBuilder = HilogPluginConfig.HilogConfig.newBuilder();
709         if (deviceIPPortInfo.getDeviceType() == DeviceType.FULL_HOS_DEVICE) {
710             hilogBuilder.setDeviceType(HilogPluginConfig.Type.P40);
711         } else {
712             hilogBuilder.setDeviceType(HilogPluginConfig.Type.HI3516);
713         }
714         hilogBuilder.setLogLevel(HilogPluginConfig.Level.valueOf(hilogLevel));
715         hilogBuilder.setNeedClear(true);
716         return hilogBuilder.build();
717     }
718 
719     /**
720      * getFtraceSha
721      *
722      * @param deviceIPPortInfo deviceIPPortInfo
723      * @param pluginFtraceName pluginFtraceName
724      * @return String
725      */
getPluginSha(DeviceIPPortInfo deviceIPPortInfo, String pluginFtraceName)726     public String getPluginSha(DeviceIPPortInfo deviceIPPortInfo, String pluginFtraceName) {
727         String sha256;
728         if (IS_SUPPORT_NEW_HDC && deviceIPPortInfo.getDeviceType() == LEAN_HOS_DEVICE) {
729             sha256 = getSTDSha256(pluginFtraceName);
730         } else {
731             sha256 = getSha256(pluginFtraceName);
732         }
733         return sha256;
734     }
735 
736     /**
737      * push htrace command file to device
738      *
739      * @param commandStr commandStr
740      * @param timeStamp timeStamp
741      * @param deviceIPPortInfo deviceIPPortInfo
742      * @return String
743      */
pushHtraceCommandFile(String commandStr, String timeStamp, DeviceIPPortInfo deviceIPPortInfo)744     public String pushHtraceCommandFile(String commandStr, String timeStamp, DeviceIPPortInfo deviceIPPortInfo) {
745         String baseDir = TraceStreamerUtils.getInstance().getCreateFileDir();
746         String commandFileName = "command".concat(timeStamp).concat(".txt");
747         String commandFileStorePath = baseDir.concat(commandFileName);
748         File txt = new File(commandFileStorePath);
749         try {
750             if (!txt.exists()) {
751                 txt.createNewFile();
752             }
753             byte[] bytes = commandStr.getBytes();
754             FileOutputStream fos = new FileOutputStream(txt);
755             fos.write(bytes, 0, bytes.length);
756             fos.close();
757         } catch (IOException io) {
758             if (ProfilerLogManager.isErrorEnabled()) {
759                 LOGGER.error("pushHtraceCommandFile fail:", io.getMessage());
760             }
761         }
762         ArrayList pushCmd;
763         ArrayList clearCommand;
764         if (IS_SUPPORT_NEW_HDC && deviceIPPortInfo.getDeviceType() == LEAN_HOS_DEVICE) {
765             clearCommand = conversionCommand(HDC_STD_ROOT_CLEAR_COMMAND, deviceIPPortInfo.getDeviceID());
766             pushCmd = conversionCommand(HDC_STD_PUSH_FILE_SHELL, deviceIPPortInfo.getDeviceID(), commandFileStorePath,
767                 FILE_PATH);
768         } else {
769             clearCommand = conversionCommand(HDC_CLEAR_COMMAND_CMD, deviceIPPortInfo.getDeviceID());
770             pushCmd =
771                 conversionCommand(HDC_PUSH_FILE_SHELL, deviceIPPortInfo.getDeviceID(), commandFileStorePath, FILE_PATH);
772         }
773         HdcWrapper.getInstance().execCmdBy(clearCommand);
774         HdcWrapper.getInstance().execCmdBy(pushCmd);
775         if (ProfilerLogManager.isInfoEnabled()) {
776             LOGGER.info("pushHtraceCommandFile success", pushCmd);
777         }
778         return FILE_PATH.concat("/").concat(commandFileName);
779     }
780 
781     /**
782      * 获取插件名称
783      *
784      * @param deviceIPPortInfo deviceIPPortInfo
785      * @param PluginName PluginName
786      * @return Optional
787      */
getPluginName(DeviceIPPortInfo deviceIPPortInfo, String PluginName)788     public Optional getPluginName(DeviceIPPortInfo deviceIPPortInfo, String PluginName) {
789         if (ProfilerLogManager.isInfoEnabled()) {
790             LOGGER.info("getPluginName");
791         }
792         ProfilerServiceTypes.GetCapabilitiesResponse response =
793             HiProfilerClient.getInstance().getCapabilities(deviceIPPortInfo.getIp(), deviceIPPortInfo.getForwardPort());
794         List<ProfilerServiceTypes.ProfilerPluginCapability> capabilitiesList = response.getCapabilitiesList();
795         if (capabilitiesList.isEmpty()) {
796             return Optional.empty();
797         }
798         if (Optional.ofNullable(capabilitiesList).isPresent()) {
799             List<ProfilerServiceTypes.ProfilerPluginCapability> capabilitiesLists =
800                 capabilitiesList.stream().filter(item -> item.getName().contains(PluginName))
801                     .collect(Collectors.toList());
802             if (capabilitiesLists.size() > 0) {
803                 ProfilerServiceTypes.ProfilerPluginCapability profilerPluginCapability = capabilitiesLists.get(0);
804                 return Optional.of(profilerPluginCapability.getName());
805             } else {
806                 return Optional.empty();
807             }
808         } else {
809             return Optional.empty();
810         }
811     }
812 
startKeepLiveSession(DeviceIPPortInfo deviceIPPortInfo, int sessionId, long localSessionId)813     private void startKeepLiveSession(DeviceIPPortInfo deviceIPPortInfo, int sessionId, long localSessionId) {
814         if (ProfilerLogManager.isInfoEnabled()) {
815             LOGGER.info("startKeepLiveSession");
816         }
817         String keepSessionName = getKeepSessionName(deviceIPPortInfo, sessionId);
818         QuartzManager.getInstance()
819             .addExecutor(keepSessionName, new KeepSession(localSessionId, sessionId, deviceIPPortInfo));
820         QuartzManager.getInstance().startExecutor(keepSessionName, 0, KEEP_SESSION_REQUEST_TIME);
821     }
822 
823     /**
824      * getKeepSessionName
825      *
826      * @param deviceIPPortInfo deviceIPPortInfo
827      * @param sessionId sessionId
828      * @return String
829      */
getKeepSessionName(DeviceIPPortInfo deviceIPPortInfo, int sessionId)830     public String getKeepSessionName(DeviceIPPortInfo deviceIPPortInfo, int sessionId) {
831         if (ProfilerLogManager.isInfoEnabled()) {
832             LOGGER.info("getKeepSessionName");
833         }
834         if (Objects.nonNull(deviceIPPortInfo)) {
835             return "KEEP" + deviceIPPortInfo.getDeviceName() + sessionId;
836         } else {
837             return "";
838         }
839     }
840 
841     /**
842      * 请求启动session
843      *
844      * @param deviceIPPortInfo deviceIPPortInfo
845      * @param systemConfigData systemConfigData
846      * @return String String
847      * @throws GrpcException GrpcException
848      */
showHtraceCommand(DeviceIPPortInfo deviceIPPortInfo, SystemConfigData systemConfigData)849     public String showHtraceCommand(DeviceIPPortInfo deviceIPPortInfo, SystemConfigData systemConfigData) {
850         if (ProfilerLogManager.isInfoEnabled()) {
851             LOGGER.info("showHtraceCommand");
852         }
853         if (deviceIPPortInfo == null) {
854             return PROMPT_INFORMATION;
855         }
856         ProfilerServiceTypes.ProfilerSessionConfig sessionConfig = getHtraceConfig(systemConfigData.getMaxDuration());
857         ProfilerServiceTypes.CreateSessionRequest.Builder request =
858             ProfilerServiceTypes.CreateSessionRequest.newBuilder().setRequestId(CommonUtil.getRequestId())
859                 .setSessionConfig(sessionConfig);
860         // htrace
861         Optional<String> optionalFtrace = getPluginName(deviceIPPortInfo, "libftrace");
862         if (optionalFtrace.isPresent()) {
863             TracePluginConfigOuterClass.TracePluginConfig htraceEventConfiguration =
864                 traceEventConfiguration(systemConfigData);
865             CommonTypes.ProfilerPluginConfig htracePlugConfig =
866                 commandPlugConfig(deviceIPPortInfo, optionalFtrace.get(), htraceEventConfiguration.toString());
867             request = request.addPluginConfigs(htracePlugConfig);
868         } else {
869             return PROMPT_MISSING_FILE;
870         }
871         // memory
872         if (systemConfigData != null && (systemConfigData.isMemoryInfo() || systemConfigData.isVmemoryInfo())) {
873             Optional<String> optionalMemory = getPluginName(deviceIPPortInfo, "libmem");
874             if (optionalMemory.isPresent()) {
875                 MemoryPluginConfig.MemoryConfig memoryEventConfiguration = memoryEventConfiguration(systemConfigData);
876                 CommonTypes.ProfilerPluginConfig memoryPlugConfig =
877                     commandPlugConfig(deviceIPPortInfo, optionalMemory.get(), memoryEventConfiguration.toString());
878                 request = request.addPluginConfigs(memoryPlugConfig);
879             } else {
880                 return PROMPT_MISSING_FILE;
881             }
882         }
883         // hilog
884         if (systemConfigData.getHilogLevel() != null) {
885             Optional<String> hilogPluginNameOption = getPluginName(deviceIPPortInfo, "libhilog");
886             if (hilogPluginNameOption.isPresent()) {
887                 HilogPluginConfig.HilogConfig hilogEventConfiguration =
888                     hilogEventConfiguration(deviceIPPortInfo, systemConfigData.getHilogLevel());
889                 CommonTypes.ProfilerPluginConfig hilogPlugConfig =
890                     commandPlugConfig(deviceIPPortInfo, hilogPluginNameOption.get(),
891                         hilogEventConfiguration.toString());
892                 request = request.addPluginConfigs(hilogPlugConfig);
893             } else {
894                 return PROMPT_MISSING_FILE;
895             }
896         }
897         return request.build().toString();
898     }
899 
900     /**
901      * plugConfig
902      *
903      * @param deviceIPPortInfoParam deviceIPPortInfoParam
904      * @param pluginName pluginName
905      * @param configByteParam configByteParam
906      * @return CommonTypes.ProfilerPluginConfi
907      */
commandPlugConfig(DeviceIPPortInfo deviceIPPortInfoParam, String pluginName, String configByteParam)908     public CommonTypes.ProfilerPluginConfig commandPlugConfig(DeviceIPPortInfo deviceIPPortInfoParam, String pluginName,
909         String configByteParam) {
910         if (ProfilerLogManager.isInfoEnabled()) {
911             LOGGER.info("plugConfig");
912         }
913         String Sha256;
914         if (IS_SUPPORT_NEW_HDC && deviceIPPortInfoParam.getDeviceType() == LEAN_HOS_DEVICE) {
915             Sha256 = getSTDSha256(pluginName);
916         } else {
917             Sha256 = getSha256(pluginName);
918         }
919         return CommonTypes.ProfilerPluginConfig.newBuilder().setPluginSha256(Sha256).setName(pluginName)
920             .setSampleInterval(5000)
921             .setConfigData(ByteString.copyFrom(configByteParam.getBytes(StandardCharsets.UTF_8))).build();
922     }
923 }
924