You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by GitBox <gi...@apache.org> on 2019/10/17 11:34:29 UTC

[GitHub] [airflow] ashb commented on a change in pull request #6261: [AIRFLOW-5141] Added optional resource usage logging to KubernetesPod…

ashb commented on a change in pull request #6261: [AIRFLOW-5141] Added optional resource usage logging to KubernetesPod…
URL: https://github.com/apache/airflow/pull/6261#discussion_r335945777
 
 

 ##########
 File path: airflow/kubernetes/pod_usage_metrics_logger.py
 ##########
 @@ -0,0 +1,223 @@
+# 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.
+"""Logs resource usage of a pod"""
+import re
+import time
+from collections import defaultdict
+from datetime import datetime as dt, timedelta
+
+from kubernetes.client.models.v1_pod import V1Pod
+
+from airflow import LoggingMixin
+
+
+class PodUsageMetricsLogger(LoggingMixin):
+    """
+    This class logs all the resource usage metrics of a pod during the pod life time.
+    """
+    memory_usage_units = {'Ki': 1,
+                          'Mi': 2 ** 10,
+                          'Gi': 2 ** 20,
+                          'Ti': 2 ** 30,
+                          'Pi': 2 ** 40,
+                          'Ei': 2 ** 50,
+                          '': 1}
+    # Sometimes memory usage is not followed by unit if it is 0
+    # In these cases regex might return '' or None for unit.
+    valid_memory_usage_regex = re.compile(r'^([+]?[0-9]+?([.][0-9]+)?)(([KMGTPE][i])?)$')
+    # This regex checks for a positive float number with optional Ki, Mi, Gi, Ti, Pi, or Ei as unit
+
+    cpu_usage_units = {'m': 1,
+                       '': 1}  # Sometimes cpu usage is not followed by the unit when usage is 0
+    valid_cpu_usage_regex = re.compile(r'^([+]?[0-9]+?([.][0-9]+)?)([m]?)$')
+    # This regex check for a positive float number with optional millicpu(m) unit
+
+    def __init__(self,
+                 pod_launcher: object,  # (PodLauncher type) importing it might causes circular imports
+                 pod: V1Pod,
+                 resource_usage_fetch_interval: int,
+                 resource_usage_log_interval: int):
+        """
+        Creates the usage metrics logger.
+        :param pod_launcher: reference to the launcher of the metrics logger
+        :param pod: the pod we are logging the usage metrics
+        :param resource_usage_log_interval: logging interval in seconds
+        """
+        super().__init__()
+        self.pod_launcher = pod_launcher
+        self.pod = pod
+        self.resource_usage_fetch_interval = resource_usage_fetch_interval
+        self.resource_usage_log_interval = resource_usage_log_interval
+        self.max_cpu_usages = defaultdict(lambda: -1)  # type: dict
+        self.max_memory_usages = defaultdict(lambda: -1)  # type: dict
+
+    def log_pod_usage_metrics(self):
+        """
+        Periodically calls metrics api for the pod, logs current usage of the pod per container, and keeps
+        track of max usage seen for all containers.
+        :return:
+        """
+        if self.resource_usage_fetch_interval <= 0:
+            self.log.error('Parameter resource_usage_fetch_interval must be positive. Cancelling pod usage '
+                           'monitoring thread for pod: {0}.'.format(self.pod.metadata.name))
+            return
+        self.log.info('Pod usage monitoring thread started for pod: {0}'.format(self.pod.metadata.name))
+        resource_usage_api_url = "/apis/metrics.k8s.io/v1beta1/namespaces/{0}/pods/{1}"\
+                                 .format(self.pod.metadata.namespace,
+                                         self.pod.metadata.name)
+        cur_time = dt.now()
+        last_fetch_time = cur_time - timedelta(seconds=self.resource_usage_fetch_interval)
+        last_log_time = cur_time - timedelta(seconds=self.resource_usage_log_interval)
+        while self.pod_launcher.pod_is_running(self.pod):
+            if cur_time < last_fetch_time + timedelta(seconds=self.resource_usage_fetch_interval):
+                time.sleep(1)
 
 Review comment:
   Why not just sleep for `self.resource_usage_fetch_interval`?

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services