• 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.utils.session.service;
17 
18 import com.intellij.ide.plugins.PluginManager;
19 import com.intellij.ide.util.PropertiesComponent;
20 import com.intellij.openapi.application.Application;
21 import com.intellij.openapi.application.ApplicationManager;
22 import com.intellij.openapi.application.PathManager;
23 import com.intellij.openapi.extensions.PluginId;
24 import com.intellij.openapi.project.Project;
25 import io.grpc.StatusRuntimeException;
26 import ohos.devtools.datasources.databases.datatable.MemoryTable;
27 import ohos.devtools.datasources.databases.datatable.enties.DiskIOData;
28 import ohos.devtools.datasources.databases.datatable.enties.EnergyLocationInfo;
29 import ohos.devtools.datasources.databases.datatable.enties.ProcessCpuData;
30 import ohos.devtools.datasources.databases.datatable.enties.ProcessMemInfo;
31 import ohos.devtools.datasources.transport.grpc.HiProfilerClient;
32 import ohos.devtools.datasources.transport.grpc.ProfilerServiceHelper;
33 import ohos.devtools.datasources.transport.grpc.service.CommonTypes;
34 import ohos.devtools.datasources.transport.grpc.service.ProfilerServiceTypes;
35 import ohos.devtools.datasources.transport.hdc.HdcWrapper;
36 import ohos.devtools.datasources.utils.common.Constant;
37 import ohos.devtools.datasources.utils.common.util.CommonUtil;
38 import ohos.devtools.datasources.utils.common.util.DateTimeUtil;
39 import ohos.devtools.datasources.utils.common.util.Validate;
40 import ohos.devtools.datasources.utils.datahandler.datapoller.DataPoller;
41 import ohos.devtools.datasources.utils.device.entity.DeviceIPPortInfo;
42 import ohos.devtools.datasources.utils.device.entity.DeviceProcessInfo;
43 import ohos.devtools.datasources.utils.device.entity.DeviceType;
44 import ohos.devtools.datasources.utils.device.entity.TraceFileInfo;
45 import ohos.devtools.datasources.utils.plugin.entity.AnalysisType;
46 import ohos.devtools.datasources.utils.plugin.entity.HiProfilerPluginConfig;
47 import ohos.devtools.datasources.utils.plugin.entity.PluginBufferConfig;
48 import ohos.devtools.datasources.utils.plugin.entity.PluginConf;
49 import ohos.devtools.datasources.utils.plugin.entity.PluginMode;
50 import ohos.devtools.datasources.utils.plugin.service.PlugManager;
51 import ohos.devtools.datasources.utils.process.entity.ProcessInfo;
52 import ohos.devtools.datasources.utils.process.service.ProcessManager;
53 import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager;
54 import ohos.devtools.datasources.utils.quartzmanager.QuartzManager;
55 import ohos.devtools.datasources.utils.session.KeepSession;
56 import ohos.devtools.datasources.utils.session.entity.SessionInfo;
57 import ohos.devtools.services.cpu.CpuDao;
58 import ohos.devtools.services.cpu.CpuService;
59 import ohos.devtools.services.cpu.CpuValidate;
60 import ohos.devtools.services.diskio.DiskIoService;
61 import ohos.devtools.services.diskio.DiskIoValidate;
62 import ohos.devtools.services.memory.MemoryValidate;
63 import ohos.devtools.services.memory.agentbean.ClassInfo;
64 import ohos.devtools.services.memory.agentbean.MemoryHeapInfo;
65 import ohos.devtools.services.memory.agentbean.MemoryInstanceDetailsInfo;
66 import ohos.devtools.services.memory.agentdao.ClassInfoDao;
67 import ohos.devtools.services.memory.agentdao.ClassInfoManager;
68 import ohos.devtools.services.memory.agentdao.MemoryHeapDao;
69 import ohos.devtools.services.memory.agentdao.MemoryHeapManager;
70 import ohos.devtools.services.memory.agentdao.MemoryInstanceDao;
71 import ohos.devtools.services.memory.agentdao.MemoryInstanceDetailsDao;
72 import ohos.devtools.services.memory.agentdao.MemoryInstanceDetailsManager;
73 import ohos.devtools.services.memory.agentdao.MemoryInstanceManager;
74 import ohos.devtools.services.memory.agentdao.MemoryUpdateInfo;
75 import ohos.devtools.services.memory.memoryservice.MemoryService;
76 import ohos.devtools.services.userdata.UserDataService;
77 import ohos.devtools.views.common.LayoutConstants;
78 import ohos.devtools.views.layout.chartview.ProfilerChartsView;
79 import ohos.devtools.views.layout.dialog.ExportFileChooserDialog;
80 import org.apache.commons.codec.digest.DigestUtils;
81 import org.apache.commons.lang3.StringUtils;
82 import org.apache.logging.log4j.LogManager;
83 import org.apache.logging.log4j.Logger;
84 
85 import static ohos.devtools.datasources.transport.hdc.HdcCmdList.CHMOD_TO_OHOS;
86 
87 import javax.swing.JProgressBar;
88 import java.io.BufferedInputStream;
89 import java.io.BufferedOutputStream;
90 import java.io.File;
91 import java.io.FileInputStream;
92 import java.io.FileOutputStream;
93 import java.io.IOException;
94 import java.io.InputStream;
95 import java.io.ObjectInputStream;
96 import java.io.ObjectOutputStream;
97 import java.util.ArrayList;
98 import java.util.Date;
99 import java.util.HashMap;
100 import java.util.LinkedList;
101 import java.util.List;
102 import java.util.Locale;
103 import java.util.Objects;
104 import java.util.Optional;
105 import java.util.Set;
106 import java.util.concurrent.TimeUnit;
107 
108 import static ohos.devtools.datasources.transport.hdc.HdcCmdList.HDC_CHMOD_PROC;
109 import static ohos.devtools.datasources.transport.hdc.HdcStdCmdList.HDC_STD_CHMOD_PROC;
110 import static ohos.devtools.datasources.transport.hdc.HdcWrapper.conversionCommand;
111 import static ohos.devtools.datasources.utils.common.Constant.DEVTOOLS_PLUGINS_FULL_PATH;
112 import static ohos.devtools.datasources.utils.device.entity.DeviceType.FULL_HOS_DEVICE;
113 import static ohos.devtools.datasources.utils.device.entity.DeviceType.LEAN_HOS_DEVICE;
114 import static ohos.devtools.datasources.utils.plugin.entity.PluginBufferConfig.Policy.RECYCLE;
115 import static ohos.devtools.views.common.Constant.IS_SUPPORT_NEW_HDC;
116 
117 /**
118  * session Management core class
119  *
120  * @since 2021/5/19 16:39
121  */
122 public class SessionManager {
123     private static final Logger LOGGER = LogManager.getLogger(SessionManager.class);
124     private static final int KEEP_SESSION_TIME = 10000;
125     private static final int KEEP_SESSION_REQUEST_TIME = 3000;
126     private static final String STD_DEVELOPTOOLS = "stddeveloptools";
127     private static final SessionManager SINGLETON = new SessionManager();
128 
129     private Project project;
130     private HashMap<Long, SessionInfo> profilingSessions;
131     private HashMap<Long, DataPoller> dataPollerHashMap = new HashMap<>();
132     private MemoryTable memoTable;
133     private ClassInfoDao classInfoDao;
134     private MemoryHeapDao memoryHeapDao;
135     private MemoryInstanceDao memoryInstanceDao;
136     private MemoryInstanceDetailsDao memoryInstanceDetailsDao;
137 
SessionManager()138     private SessionManager() {
139         profilingSessions = new HashMap<>();
140     }
141 
142     /**
143      * getInstance
144      *
145      * @return SessionManager
146      */
getInstance()147     public static SessionManager getInstance() {
148         return SessionManager.SINGLETON;
149     }
150 
151     /**
152      * Clear session Id directly, use with caution
153      *
154      * @param localSessionId localSessionId
155      */
deleteLocalSession(Long localSessionId)156     public void deleteLocalSession(Long localSessionId) {
157         if (ProfilerLogManager.isInfoEnabled()) {
158             LOGGER.info("deleteLocalSession");
159         }
160         if (profilingSessions != null) {
161             ProfilerChartsView profilerChartsView = ProfilerChartsView.sessionMap.get(localSessionId);
162             if (profilerChartsView != null) {
163                 profilerChartsView.getPublisher().stopRefresh(true);
164             }
165             SessionInfo sessionInfo = profilingSessions.get(localSessionId);
166             if (Objects.nonNull(sessionInfo)) {
167                 String keepSessionName =
168                     getKeepSessionName(sessionInfo.getDeviceIPPortInfo(), sessionInfo.getSessionId());
169                 QuartzManager.getInstance().deleteExecutor(keepSessionName);
170             }
171             DataPoller dataPoller = dataPollerHashMap.get(localSessionId);
172             if (Objects.nonNull(dataPoller)) {
173                 dataPoller.shutDown();
174             }
175             removeLocalSessionData(localSessionId);
176         }
177     }
178 
removeLocalSessionData(long localSessionId)179     private void removeLocalSessionData(long localSessionId) {
180         CpuService.getInstance().deleteSessionData(localSessionId);
181         MemoryService.getInstance().deleteSessionData(localSessionId);
182         DiskIoService.getInstance().deleteSessionData(localSessionId);
183         UserDataService.getInstance().deleteSessionData(localSessionId);
184         deleteAllAgentData(localSessionId, true);
185         profilingSessions.remove(localSessionId);
186     }
187 
getProject()188     public Project getProject() {
189         return project;
190     }
191 
setProject(Project project)192     public void setProject(Project project) {
193         this.project = project;
194     }
195 
196     /**
197      * Create Session based on device information, process information, and specific scenarios
198      *
199      * @param device device
200      * @param process process
201      * @param analysisType analysisType
202      * @return Long sessionId
203      */
createSession(DeviceIPPortInfo device, ProcessInfo process, AnalysisType analysisType)204     public Long createSession(DeviceIPPortInfo device, ProcessInfo process, AnalysisType analysisType) {
205         if (device == null || process == null) {
206             return Constant.ABNORMAL;
207         }
208         long localSessionID = CommonUtil.getLocalSessionId();
209         if (analysisType == AnalysisType.GPU_CONFIG_TYPE) {
210             return handleGpuConfig(device, process, analysisType, localSessionID);
211         }
212         List<ProfilerServiceTypes.ProfilerPluginCapability> capability = getProfilerPluginCapabilities(device);
213         if (capability == null || capability.size() == 0) {
214             return Constant.ABNORMAL;
215         }
216         ProfilerServiceTypes.ProfilerSessionConfig.Builder sessionConfigBuilder =
217             getSessionConfigBuilder(device, process);
218         List<CommonTypes.ProfilerPluginConfig> plugs = new ArrayList();
219         List<PluginConf> configs =
220             PlugManager.getInstance().getPluginConfig(device.getDeviceType(), PluginMode.ONLINE, analysisType);
221         for (PluginConf conf : configs) {
222             if (handlespecailconfig(localSessionID, conf)) {
223                 continue;
224             }
225             if (conf.isSpecialStart()) {
226                 boolean startResult = conf.getSpecialStartPlugMethod().specialStartPlugMethod(device, process);
227                 try {
228                     TimeUnit.MILLISECONDS.sleep(3500);
229                 } catch (InterruptedException interruptedException) {
230                     LOGGER.error("sleep");
231                 }
232                 List<ProfilerServiceTypes.ProfilerPluginCapability> caps = getProfilerPluginCapabilities(device);
233                 Optional<ProfilerServiceTypes.ProfilerPluginCapability> plug =
234                     getLibPlugin(caps, conf.getGetPluginName().getPluginName(device, process));
235                 if (startResult && plug.isPresent()) {
236                     sessionConfigBuilder.addBuffers(getBufferConfig(conf));
237                     HiProfilerPluginConfig config = conf.getICreatePluginConfig().createPluginConfig(device, process);
238                     plugs.add(getAgentPluginConfig(conf, plug.get(), config));
239                     PlugManager.getInstance().addPluginStartSuccess(localSessionID, conf);
240                 }
241             } else {
242                 Optional<ProfilerServiceTypes.ProfilerPluginCapability> plug =
243                     getLibPlugin(capability, conf.getPluginFileName());
244                 if (plug.isPresent()) {
245                     sessionConfigBuilder.addBuffers(getBufferConfig(conf));
246                     CommonTypes.ProfilerPluginConfig pluginConfig = getProfilerPluginConfig(conf, plug.get(),
247                         conf.getICreatePluginConfig().createPluginConfig(device, process), device);
248                     plugs.add(pluginConfig);
249                     PlugManager.getInstance().addPluginStartSuccess(localSessionID, conf);
250                 }
251             }
252         }
253         return resultCreateSesion(device, process, localSessionID, sessionConfigBuilder, plugs);
254     }
255 
getPluginCapability(DeviceIPPortInfo device, ProcessInfo process, PluginConf conf)256     private void getPluginCapability(DeviceIPPortInfo device, ProcessInfo process, PluginConf conf) {
257         Optional<ProfilerServiceTypes.ProfilerPluginCapability> plug;
258         do {
259             List<ProfilerServiceTypes.ProfilerPluginCapability> caps =
260                 getProfilerPluginCapabilities(device);
261             plug = getLibPlugin(caps, conf.getGetPluginName().getPluginName(device, process));
262             try {
263                 TimeUnit.MILLISECONDS.sleep(1000);
264             } catch (InterruptedException interruptedException) {
265                 LOGGER.error("sleep");
266             }
267         } while (!plug.isPresent());
268     }
269 
handlespecailconfig(long localSessionID, PluginConf conf)270     private boolean handlespecailconfig(long localSessionID, PluginConf conf) {
271         if (conf.isAlwaysAdd()) {
272             PlugManager.getInstance().addPluginStartSuccess(localSessionID, conf);
273             return true;
274         }
275         if (conf.isOperationStart()) {
276             return true;
277         }
278         return false;
279     }
280 
resultCreateSesion(DeviceIPPortInfo device, ProcessInfo process, long localSessionID, ProfilerServiceTypes.ProfilerSessionConfig.Builder sessionConfigBuilder, List<CommonTypes.ProfilerPluginConfig> plugs)281     private Long resultCreateSesion(DeviceIPPortInfo device, ProcessInfo process, long localSessionID,
282         ProfilerServiceTypes.ProfilerSessionConfig.Builder sessionConfigBuilder,
283         List<CommonTypes.ProfilerPluginConfig> plugs) {
284         if (!plugs.isEmpty()) {
285             ProfilerServiceTypes.CreateSessionResponse res = createSessionResponse(device, sessionConfigBuilder, plugs);
286             if (res.getSessionId() > 0) {
287                 startKeepLiveSession(device, res.getSessionId(), localSessionID);
288                 profilingSessions.put(localSessionID, createSessionInfo(device, process, res.getSessionId()));
289                 if (ProfilerLogManager.isInfoEnabled()) {
290                     LOGGER.info("Task with Session created successfully");
291                 }
292                 return localSessionID;
293             }
294         }
295         if (ProfilerLogManager.isErrorEnabled()) {
296             LOGGER.error("Failed to create task with Session!");
297         }
298         return Constant.ABNORMAL;
299     }
300 
handleGpuConfig(DeviceIPPortInfo device, ProcessInfo process, AnalysisType analysisType, long localSessionID)301     private long handleGpuConfig(DeviceIPPortInfo device, ProcessInfo process, AnalysisType analysisType,
302         long localSessionID) {
303         List<PluginConf> configs =
304             PlugManager.getInstance().getPluginConfig(device.getDeviceType(), PluginMode.ONLINE, analysisType);
305         for (PluginConf conf : configs) {
306             if (conf.isAlwaysAdd()) {
307                 PlugManager.getInstance().addPluginStartSuccess(localSessionID, conf);
308                 continue;
309             }
310         }
311         profilingSessions.put(localSessionID, createSessionInfo(device, process, Integer.MAX_VALUE));
312         return localSessionID;
313     }
314 
getProfilerPluginConfig(PluginConf conf, ProfilerServiceTypes.ProfilerPluginCapability plug, HiProfilerPluginConfig pluginConfig, DeviceIPPortInfo device)315     private CommonTypes.ProfilerPluginConfig getProfilerPluginConfig(PluginConf conf,
316         ProfilerServiceTypes.ProfilerPluginCapability plug, HiProfilerPluginConfig pluginConfig,
317         DeviceIPPortInfo device) {
318         if (ProfilerLogManager.isInfoEnabled()) {
319             LOGGER.info("getProfilerPluginConfig", pluginConfig);
320         }
321         String pluginFileName = conf.getPluginFileName();
322         String fileName = pluginFileName.substring(pluginFileName.lastIndexOf("/") + 1);
323         StringBuilder stringBuilder = new StringBuilder();
324         if (IS_SUPPORT_NEW_HDC && device.getDeviceType() == LEAN_HOS_DEVICE) {
325             stringBuilder.append(SessionManager.getInstance().tempPath()).append(STD_DEVELOPTOOLS)
326                 .append(File.separator).append(fileName);
327         } else {
328             stringBuilder.append(SessionManager.getInstance().getPluginPath()).append(DEVTOOLS_PLUGINS_FULL_PATH)
329                 .append(File.separator).append(fileName);
330         }
331         return ProfilerServiceHelper
332             .profilerPluginConfig(plug.getName(), "", pluginConfig.getSampleInterval(),
333                 pluginConfig.getConfData());
334     }
335 
getAgentPluginConfig(PluginConf conf, ProfilerServiceTypes.ProfilerPluginCapability plug, HiProfilerPluginConfig pluginConfig)336     private CommonTypes.ProfilerPluginConfig getAgentPluginConfig(PluginConf conf,
337         ProfilerServiceTypes.ProfilerPluginCapability plug, HiProfilerPluginConfig pluginConfig) {
338         if (ProfilerLogManager.isInfoEnabled()) {
339             LOGGER.info("getAgentProfilerPluginConfig", pluginConfig);
340         }
341         String pluginFileName = conf.getPluginFileName();
342         String fileName = pluginFileName.substring(pluginFileName.lastIndexOf("/") + 1);
343         StringBuilder stringBuilder = new StringBuilder(SessionManager.getInstance().getPluginPath());
344         stringBuilder.append(DEVTOOLS_PLUGINS_FULL_PATH).append(File.separator).append(fileName).toString();
345         return ProfilerServiceHelper
346             .profilerPluginConfig(plug.getName(), "", pluginConfig.getSampleInterval(), pluginConfig.getConfData());
347     }
348 
getBufferConfig(PluginConf conf)349     private ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig getBufferConfig(PluginConf conf) {
350         if (ProfilerLogManager.isInfoEnabled()) {
351             LOGGER.info("getBufferConfig");
352         }
353         PluginBufferConfig pluginBufferConfig = conf.getPluginBufferConfig();
354         ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Builder builder =
355             ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.newBuilder();
356         if (pluginBufferConfig.getPolicy() == RECYCLE) {
357             builder.setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.RECYCLE);
358         } else {
359             builder.setPolicy(ProfilerServiceTypes.ProfilerSessionConfig.BufferConfig.Policy.FLATTEN);
360         }
361         return builder.setPages(pluginBufferConfig.getPages()).build();
362     }
363 
createSessionResponse(DeviceIPPortInfo device, ProfilerServiceTypes.ProfilerSessionConfig.Builder sessionConfigBuilder, List<CommonTypes.ProfilerPluginConfig> plugs)364     private ProfilerServiceTypes.CreateSessionResponse createSessionResponse(DeviceIPPortInfo device,
365         ProfilerServiceTypes.ProfilerSessionConfig.Builder sessionConfigBuilder,
366         List<CommonTypes.ProfilerPluginConfig> plugs) {
367         if (ProfilerLogManager.isInfoEnabled()) {
368             LOGGER.info("createSessionResponse");
369         }
370         ProfilerServiceTypes.CreateSessionRequest request =
371             ProfilerServiceHelper.createSessionRequest(CommonUtil.getRequestId(), sessionConfigBuilder.build(), plugs);
372         return HiProfilerClient.getInstance().requestCreateSession(device.getIp(), device.getForwardPort(), request);
373     }
374 
getProfilerPluginCapabilities(DeviceIPPortInfo device)375     private List<ProfilerServiceTypes.ProfilerPluginCapability> getProfilerPluginCapabilities(DeviceIPPortInfo device) {
376         if (ProfilerLogManager.isInfoEnabled()) {
377             LOGGER.info("getProfilerPluginCapabilities");
378         }
379         if (device.getForwardPort() == 0) {
380             ArrayList<ProfilerServiceTypes.ProfilerPluginCapability> capabilities =
381                 new ArrayList<ProfilerServiceTypes.ProfilerPluginCapability>();
382             capabilities.add(ProfilerServiceTypes.ProfilerPluginCapability.newBuilder().build());
383             return capabilities;
384         }
385         ProfilerServiceTypes.GetCapabilitiesResponse capabilitiesRes =
386             HiProfilerClient.getInstance().getCapabilities(device.getIp(), device.getForwardPort());
387         if (ProfilerLogManager.isInfoEnabled()) {
388             LOGGER.info("capability {}", capabilitiesRes.getCapabilitiesList());
389         }
390         return capabilitiesRes.getCapabilitiesList();
391     }
392 
getSessionConfigBuilder(DeviceIPPortInfo device, ProcessInfo process)393     private ProfilerServiceTypes.ProfilerSessionConfig.Builder getSessionConfigBuilder(DeviceIPPortInfo device,
394         ProcessInfo process) {
395         if (ProfilerLogManager.isInfoEnabled()) {
396             LOGGER.info("getSessionConfigBuilder");
397         }
398         if (device.getDeviceType() == FULL_HOS_DEVICE) {
399             boolean isDebug = ProcessManager.getInstance().checkIsDebuggerProcess(device, process);
400             if (isDebug) {
401                 return ProfilerServiceTypes.ProfilerSessionConfig.newBuilder().setKeepAliveTime(10000)
402                     .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE);
403             }
404         }
405         return ProfilerServiceTypes.ProfilerSessionConfig.newBuilder().setKeepAliveTime(KEEP_SESSION_TIME)
406             .setSessionMode(ProfilerServiceTypes.ProfilerSessionConfig.Mode.ONLINE);
407     }
408 
startKeepLiveSession(DeviceIPPortInfo deviceIPPortInfo, int sessionId, long localSessionId)409     private void startKeepLiveSession(DeviceIPPortInfo deviceIPPortInfo, int sessionId, long localSessionId) {
410         if (ProfilerLogManager.isInfoEnabled()) {
411             LOGGER.info("startKeepLiveSession");
412         }
413         String keepSessionName = getKeepSessionName(deviceIPPortInfo, sessionId);
414         QuartzManager.getInstance()
415             .addExecutor(keepSessionName, new KeepSession(localSessionId, sessionId, deviceIPPortInfo));
416         QuartzManager.getInstance().startExecutor(keepSessionName, 0, KEEP_SESSION_REQUEST_TIME);
417     }
418 
419     /**
420      * createSessionOperationStart
421      *
422      * @param device device
423      * @param process process
424      * @param configName configName
425      * @return long
426      */
createSessionOperationStart(DeviceIPPortInfo device, ProcessInfo process, String configName)427     public long createSessionOperationStart(DeviceIPPortInfo device, ProcessInfo process, String configName) {
428         Optional<PluginConf> pluginConfigOpt = PlugManager.getInstance().getPluginConfigByName(configName);
429         if (pluginConfigOpt.isPresent()) {
430             PluginConf pluginConf = pluginConfigOpt.get();
431             List<ProfilerServiceTypes.ProfilerPluginCapability> profilerPluginCapabilities =
432                 getProfilerPluginCapabilities(device);
433             Optional<ProfilerServiceTypes.ProfilerPluginCapability> plug =
434                 getLibPlugin(profilerPluginCapabilities, pluginConf.getPluginDataName());
435             if (plug.isPresent()) {
436                 ProfilerServiceTypes.ProfilerSessionConfig.Builder sessionConfigBuilder =
437                     getSessionConfigBuilder(device, process);
438                 sessionConfigBuilder.addBuffers(getBufferConfig(pluginConf));
439                 CommonTypes.ProfilerPluginConfig pluginConfig = getProfilerPluginConfig(pluginConf, plug.get(),
440                     pluginConf.getICreatePluginConfig().createPluginConfig(device, process), device);
441                 ArrayList<CommonTypes.ProfilerPluginConfig> profilerPluginConfigs = new ArrayList<>();
442                 profilerPluginConfigs.add(pluginConfig);
443                 long localSessionID = CommonUtil.getLocalSessionId();
444                 return resultCreateSesion(device, process, localSessionID, sessionConfigBuilder, profilerPluginConfigs);
445             }
446         }
447         return Constant.ABNORMAL;
448     }
449 
450     /**
451      * stopAndDestoryOperation
452      *
453      * @param secondId secondId
454      * @return boolean
455      */
stopAndDestoryOperation(long secondId)456     public boolean stopAndDestoryOperation(long secondId) {
457         if (secondId <= 0) {
458             return false;
459         }
460         SessionInfo session = profilingSessions.get(secondId);
461         if (session == null) {
462             return false;
463         }
464         String keepSessionName = getKeepSessionName(session.getDeviceIPPortInfo(), session.getSessionId());
465         QuartzManager.getInstance().deleteExecutor(keepSessionName);
466         int sessionId = session.getSessionId();
467         if (ProfilerLogManager.isInfoEnabled()) {
468             LOGGER.info("deleteSession sessionId {}", sessionId);
469         }
470         DeviceIPPortInfo device = session.getDeviceIPPortInfo();
471         if (Objects.isNull(device)) {
472             return false;
473         }
474         boolean stopSessionRes =
475             HiProfilerClient.getInstance().requestStopSession(device.getIp(), device.getForwardPort(), sessionId, true);
476         if (stopSessionRes) {
477             boolean destroySessionRes = false;
478             try {
479                 destroySessionRes = HiProfilerClient.getInstance()
480                     .requestDestroySession(device.getIp(), device.getForwardPort(), sessionId);
481             } catch (StatusRuntimeException exception) {
482                 if (ProfilerLogManager.isErrorEnabled()) {
483                     LOGGER.error("StatusRuntimeException", exception);
484                 }
485             } finally {
486                 profilingSessions.remove(secondId);
487             }
488             if (ProfilerLogManager.isInfoEnabled()) {
489                 LOGGER.info("Session deleted successfully.");
490             }
491             return destroySessionRes;
492         } else {
493             if (ProfilerLogManager.isErrorEnabled()) {
494                 LOGGER.error("Failed to delete Session ");
495             }
496             return false;
497         }
498     }
499 
500     /**
501      * getKeepSessionName
502      *
503      * @param deviceIPPortInfo deviceIPPortInfo
504      * @param sessionId sessionId
505      * @return String
506      */
getKeepSessionName(DeviceIPPortInfo deviceIPPortInfo, int sessionId)507     public String getKeepSessionName(DeviceIPPortInfo deviceIPPortInfo, int sessionId) {
508         if (ProfilerLogManager.isInfoEnabled()) {
509             LOGGER.info("getKeepSessionName");
510         }
511         if (Objects.nonNull(deviceIPPortInfo)) {
512             return "KEEP" + deviceIPPortInfo.getDeviceName() + sessionId;
513         } else {
514             return "";
515         }
516     }
517 
createSessionInfo(DeviceIPPortInfo device, ProcessInfo process, int sessionId)518     private SessionInfo createSessionInfo(DeviceIPPortInfo device, ProcessInfo process, int sessionId) {
519         if (ProfilerLogManager.isInfoEnabled()) {
520             LOGGER.info("createSessionInfo");
521         }
522         String deviceId = device.getDeviceID();
523         String sessionName = CommonUtil.generateSessionName(deviceId, process.getProcessId());
524         return SessionInfo.builder().sessionId(sessionId).sessionName(sessionName).pid(process.getProcessId())
525             .processName(process.getProcessName()).deviceIPPortInfo(device).processInfo(process).build();
526     }
527 
getLibPlugin( List<ProfilerServiceTypes.ProfilerPluginCapability> capabilities, String libDataPlugin)528     private Optional<ProfilerServiceTypes.ProfilerPluginCapability> getLibPlugin(
529         List<ProfilerServiceTypes.ProfilerPluginCapability> capabilities, String libDataPlugin) {
530         if (ProfilerLogManager.isInfoEnabled()) {
531             LOGGER.info("getLibPlugin");
532         }
533         Optional<ProfilerServiceTypes.ProfilerPluginCapability> ability = capabilities.stream()
534             .filter(profilerPluginCapability -> profilerPluginCapability.getName().contains(libDataPlugin)).findFirst();
535         if (ProfilerLogManager.isInfoEnabled()) {
536             LOGGER.info("plug : {}", ability);
537         }
538         return ability;
539     }
540 
541     /**
542      * Establish a session with the end side and start the session.
543      *
544      * @param localSessionId Local Session Id
545      * @param restartFlag Whether to start again
546      * @return boolean
547      */
startSession(Long localSessionId, boolean restartFlag)548     public boolean startSession(Long localSessionId, boolean restartFlag) {
549         if (ProfilerLogManager.isInfoEnabled()) {
550             LOGGER.info("startSession");
551         }
552         if (localSessionId == null) {
553             return false;
554         }
555         SessionInfo session = profilingSessions.get(localSessionId);
556         if (session == null || session.getSessionId() == Integer.MAX_VALUE) {
557             return true;
558         }
559         if (restartFlag) {
560             // Click start, delete the previous data first
561             CpuService.getInstance().deleteSessionData(localSessionId);
562             MemoryService.getInstance().deleteSessionData(localSessionId);
563             DiskIoService.getInstance().deleteSessionData(localSessionId);
564             UserDataService.getInstance().deleteSessionData(localSessionId);
565             deleteAllAgentData(localSessionId, false);
566         }
567         int sessionId = session.getSessionId();
568         if (ProfilerLogManager.isInfoEnabled()) {
569             LOGGER.info("startSession sessionId {}", sessionId);
570         }
571         DeviceIPPortInfo device = session.getDeviceIPPortInfo();
572         return HiProfilerClient.getInstance().requestStartSession(device.getIp(), device.getForwardPort(), sessionId);
573     }
574 
575     /**
576      * Turn on polling to get data
577      *
578      * @param localSessionId localSessionId
579      * @return boolean Turn on polling
580      */
fetchData(Long localSessionId)581     public boolean fetchData(Long localSessionId) {
582         if (ProfilerLogManager.isInfoEnabled()) {
583             LOGGER.info("handle fetchData");
584         }
585         if (localSessionId == null || localSessionId <= 0) {
586             return false;
587         }
588         // Set permissions on the process that gets CPU data
589         DeviceIPPortInfo deviceInfo = SessionManager.getInstance().getDeviceInfoBySessionId(localSessionId);
590         ArrayList<String> cmdStr;
591         if (IS_SUPPORT_NEW_HDC && deviceInfo.getDeviceType() == LEAN_HOS_DEVICE) {
592             cmdStr = conversionCommand(HDC_STD_CHMOD_PROC, deviceInfo.getDeviceID());
593             HdcWrapper.getInstance().execCmdBy(cmdStr, 10);
594         }
595         if ((!IS_SUPPORT_NEW_HDC) && deviceInfo.getDeviceType() == LEAN_HOS_DEVICE) {
596             cmdStr = conversionCommand(HDC_CHMOD_PROC, deviceInfo.getDeviceID());
597             HdcWrapper.getInstance().execCmdBy(cmdStr, 10);
598         }
599         try {
600             if (localSessionId <= 0) {
601                 return false;
602             }
603             SessionInfo session = profilingSessions.get(localSessionId);
604             if (Objects.isNull(session)) {
605                 return true;
606             }
607             DeviceIPPortInfo device = session.getDeviceIPPortInfo();
608             if (ProfilerLogManager.isInfoEnabled()) {
609                 LOGGER.info("start new DataPoller {}", DateTimeUtil.getNowTimeLong());
610             }
611             int sessionId = session.getSessionId();
612             DataPoller dataPoller = new DataPoller(localSessionId, sessionId, device);
613             if (sessionId != Integer.MAX_VALUE && sessionId > 0) {
614                 dataPoller.start();
615             }
616             dataPollerHashMap.put(localSessionId, dataPoller);
617             return true;
618         } catch (Exception exception) {
619             if (ProfilerLogManager.isErrorEnabled()) {
620                 LOGGER.error("fetchData exception", exception);
621             }
622             return false;
623         }
624     }
625 
626     /**
627      * isRefsh
628      *
629      * @param localSessionId localSessionId
630      * @return boolean
631      */
getSessionInfo(Long localSessionId)632     public SessionInfo getSessionInfo(Long localSessionId) {
633         if (ProfilerLogManager.isInfoEnabled()) {
634             LOGGER.info("getSessionInfo");
635         }
636         return profilingSessions.get(localSessionId);
637     }
638 
639     /**
640      * getDeviceInfoBySessionId
641      *
642      * @param localSessionId localSessionId
643      * @return DeviceIPPortInfo
644      */
getDeviceInfoBySessionId(long localSessionId)645     public DeviceIPPortInfo getDeviceInfoBySessionId(long localSessionId) {
646         if (ProfilerLogManager.isInfoEnabled()) {
647             LOGGER.info("getDeviceInfoBySessionId");
648         }
649         return profilingSessions.get(localSessionId).getDeviceIPPortInfo();
650     }
651 
652     /**
653      * View stop Loading
654      *
655      * @param localSession local Session
656      * @param firstTimeStamp first Time Stamp
657      */
stopLoadingView(Long localSession, long firstTimeStamp)658     public void stopLoadingView(Long localSession, long firstTimeStamp) {
659         if (ProfilerLogManager.isInfoEnabled()) {
660             LOGGER.info("stopLoadingView");
661         }
662         SessionInfo sessionInfo = profilingSessions.get(localSession);
663         if (sessionInfo != null) {
664             sessionInfo.setStartTimestamp(firstTimeStamp);
665             sessionInfo.setStartRefsh(true);
666             profilingSessions.put(localSession, sessionInfo);
667         }
668     }
669 
670     /**
671      * stop Session
672      *
673      * @param localSessionId localSessionId
674      * @return boolean Stop success indicator
675      */
endSession(Long localSessionId)676     public boolean endSession(Long localSessionId) {
677         if (ProfilerLogManager.isInfoEnabled()) {
678             LOGGER.info("endSession");
679         }
680         if (localSessionId == null || localSessionId <= 0) {
681             return false;
682         }
683         SessionInfo session = profilingSessions.get(localSessionId);
684         if (session == null) {
685             return true;
686         }
687         session.setStartRefsh(false);
688         int sessionId = session.getSessionId();
689         DeviceIPPortInfo device = session.getDeviceIPPortInfo();
690         LOGGER.info("endSession sessionId {}", sessionId);
691         boolean stopSessionRes =
692             HiProfilerClient.getInstance().requestStopSession(device.getIp(), device.getForwardPort(), sessionId, true);
693         if (stopSessionRes) {
694             DataPoller dataPoller = dataPollerHashMap.get(localSessionId);
695             if (dataPoller != null) {
696                 dataPoller.shutDown();
697             }
698             if (ProfilerLogManager.isInfoEnabled()) {
699                 LOGGER.info("Task with Session stopped successfully.");
700             }
701         } else {
702             if (ProfilerLogManager.isErrorEnabled()) {
703                 LOGGER.error("Failed to stop task with Session!");
704             }
705         }
706         return stopSessionRes;
707     }
708 
709     /**
710      * Delete the Session session interface
711      *
712      * @param localSessionId localSessionId
713      * @return boolean Is the deletion successful
714      */
deleteSession(Long localSessionId)715     public boolean deleteSession(Long localSessionId) {
716         if (ProfilerLogManager.isInfoEnabled()) {
717             LOGGER.info("deleteSession");
718         }
719         try {
720             if (localSessionId == null || localSessionId <= 0) {
721                 return false;
722             }
723             SessionInfo session = profilingSessions.get(localSessionId);
724             if (session == null) {
725                 return false;
726             }
727             if (session.getSessionId() == Integer.MAX_VALUE) {
728                 return true;
729             }
730             String keepSessionName = getKeepSessionName(session.getDeviceIPPortInfo(), session.getSessionId());
731             QuartzManager.getInstance().deleteExecutor(keepSessionName);
732             removeLocalSessionData(localSessionId);
733             if (session.isOfflineMode()) {
734                 return true;
735             }
736             int sessionId = session.getSessionId();
737             if (ProfilerLogManager.isInfoEnabled()) {
738                 LOGGER.info("deleteSession sessionId {}", sessionId);
739             }
740             DeviceIPPortInfo device = session.getDeviceIPPortInfo();
741             boolean stopSessionRes = HiProfilerClient.getInstance()
742                 .requestStopSession(device.getIp(), device.getForwardPort(), sessionId, true);
743             if (stopSessionRes) {
744                 boolean destroySessionRes = false;
745                 try {
746                     destroySessionRes = isDestroySessionRes(localSessionId, sessionId, device);
747                 } catch (StatusRuntimeException exception) {
748                     if (ProfilerLogManager.isErrorEnabled()) {
749                         LOGGER.error("exception ", exception);
750                     }
751                 }
752                 if (ProfilerLogManager.isInfoEnabled()) {
753                     LOGGER.info("Task with Session deleted successfully.");
754                 }
755                 return destroySessionRes;
756             } else {
757                 if (ProfilerLogManager.isErrorEnabled()) {
758                     LOGGER.error("Failed to delete task with Session ");
759                 }
760                 return false;
761             }
762         } finally {
763             doDeleteSessionData(localSessionId);
764         }
765     }
766 
isDestroySessionRes(Long localSessionId, int sessionId, DeviceIPPortInfo device)767     private boolean isDestroySessionRes(Long localSessionId, int sessionId, DeviceIPPortInfo device) {
768         boolean destroySessionRes =
769             HiProfilerClient.getInstance().requestDestroySession(device.getIp(), device.getForwardPort(), sessionId);
770         if (destroySessionRes) {
771             DataPoller dataPoller = dataPollerHashMap.get(localSessionId);
772             if (dataPoller != null) {
773                 dataPoller.shutDown();
774             }
775         }
776         return destroySessionRes;
777     }
778 
779     /**
780      * doDeleteSessionData
781      *
782      * @param localSessionId localSessionId
783      */
doDeleteSessionData(Long localSessionId)784     private void doDeleteSessionData(Long localSessionId) {
785         if (ProfilerLogManager.isInfoEnabled()) {
786             LOGGER.info("doDeleteSessionData");
787         }
788         if (localSessionId != null && localSessionId > 0) {
789             boolean traceFile = ProfilerChartsView.sessionMap.get(localSessionId).getPublisher().isTraceFile();
790             if (!traceFile) {
791                 CpuService.getInstance().deleteSessionData(localSessionId);
792                 MemoryService.getInstance().deleteSessionData(localSessionId);
793                 DiskIoService.getInstance().deleteSessionData(localSessionId);
794                 UserDataService.getInstance().deleteSessionData(localSessionId);
795                 deleteAllAgentData(localSessionId, true);
796             }
797         }
798     }
799 
deleteAllAgentData(Long localSessionId, boolean deleteClassInfo)800     private void deleteAllAgentData(Long localSessionId, boolean deleteClassInfo) {
801         if (ProfilerLogManager.isInfoEnabled()) {
802             LOGGER.info("deleteAllAgentData");
803         }
804         if (memoTable == null) {
805             memoTable = new MemoryTable();
806         }
807         if (memoryHeapDao == null) {
808             memoryHeapDao = new MemoryHeapDao();
809         }
810         if (memoryInstanceDao == null) {
811             memoryInstanceDao = new MemoryInstanceDao();
812         }
813         if (classInfoDao == null) {
814             classInfoDao = new ClassInfoDao();
815         }
816         if (memoryInstanceDetailsDao == null) {
817             memoryInstanceDetailsDao = new MemoryInstanceDetailsDao();
818         }
819         if (deleteClassInfo) {
820             classInfoDao.deleteSessionData(localSessionId);
821         }
822         memoryHeapDao.deleteSessionData(localSessionId);
823         memoryInstanceDao.deleteSessionData(localSessionId);
824         memoryInstanceDetailsDao.deleteSessionData(localSessionId);
825     }
826 
827     /**
828      * Used to notify the end side to close all session connections after the IDE is closed.
829      */
stopAllSession()830     public void stopAllSession() {
831         if (ProfilerLogManager.isInfoEnabled()) {
832             LOGGER.info("stopAllSession");
833         }
834         if (profilingSessions.isEmpty()) {
835             return;
836         }
837         profilingSessions.values().forEach(sessionInfo -> {
838             String keepSessionName = getKeepSessionName(sessionInfo.getDeviceIPPortInfo(), sessionInfo.getSessionId());
839             QuartzManager.getInstance().deleteExecutor(keepSessionName);
840             DeviceIPPortInfo device = sessionInfo.getDeviceIPPortInfo();
841             if (device != null) {
842                 HiProfilerClient hiProfiler = HiProfilerClient.getInstance();
843                 hiProfiler
844                     .requestStopSession(device.getIp(), device.getForwardPort(), sessionInfo.getSessionId(), true);
845                 hiProfiler.requestDestroySession(device.getIp(), device.getForwardPort(), sessionInfo.getSessionId());
846             }
847         });
848     }
849 
850     /**
851      * Save the collected data to a file.
852      *
853      * @param sessionId sessionId
854      * @param deviceProcessInfo deviceProcessInfo
855      * @param pathname pathname
856      * @return boolean
857      */
saveSessionDataToFile(long sessionId, DeviceProcessInfo deviceProcessInfo, String pathname)858     public boolean saveSessionDataToFile(long sessionId, DeviceProcessInfo deviceProcessInfo, String pathname) {
859         if (ProfilerLogManager.isInfoEnabled()) {
860             LOGGER.info("saveSessionDataToFile");
861         }
862         if (sessionId <= 0 || deviceProcessInfo == null || StringUtils.isEmpty(pathname)) {
863             return false;
864         }
865         List<ProcessMemInfo> memInfoList = MemoryService.getInstance().getAllData(sessionId);
866         List<ClassInfo> classInfos = new ClassInfoManager().getAllClassInfoData(sessionId);
867         List<MemoryHeapInfo> memoryHeapInfos = new MemoryHeapManager().getAllMemoryHeapInfos(sessionId);
868         List<MemoryInstanceDetailsInfo> detailsInfos = new MemoryInstanceDetailsManager().getAllMemoryInstanceDetails();
869         ArrayList<MemoryUpdateInfo> memoryInstanceInfos = new MemoryInstanceManager().getAllMemoryInstanceInfos();
870         List<DiskIOData> sysDiskIoInfoList = DiskIoService.getInstance().getAllData(sessionId);
871         List<ProcessCpuData> cpuInfoList = CpuDao.getInstance().getAllData(sessionId);
872         List<EnergyLocationInfo> energyList = new LinkedList<>();
873         FileOutputStream fileOutputStream = null;
874         ObjectOutputStream objectOutputStream = null;
875         try {
876             File file = new File(pathname);
877             fileOutputStream = new FileOutputStream(file);
878             objectOutputStream = new ObjectOutputStream(fileOutputStream);
879             TraceFileInfo startObj = new TraceFileInfo();
880             int recordNum = memInfoList.size() + classInfos.size() + memoryHeapInfos.size() + detailsInfos.size()
881                 + memoryInstanceInfos.size() + sysDiskIoInfoList.size() + cpuInfoList.size();
882             startObj.setRecordNum(recordNum);
883             startObj.setCreateTime(new Date().getTime());
884             startObj.setVersion("V1.0");
885             objectOutputStream.writeObject(startObj);
886             for (int index = 0; index < memInfoList.size(); index++) {
887                 setDeviceProcessInfo(deviceProcessInfo, memInfoList, objectOutputStream, index);
888             }
889             handleStreamToDataBean(sysDiskIoInfoList, cpuInfoList, energyList, objectOutputStream);
890             writeCollectionData(objectOutputStream, classInfos, memoryHeapInfos, detailsInfos, memoryInstanceInfos);
891             objectOutputStream.writeObject(deviceProcessInfo);
892             if (ProfilerLogManager.isInfoEnabled()) {
893                 LOGGER.info("Task with Session ID {} Save To File successfully.");
894             }
895         } catch (IOException exception) {
896             if (ProfilerLogManager.isErrorEnabled()) {
897                 LOGGER.error(exception.getMessage());
898             }
899             return false;
900         } finally {
901             closeIoStream(null, null, fileOutputStream, objectOutputStream);
902         }
903         return true;
904     }
905 
handleStreamToDataBean(List<DiskIOData> sysDiskIoInfoList, List<ProcessCpuData> cpuInfoList, List<EnergyLocationInfo> energyList, ObjectOutputStream objectOutputStream)906     private void handleStreamToDataBean(List<DiskIOData> sysDiskIoInfoList,
907         List<ProcessCpuData> cpuInfoList, List<EnergyLocationInfo> energyList, ObjectOutputStream objectOutputStream)
908         throws IOException {
909         for (DiskIOData sysDiskIoInfo : sysDiskIoInfoList) {
910             objectOutputStream.writeObject(sysDiskIoInfo);
911         }
912         for (ProcessCpuData processCpuData : cpuInfoList) {
913             objectOutputStream.writeObject(processCpuData);
914         }
915         for (EnergyLocationInfo energyLocationInfo : energyList) {
916             objectOutputStream.writeObject(energyLocationInfo);
917         }
918     }
919 
920     /**
921      * setDeviceProcessInfo
922      *
923      * @param deviceProcessInfo deviceProcessInfo
924      * @param memInfoList memInfoList
925      * @param objectOutputStream objectOutputStream
926      * @param index index
927      * @throws IOException IOException
928      */
setDeviceProcessInfo(DeviceProcessInfo deviceProcessInfo, List<ProcessMemInfo> memInfoList, ObjectOutputStream objectOutputStream, int index)929     private void setDeviceProcessInfo(DeviceProcessInfo deviceProcessInfo, List<ProcessMemInfo> memInfoList,
930         ObjectOutputStream objectOutputStream, int index) throws IOException {
931         if (ProfilerLogManager.isInfoEnabled()) {
932             LOGGER.info("setDeviceProcessInfo");
933         }
934         ProcessMemInfo memObject = memInfoList.get(index);
935         objectOutputStream.writeObject(memObject);
936         if (index == 0) {
937             deviceProcessInfo.setStartTime(memObject.getTimeStamp());
938         }
939         if (index == (memInfoList.size() - 1)) {
940             deviceProcessInfo.setEndTime(memObject.getTimeStamp());
941         }
942     }
943 
writeCollectionData(ObjectOutputStream objectOutputStream, List<ClassInfo> classInfos, List<MemoryHeapInfo> memoryHeapInfos, List<MemoryInstanceDetailsInfo> detailsInfos, ArrayList<MemoryUpdateInfo> memoryInstanceInfos)944     private void writeCollectionData(ObjectOutputStream objectOutputStream, List<ClassInfo> classInfos,
945         List<MemoryHeapInfo> memoryHeapInfos, List<MemoryInstanceDetailsInfo> detailsInfos,
946         ArrayList<MemoryUpdateInfo> memoryInstanceInfos) throws IOException {
947         if (ProfilerLogManager.isInfoEnabled()) {
948             LOGGER.info("writeCollectionData");
949         }
950         for (ClassInfo classInfo : classInfos) {
951             objectOutputStream.writeObject(classInfo);
952         }
953         for (MemoryHeapInfo memoryHeapInfo : memoryHeapInfos) {
954             objectOutputStream.writeObject(memoryHeapInfo);
955         }
956         for (MemoryInstanceDetailsInfo instanceDetailsInfo : detailsInfos) {
957             objectOutputStream.writeObject(instanceDetailsInfo);
958         }
959 
960         for (int index = 0; index < memoryInstanceInfos.size(); index++) {
961             MemoryUpdateInfo instanceInfo = memoryInstanceInfos.get(index);
962             objectOutputStream.writeObject(instanceInfo);
963         }
964     }
965 
966     /**
967      * local Session Data From File
968      *
969      * @param jProgressBar jProgressBar
970      * @param file file
971      * @return Optional<DeviceProcessInfo>
972      */
localSessionDataFromFile(JProgressBar jProgressBar, File file)973     public Optional<DeviceProcessInfo> localSessionDataFromFile(JProgressBar jProgressBar, File file) {
974         if (ProfilerLogManager.isInfoEnabled()) {
975             LOGGER.info("localSessionDataFromFile");
976         }
977         if (jProgressBar == null || file == null) {
978             return Optional.ofNullable(null);
979         }
980         FileInputStream fileInputStream = null;
981         ObjectInputStream objectInputStream = null;
982         DeviceProcessInfo deviceProcessInfo = null;
983         try {
984             fileInputStream = new FileInputStream(file);
985             objectInputStream = new ObjectInputStream(fileInputStream);
986             Object firstObj = objectInputStream.readObject();
987             TraceFileInfo traceFileInfo = null;
988             if (firstObj instanceof TraceFileInfo) {
989                 traceFileInfo = (TraceFileInfo) firstObj;
990                 if (!"V1.0".equals(traceFileInfo.getVersion())) {
991                     // The trace file is not the latest version
992                     return Optional.empty();
993                 }
994             } else {
995                 // The trace file is not the latest version
996                 return Optional.empty();
997             }
998             deviceProcessInfo = loadFileInDataBase(jProgressBar, traceFileInfo, objectInputStream);
999         } catch (IOException | ClassNotFoundException exception) {
1000             if (exception.getMessage().indexOf("invalid stream header") >= 0) {
1001                 if (file.getName().indexOf(".bin") >= 0) {
1002                     return Optional.empty();
1003                 }
1004                 return Optional.empty();
1005             }
1006             if (ProfilerLogManager.isErrorEnabled()) {
1007                 LOGGER.error("load Data Error {}", exception.getMessage());
1008             }
1009             return Optional.empty();
1010         } finally {
1011             closeIoStream(fileInputStream, objectInputStream, null, null);
1012         }
1013         long localSessionId = deviceProcessInfo.getLocalSessionId();
1014         SessionInfo session = SessionInfo.builder().sessionName(String.valueOf(localSessionId)).build();
1015         session.setOfflineMode(true);
1016         profilingSessions.put(localSessionId, session);
1017         jProgressBar.setValue(LayoutConstants.HUNDRED);
1018         return Optional.of(deviceProcessInfo);
1019     }
1020 
loadFileInDataBase(JProgressBar jProgressBar, TraceFileInfo traceFileInfo, ObjectInputStream objectInputStream)1021     private DeviceProcessInfo loadFileInDataBase(JProgressBar jProgressBar, TraceFileInfo traceFileInfo,
1022         ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
1023         if (ProfilerLogManager.isInfoEnabled()) {
1024             LOGGER.info("loadFileInDataBase");
1025         }
1026         long objNum = traceFileInfo.getRecordNum() + 1;
1027         long currentNum = 0L;
1028         intDbDao();
1029         Validate[] validates = {new CpuValidate(), new MemoryValidate(), new DiskIoValidate()};
1030         while (true) {
1031             Object object = objectInputStream.readObject();
1032             for (Validate item : validates) {
1033                 if (item.validate(object)) {
1034                     currentNum = currentNum + 1;
1035                     loadPercentage(jProgressBar, objNum, currentNum);
1036                     item.addToList(object);
1037                     break;
1038                 }
1039             }
1040             if (object instanceof DeviceProcessInfo) {
1041                 // Finally, if there is still data in the datalist, import the database
1042                 int processMemInfoNum = 0;
1043                 for (Validate item : validates) {
1044                     if (item instanceof MemoryValidate) {
1045                         processMemInfoNum = ((MemoryValidate) item).getMenInfoSize();
1046                     }
1047                     item.batchInsertToDb();
1048                 }
1049                 currentNum = currentNum + processMemInfoNum;
1050                 int progress = (int) (currentNum * LayoutConstants.HUNDRED / objNum);
1051                 jProgressBar.setValue(progress);
1052                 return (DeviceProcessInfo) object;
1053             } else {
1054                 continue;
1055             }
1056         }
1057     }
1058 
intDbDao()1059     private void intDbDao() {
1060         if (ProfilerLogManager.isInfoEnabled()) {
1061             LOGGER.info("intDbDao");
1062         }
1063     }
1064 
loadPercentage(JProgressBar jProgressBar, long objNum, long currentNum)1065     private void loadPercentage(JProgressBar jProgressBar, long objNum, long currentNum) {
1066         if (ProfilerLogManager.isInfoEnabled()) {
1067             LOGGER.info("loadPercentage");
1068         }
1069         int progress = (int) (currentNum * LayoutConstants.HUNDRED / objNum);
1070         double result = progress % 25;
1071         if (result == 0) {
1072             jProgressBar.setValue(progress);
1073         }
1074     }
1075 
closeIoStream(FileInputStream fileInputStream, ObjectInputStream objectInputStream, FileOutputStream fileOutputStream, ObjectOutputStream objectOutputStream)1076     private void closeIoStream(FileInputStream fileInputStream, ObjectInputStream objectInputStream,
1077         FileOutputStream fileOutputStream, ObjectOutputStream objectOutputStream) {
1078         if (ProfilerLogManager.isInfoEnabled()) {
1079             LOGGER.info("closeIoStream");
1080         }
1081         if (fileInputStream != null) {
1082             try {
1083                 fileInputStream.close();
1084             } catch (IOException exception) {
1085                 if (ProfilerLogManager.isErrorEnabled()) {
1086                     LOGGER.error("exception:{}", exception.getMessage());
1087                 }
1088             }
1089         }
1090         if (objectInputStream != null) {
1091             try {
1092                 objectInputStream.close();
1093             } catch (IOException exception) {
1094                 if (ProfilerLogManager.isErrorEnabled()) {
1095                     LOGGER.error("exception:{}", exception.getMessage());
1096                 }
1097             }
1098         }
1099         if (fileOutputStream != null) {
1100             try {
1101                 fileOutputStream.close();
1102             } catch (IOException exception) {
1103                 if (ProfilerLogManager.isErrorEnabled()) {
1104                     LOGGER.error("exception:{}", exception.getMessage());
1105                 }
1106             }
1107         }
1108         if (objectOutputStream != null) {
1109             try {
1110                 objectOutputStream.close();
1111             } catch (IOException exception) {
1112                 if (ProfilerLogManager.isErrorEnabled()) {
1113                     LOGGER.error("exception:{}", exception.getMessage());
1114                 }
1115             }
1116         }
1117     }
1118 
1119     /**
1120      * delete Session By OffLine Device
1121      *
1122      * @param device device
1123      */
deleteSessionByOffLineDevice(DeviceIPPortInfo device)1124     public void deleteSessionByOffLineDevice(DeviceIPPortInfo device) {
1125         if (ProfilerLogManager.isInfoEnabled()) {
1126             LOGGER.info("deleteSessionByOffLineDevice");
1127         }
1128         if (profilingSessions.isEmpty() || device == null) {
1129             return;
1130         }
1131         Set<Long> sessionIds = profilingSessions.keySet();
1132         for (Long session : sessionIds) {
1133             SessionInfo sessionInfo = profilingSessions.get(session);
1134             if (sessionInfo != null) {
1135                 DeviceIPPortInfo deviceSource = sessionInfo.getDeviceIPPortInfo();
1136                 if (device.getDeviceID().equals(deviceSource.getDeviceID())) {
1137                     String keepSessionName =
1138                         getKeepSessionName(sessionInfo.getDeviceIPPortInfo(), sessionInfo.getSessionId());
1139                     QuartzManager.getInstance().deleteExecutor(keepSessionName);
1140                     // 停止chart刷新
1141                     ProfilerChartsView.sessionMap.get(session).getPublisher().stopRefresh(true);
1142                     DataPoller dataPoller = dataPollerHashMap.get(session);
1143                     if (Objects.nonNull(dataPoller)) {
1144                         dataPoller.shutDown();
1145                     }
1146                     removeLocalSessionData(session);
1147                 }
1148             }
1149         }
1150     }
1151 
1152     /**
1153      * get Plugin Path
1154      *
1155      * @return String plugin Path
1156      */
getPluginPath()1157     public String getPluginPath() {
1158         if (ProfilerLogManager.isInfoEnabled()) {
1159             LOGGER.info("getPluginPath");
1160         }
1161         String pluginPath = "";
1162         PluginId plugin = PluginManager.getPluginByClassName(this.getClass().getName());
1163         if (plugin != null) {
1164             File path = PluginManager.getPlugin(plugin).getPath();
1165             try {
1166                 pluginPath = path.getCanonicalPath() + File.separator + "ohos" + File.separator;
1167             } catch (IOException ioException) {
1168                 if (ProfilerLogManager.isErrorEnabled()) {
1169                     LOGGER.error("exception:{}", ioException.getMessage());
1170                 }
1171             }
1172         } else {
1173             String sourcePath = SessionManager.class.getResource("").getPath();
1174             int indexOf = sourcePath.indexOf("/build");
1175             String substring = sourcePath.substring(1, indexOf);
1176             pluginPath = substring + "\\src\\main\\resources\\ohosresource\\";
1177         }
1178         return pluginPath;
1179     }
1180 
1181     /**
1182      * get temp Path
1183      *
1184      * @return String temp Path
1185      */
tempPath()1186     public String tempPath() {
1187         return PathManager.getTempPath() + File.separator + "ohos" + File.separator;
1188     }
1189 
1190     /**
1191      * getHdcPath
1192      *
1193      * @return String
1194      */
getHdcPath()1195     public String getHdcPath() {
1196         String value = "";
1197         PropertiesComponent instance = null;
1198         Application application = ApplicationManager.getApplication();
1199         if (Objects.nonNull(application)) {
1200             instance = application.getService(PropertiesComponent.class);
1201         }
1202         if (Objects.nonNull(instance)) {
1203             value = instance.getValue("huawei.sdk.location");
1204         }
1205         if (StringUtils.isBlank(value)) {
1206             if (ProfilerLogManager.isInfoEnabled()) {
1207                 LOGGER.info("sdk path is null");
1208             }
1209             return "hdc";
1210         } else {
1211             return value + File.separator + "toolchains" + File.separator + "hdc";
1212         }
1213     }
1214 
1215     /**
1216      * getHdcStdPath
1217      *
1218      * @return String
1219      */
getHdcStdPath()1220     public String getHdcStdPath() {
1221         String value = "";
1222         PropertiesComponent instance = null;
1223         Application application = ApplicationManager.getApplication();
1224         if (Objects.nonNull(application)) {
1225             instance = application.getService(PropertiesComponent.class);
1226         }
1227         if (Objects.nonNull(instance)) {
1228             value = instance.getValue("oh.sdk.location");
1229         }
1230         if (StringUtils.isBlank(value)) {
1231             if (ProfilerLogManager.isInfoEnabled()) {
1232                 LOGGER.info("sdk path is null");
1233             }
1234             return "hdc_std";
1235         } else {
1236             return value + File.separator + "toolchains" + File.separator + "hdc_std";
1237         }
1238     }
1239 
1240     /**
1241      * get pid
1242      *
1243      * @param localSessionId localSessionId
1244      * @return long
1245      */
getPid(Long localSessionId)1246     public long getPid(Long localSessionId) {
1247         return profilingSessions.get(localSessionId).getPid();
1248     }
1249 
1250     /**
1251      * get ProcessName
1252      *
1253      * @param localSessionId localSessionId
1254      * @return long
1255      */
getProcessName(Long localSessionId)1256     public String getProcessName(Long localSessionId) {
1257         SessionInfo sessionInfo = profilingSessions.get(localSessionId);
1258         if (sessionInfo != null) {
1259             return sessionInfo.getProcessName();
1260         }
1261         return "";
1262     }
1263 
1264     /**
1265      * export File
1266      *
1267      * @param exportFileName exportFileName
1268      * @param fileChooserDialog fileChooserDialog
1269      * @return boolean
1270      */
exportDumpOrHookFile(String exportFileName, ExportFileChooserDialog fileChooserDialog)1271     public boolean exportDumpOrHookFile(String exportFileName, ExportFileChooserDialog fileChooserDialog) {
1272         if (ProfilerLogManager.isInfoEnabled()) {
1273             LOGGER.info("exportDumpOrHookFile");
1274         }
1275         // not get from device
1276         int line;
1277         boolean result = true;
1278         FileOutputStream fileOut = null;
1279         BufferedOutputStream dataOut = null;
1280         File file = new File(SessionManager.getInstance().tempPath() + File.separator + exportFileName);
1281         try {
1282             // Excuting an order
1283             fileOut = new FileOutputStream(
1284                 fileChooserDialog.getExportFilePath() + File.separator + fileChooserDialog.getExportFileName() + "."
1285                     + fileChooserDialog.getFileType());
1286             dataOut = new BufferedOutputStream(fileOut);
1287             try (InputStream inputStream = new FileInputStream(file);
1288                 BufferedInputStream brInputStream = new BufferedInputStream(inputStream);) {
1289                 while ((line = brInputStream.read()) != -1) {
1290                     dataOut.write(line);
1291                 }
1292             } catch (IOException exception) {
1293                 if (ProfilerLogManager.isErrorEnabled()) {
1294                     LOGGER.error("exception {}", exception.getMessage());
1295                 }
1296                 result = false;
1297             }
1298         } catch (IOException exception) {
1299             if (ProfilerLogManager.isErrorEnabled()) {
1300                 LOGGER.error("exception {}", exception.getMessage());
1301             }
1302             result = false;
1303         } finally {
1304             try {
1305                 dataOut.flush();
1306                 if (dataOut != null) {
1307                     dataOut.close();
1308                 }
1309                 if (fileOut != null) {
1310                     fileOut.close();
1311                 }
1312             } catch (IOException exception) {
1313                 if (ProfilerLogManager.isErrorEnabled()) {
1314                     LOGGER.error("exception {}", exception.getMessage());
1315                 }
1316                 result = false;
1317             }
1318         }
1319         return result;
1320     }
1321 
1322     /**
1323      * getDeviceType By sessionId
1324      *
1325      * @param sessionId sessionId
1326      * @return DeviceType
1327      */
getDeviceType(long sessionId)1328     public DeviceType getDeviceType(long sessionId) {
1329         if (ProfilerLogManager.isInfoEnabled()) {
1330             LOGGER.info("getDeviceType");
1331         }
1332         SessionInfo sessionInfo = profilingSessions.get(sessionId);
1333         if (sessionInfo == null || sessionInfo.getDeviceIPPortInfo() == null) {
1334             return LEAN_HOS_DEVICE;
1335         }
1336         return sessionInfo.getDeviceIPPortInfo().getDeviceType();
1337     }
1338 
1339     /**
1340      * Setting Permissions
1341      */
settingPermissions()1342     public void settingPermissions() {
1343         if (ProfilerLogManager.isInfoEnabled()) {
1344             LOGGER.info("settingPermissions");
1345         }
1346         if (System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("mac")) {
1347             String pluginPath = getPluginPath();
1348             HdcWrapper.getInstance().execCmdBy(conversionCommand(CHMOD_TO_OHOS, pluginPath));
1349         }
1350     }
1351 
getProfilingSessions()1352     public HashMap<Long, SessionInfo> getProfilingSessions() {
1353         return profilingSessions;
1354     }
1355 
setProfilingSessions(HashMap<Long, SessionInfo> profilingSessions)1356     public void setProfilingSessions(HashMap<Long, SessionInfo> profilingSessions) {
1357         this.profilingSessions = profilingSessions;
1358     }
1359 }
1360