tanishq-chugh commented on code in PR #5451:
URL: https://github.com/apache/hive/pull/5451#discussion_r1766359794


##########
service/src/java/org/apache/hive/service/servlet/OTELExporter.java:
##########
@@ -0,0 +1,225 @@
+/*
+ * 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.hive.service.servlet;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+import com.google.common.base.Joiner;
+import io.opentelemetry.api.OpenTelemetry;
+import io.opentelemetry.api.common.AttributeKey;
+import io.opentelemetry.api.trace.Span;
+import io.opentelemetry.api.trace.Tracer;
+import io.opentelemetry.context.Context;
+import io.opentelemetry.sdk.internal.AttributesMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.hadoop.hive.ql.QueryDisplay;
+import org.apache.hadoop.hive.ql.QueryInfo;
+import org.apache.hive.service.cli.operation.OperationManager;
+import org.apache.hive.service.cli.session.SessionManager;
+
+public class OTELExporter extends Thread {
+  private static final String INSTRUMENTATION_NAME = 
OTELExporter.class.getName();
+  private static final Logger LOG = 
LoggerFactory.getLogger(OTELExporter.class);
+  private final OperationManager operationManager;
+  private Set<String> historicalQueryId;
+  private final long frequency;
+  private final Tracer tracer;
+  private Map<String, Span> queryIdToSpanMap;
+  private Map<String, List<String>> queryIdToTasksMap;
+
+  public OTELExporter(OpenTelemetry openTelemetry, SessionManager 
sessionManager, long frequency) {
+    this.tracer = openTelemetry.getTracer(INSTRUMENTATION_NAME);
+    this.operationManager = sessionManager.getOperationManager();
+    this.historicalQueryId = new HashSet<>();
+    this.frequency = frequency;
+    this.queryIdToSpanMap = new HashMap<>();
+    this.queryIdToTasksMap = new HashMap<>();
+  }
+
+  @Override
+  public void run() {
+    while (true) {
+      exposeMetricsToOTEL();
+      try {
+        Thread.sleep(frequency);
+      } catch (InterruptedException e) {
+        throw new RuntimeException(e);
+      }
+    }
+  }
+
+  public void exposeMetricsToOTEL() {
+    List<QueryInfo> liveQueries = operationManager.getLiveQueryInfos();
+    List<QueryInfo> historicalQueries = 
operationManager.getHistoricalQueryInfos();
+
+    LOG.debug("Found {} liveQueries and {} historicalQueries", 
liveQueries.size(), historicalQueries.size());
+
+    for (QueryInfo lQuery: liveQueries){
+      if(lQuery.getQueryDisplay() == null){
+        continue;
+      }
+      String queryID = lQuery.getQueryDisplay().getQueryId();
+      Span rootspan = queryIdToSpanMap.get(queryID);
+
+      //In case of live query previously encountered in past loops
+      if (rootspan != null) {
+        for (QueryDisplay.TaskDisplay task : 
lQuery.getQueryDisplay().getTaskDisplays()) {
+          if (task.getReturnValue() != null && task.getEndTime() != null && 
!queryIdToTasksMap.get(queryID).contains(task.getTaskId())) {
+            queryIdToTasksMap.get(queryID).add(task.getTaskId());
+            Context parentContext = Context.current().with(rootspan);
+            tracer.spanBuilder(queryID+ " - " + task.getTaskId() + " - live")
+                    
.setParent(parentContext).setAllAttributes(addTaskAttributes(task))
+                    .setStartTimestamp(task.getBeginTime(), 
TimeUnit.MILLISECONDS).startSpan()
+                    .end(task.getEndTime(), TimeUnit.MILLISECONDS);
+          }
+        }
+      } else {
+        // In case of live queries being seen for first time and has 
initialized its queryDisplay
+        rootspan = tracer.spanBuilder(queryID + " - live")
+                .startSpan();
+        List<String> completedTasks = new ArrayList<>();
+        Context parentContext = Context.current().with(rootspan);
+
+        Span initSpan = tracer.spanBuilder(queryID + " - 
live").setParent(parentContext).startSpan()
+                .setAttribute("queryID", lQuery.getQueryDisplay().getQueryId())
+                .setAttribute("queryString", 
lQuery.getQueryDisplay().getQueryString())
+                .setAttribute("Begin Time", lQuery.getBeginTime());
+        if (lQuery.getQueryDisplay().getErrorMessage() != null) {
+          initSpan.setAttribute("Error Message", 
lQuery.getQueryDisplay().getErrorMessage());
+        }
+        initSpan.end();
+
+        for (QueryDisplay.TaskDisplay task : 
lQuery.getQueryDisplay().getTaskDisplays()) {
+          if (task.getReturnValue() != null && task.getEndTime() != null) {
+            completedTasks.add(task.getTaskId());
+            parentContext = Context.current().with(rootspan);
+            tracer.spanBuilder(queryID + " - " + task.getTaskId() + " - live")
+                    
.setParent(parentContext).setAllAttributes(addTaskAttributes(task))
+                    .setStartTimestamp(task.getBeginTime(), 
TimeUnit.MILLISECONDS).startSpan()
+                    .end(task.getEndTime(), TimeUnit.MILLISECONDS);
+          }
+        }
+        queryIdToSpanMap.put(queryID,rootspan);
+        queryIdToTasksMap.put(queryID,completedTasks);
+      }
+    }
+
+    List<String> historicalQueryIDs = new ArrayList<>();
+    for (QueryInfo hQuery : historicalQueries) {
+      String hQueryId = hQuery.getQueryDisplay().getQueryId();
+      historicalQueryIDs.add(hQueryId);
+      Span rootspan = queryIdToSpanMap.get(hQueryId);
+
+      //For queries that were live till last loop but have ended before start 
of this loop
+      if (rootspan != null) {
+        for (QueryDisplay.TaskDisplay task : 
hQuery.getQueryDisplay().getTaskDisplays()) {
+          if (!queryIdToTasksMap.get(hQueryId).contains(task.getTaskId())) {
+            queryIdToTasksMap.get(hQueryId).add(task.getTaskId());
+            Context parentContext = Context.current().with(rootspan);
+            tracer.spanBuilder(hQueryId+ " - " + task.getTaskId() + " - 
completed")
+                    
.setParent(parentContext).setAllAttributes(addTaskAttributes(task))
+                    .setStartTimestamp(task.getBeginTime(), 
TimeUnit.MILLISECONDS).startSpan()
+                    .end(task.getEndTime(), TimeUnit.MILLISECONDS);
+          }
+        }
+
+        //Update the rootSpan name & attributes before ending it
+        rootspan.updateName(hQueryId + " - 
completed").setAllAttributes(addQueryAttributes(hQuery)).end();
+        queryIdToSpanMap.remove(hQueryId);
+        queryIdToTasksMap.remove(hQueryId);
+
+        historicalQueryId.add(hQueryId);
+      }
+
+      //For queries that already ended either before OTEL service started or 
in between OTEL loops
+      if (historicalQueryId.add(hQuery.getQueryDisplay().getQueryId())) {
+        rootspan = tracer.spanBuilder(hQuery.getQueryDisplay().getQueryId() + 
" - completed")
+                .startSpan();
+        Context parentContext = Context.current().with(rootspan);
+
+        Span initSpan = 
tracer.spanBuilder(hQuery.getQueryDisplay().getQueryId() + " - 
completed").setParent(parentContext).startSpan()
+                .setAttribute("queryID", hQuery.getQueryDisplay().getQueryId())
+                .setAttribute("queryString", 
hQuery.getQueryDisplay().getQueryString())
+                .setAttribute("Begin Time", hQuery.getBeginTime());

Review Comment:
   It would make initSpan and rootSpan storing the same content in case of 
historical queries. Would be better if we keep only these minimal attributes in 
initSpan so that there's consistency between live and historical traces.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscr...@hive.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscr...@hive.apache.org
For additional commands, e-mail: gitbox-h...@hive.apache.org

Reply via email to