首页 > 解决方案 > 在 Azure Databricks Notebook 上检索群集不活动时间

问题描述

我是 Azure Databricks 的新手,我正在将它用于一个项目。

正如这里在文档中提到的Automatic termination那样

您还可以为集群设置自动终止。在集群创建期间,您可以指定inactivity period希望集群终止的分钟数。current time如果群集上的运行和运行之间的差异last command超过指定的非活动期,Azure Databricks 会自动终止该群集。

是否有一种解决方法可以通过集群 API或任何其他方法在 Azure Databricks Notebooks 上获取集群的实时非活动期(当前时间与集群上运行的最后一个命令之间的差异) ?

标签: azurecluster-computingdatabricksazure-databricksazure-notebooks

解决方案


# Function to retrieve cluster inactivity time
from datetime import datetime
import time

def cluster_inactivity_time(log_file_path):
 
  # Open log4j-active.log and read last line
  with open(log_file_path, "r") as file:
    first_line = file.readline()
    for last_line in file:
        pass
      
  # Convert last lines' timestamp to milliseconds
  last_run_time = last_line[9:17]
  current_date = datetime.now().strftime('%Y-%m-%d')
  last_run_datetime = round(datetime.strptime(current_date + ' ' + last_run_time, "%Y-%m-%d %H:%M:%S").timestamp() * 1000)
  
  # Finding the difference between current time and last command run time
  current_time = round(time.time() * 1000)
  difference = current_time - last_run_datetime
  inactivity_time = datetime.fromtimestamp(difference / 1000.0)
  print(f'The Cluster has been Inactive for {inactivity_time.hour}:{inactivity_time.minute}:{inactivity_time.second}')


# Function Call
log_file_path = '/dbfs/cluster-logs/0809-101642-leap143/driver/log4j-active.log'
cluster_inactivity_time(log_file_path)

输出:

集群已在 0:0:35 处于非活动状态


推荐阅读