morningman commented on a change in pull request #497: Support io and cpu 
indicates for current query
URL: https://github.com/apache/incubator-doris/pull/497#discussion_r244980937
 
 

 ##########
 File path: 
fe/src/main/java/org/apache/doris/common/proc/CurrentQueryInfoProvider.java
 ##########
 @@ -0,0 +1,518 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.common.proc;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import org.apache.doris.catalog.Catalog;
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.common.Pair;
+import org.apache.doris.common.util.Counter;
+import org.apache.doris.common.util.DebugUtil;
+import org.apache.doris.common.util.RuntimeProfile;
+import org.apache.doris.qe.QueryStatisticsItem;
+import org.apache.doris.rpc.*;
+import org.apache.doris.system.Backend;
+import org.apache.doris.thrift.TNetworkAddress;
+import org.apache.doris.thrift.TStatusCode;
+import org.apache.doris.thrift.TUniqueId;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * Provide running query's PlanNode informations, includeing execution State
+ * , IO consumption and CPU consumption.
+ */
+public class CurrentQueryInfoProvider {
+    private static final Logger LOG = 
LogManager.getLogger(CurrentQueryInfoProvider.class);
+
+    public CurrentQueryInfoProvider() {
+    }
+
+    /**
+     * Firstly send request to trigger report profile for specified query and 
wait a while,
+     * Secondly get Counters from Coordinator's RuntimeProfile and return 
query's consumption.
+     *
+     * @param item
+     * @return
+     * @throws AnalysisException
+     */
+    public Consumption getQueryConsumption(QueryStatisticsItem item) throws 
AnalysisException {
+        triggerReportAndWait(item, getWaitTime(1), false);
+        return new Consumption(item.getQueryProfile());
+    }
+
+    /**
+     * Same as getQueryConsumption, but this will cause BE to report all 
queries profile.
+     *
+     * @param items
+     * @return
+     * @throws AnalysisException
+     */
+    public Map<String, Consumption> 
getQueriesConsumptions(Collection<QueryStatisticsItem> items)
+            throws AnalysisException {
+        triggerReportAndWait(items, getWaitTime(items.size()), true);
+        final Map<String, Consumption> queryConsumpations = Maps.newHashMap();
+        for (QueryStatisticsItem item : items) {
+            queryConsumpations.put(item.getQueryId(), new 
Consumption(item.getQueryProfile()));
+        }
+        return queryConsumpations;
+    }
+
+    /**
+     * Return query's instances consumption.
+     *
+     * @param item
+     * @return
+     * @throws AnalysisException
+     */
+    public Collection<InstanceConsumption> 
getQueryInstancesConsumptions(QueryStatisticsItem item) throws 
AnalysisException {
+        triggerReportAndWait(item, getWaitTime(1), false);
+        final Map<String, RuntimeProfile> instanceProfiles = 
collectInstanceProfile(item.getQueryProfile());
+        final List<InstanceConsumption> instanceConsumptions = 
Lists.newArrayList();
+        for (QueryStatisticsItem.FragmentInstanceInfo instanceInfo : 
item.getFragmentInstanceInfos()) {
+            final RuntimeProfile instanceProfile = 
instanceProfiles.get(DebugUtil.printId(instanceInfo.getInstanceId()));
+            Preconditions.checkNotNull(instanceProfile);
+            final InstanceConsumption consumption =
+                    new InstanceConsumption(
+                            instanceInfo.getFragmentId(),
+                            instanceInfo.getInstanceId(),
+                            instanceInfo.getAddress(),
+                            instanceProfile);
+            instanceConsumptions.add(consumption);
+        }
+        return instanceConsumptions;
+    }
+
+    /**
+     * Profile trees is query profile -> fragment profile -> instance profile 
....
+     * @param queryProfile
+     * @return instanceProfiles
+     */
+    private Map<String, RuntimeProfile> collectInstanceProfile(RuntimeProfile 
queryProfile) {
+        final Map<String, RuntimeProfile> instanceProfiles = Maps.newHashMap();
+        for (RuntimeProfile fragmentProfile : 
queryProfile.getChildMap().values()) {
+            for (Map.Entry<String, RuntimeProfile> entry: 
fragmentProfile.getChildMap().entrySet()) {
+                
Preconditions.checkState(instanceProfiles.put(parseInstanceId(entry.getKey()), 
entry.getValue()) == null);
+            }
+        }
+        return instanceProfiles;
+    }
+
+    /**
+     * Instance profile key is "Instance ${instance_id} (host=$host $port)"
+     * @param str
+     * @return
+     */
+    private String parseInstanceId(String str) {
+        final String[] elements = str.split(" ");
+        if (elements.length == 4) {
+            return  elements[1];
+        } else {
+            Preconditions.checkState(false);
+            return "";
+        }
+    }
+
+    private long getWaitTime(int numOfQuery) {
+        final int oneQueryWaitTime = 200;
+        final int allQueryMaxWaitTime = 2000;
+        final int waitTime = numOfQuery * oneQueryWaitTime;
+        return waitTime > allQueryMaxWaitTime ? allQueryMaxWaitTime : waitTime;
+    }
+
+    private void triggerReportAndWait(QueryStatisticsItem item, long waitTime, 
boolean allQuery)
+            throws AnalysisException {
+        final List<QueryStatisticsItem> items = Lists.newArrayList(item);
+        triggerReportAndWait(items, waitTime, allQuery);
+    }
+
+    private void triggerReportAndWait(Collection<QueryStatisticsItem> items, 
long waitTime, boolean allQuery)
+            throws AnalysisException {
+        triggerReportProfile(items, allQuery);
+        try {
+            Thread.currentThread().sleep(waitTime);
+        } catch (InterruptedException e) {
+        }
+    }
+
+    /**
+     * send report profile request.
+     * @param items
+     * @param allQuery true:all queries profile will be reported, 
false:specified queries profile will be reported.
+     * @throws AnalysisException
+     */
+    private void triggerReportProfile(Collection<QueryStatisticsItem> items, 
boolean allQuery) throws AnalysisException {
+        final Map<TNetworkAddress, Request> requestMap = Maps.newHashMap();
+        final Map<TNetworkAddress, TNetworkAddress> brpcAddressMap = 
Maps.newHashMap();
+        for (QueryStatisticsItem item : items) {
+            for (QueryStatisticsItem.FragmentInstanceInfo instanceInfo : 
item.getFragmentInstanceInfos()) {
+                // use brpc address
+                TNetworkAddress brpcNetAddress = 
brpcAddressMap.get(instanceInfo.getAddress());
+                if (brpcNetAddress == null) {
+                    try {
+                        brpcNetAddress = toBrpcHost(instanceInfo.getAddress());
+                        brpcAddressMap.put(instanceInfo.getAddress(), 
brpcNetAddress);
+                    } catch (Exception e) {
+                        LOG.warn(e.getMessage());
+                        throw new AnalysisException(e.getMessage());
+                    }
+                }
+                // merge different requests
+                Request request = requestMap.get(brpcNetAddress);
+                if (request == null) {
+                    request = new Request(brpcNetAddress);
+                    requestMap.put(brpcNetAddress, request);
+                }
+                // specified query instance which will report.
+                if (!allQuery) {
+                    final PUniqueId pUId = new 
PUniqueId(instanceInfo.getInstanceId());
+                    request.addInstanceId(pUId);
+                }
+            }
+        }
+        recvResponse(sendRequest(requestMap));
+    }
+
+    private List<Pair<Request, Future<PTiggerReportProfileResult>>> 
sendRequest(
+            Map<TNetworkAddress, Request> requestMap) throws AnalysisException 
{
+        final List<Pair<Request, Future<PTiggerReportProfileResult>>> futures 
= Lists.newArrayList();
+        for (TNetworkAddress address : requestMap.keySet()) {
+            final Request request = requestMap.get(address);
+            final PTiggerReportProfileRequest pbRequest =
+                    new PTiggerReportProfileRequest(request.getInstanceIds());
+            try {
+                futures.add(Pair.create(request, 
BackendServiceProxy.getInstance().
+                        triggerReportProfileAsync(address, pbRequest)));
+            } catch (RpcException e) {
+                throw new AnalysisException("Sending request fails for query's 
execution informations.");
+            }
+        }
+        return futures;
+    }
+
+    private void recvResponse(List<Pair<Request, 
Future<PTiggerReportProfileResult>>> futures)
+            throws AnalysisException {
+        final String reasonPrefix = "Fail to receive result.";
+        for (Pair<Request, Future<PTiggerReportProfileResult>> pair : futures) 
{
+            try {
+                final PTiggerReportProfileResult result
+                        = pair.second.get(10, TimeUnit.SECONDS);
 
 Review comment:
   You wait here for at most 10 seconds. But getWaitTime() is at most 2 
seconds? What's that mean?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to