다음을 통해 공유


R용 Databricks SDK

참고 항목

이 문서에서는 실험적 상태인 Databricks Labs의 R용 Databricks SDK에 대해 설명합니다. 피드백을 제공하고, 질문하고, 문제를 보고하려면 GitHub의 R용 Databricks SDK 리포지토리의 문제 탭을 사용합니다.

이 문서에서는 R용 Databricks SDK를 사용하여 Azure Databricks 작업 영역 및 관련 리소스에서 작업을 자동화하는 방법을 알아봅니다. 이 문서에서는 R용 Databricks SDK 설명서를 보완합니다.

참고 항목

R용 Databricks SDK는 Azure Databricks 계정의 작업 자동화를 지원하지 않습니다. 계정 수준 작업을 호출하려면 다른 Databricks SDK를 사용합니다. 예를 들면 다음과 같습니다.

시작하기 전에

R용 Databricks SDK 사용을 시작하기 전에 개발 머신에 다음이 있어야 합니다.

  • 자동화하려는 대상 Azure Databricks 작업 영역에 대한 Azure Databricks 개인용 액세스 토큰 입니다.

    참고 항목

    R용 Databricks SDK는 Azure Databricks 개인용 액세스 토큰 인증만 지원합니다.

  • R 및 선택적으로 R 호환 IDE(통합 개발 환경)입니다. Databricks는 RStudio Desktop권장하고 이 문서의 지침에 사용합니다.

R용 Databricks SDK 시작

  1. R 프로젝트의 스크립트에서 Azure Databricks 작업 영역 URL 및 개인 액세스 토큰을 사용할 수 있도록 합니다. 예를 들어 R 프로젝트의 .Renviron 파일에 다음을 추가할 수 있습니다. <your-workspace-url>작업 영역별 URL로 바꿉니다(예: https://adb-1234567890123456.7.azuredatabricks.net). 예를 들어 dapi12345678901234567890123456789012Azure Databricks 개인용 액세스 토큰으로 대체 <your-personal-access-token> 합니다.

    DATABRICKS_HOST=<your-workspace-url>
    DATABRICKS_TOKEN=<your-personal-access-token>
    

    Azure Databricks 개인용 액세스 토큰을 만들려면 다음을 수행합니다.

    1. Azure Databricks 작업 영역의 위쪽 표시줄에서 Azure Databricks 사용자 이름을 클릭한 다음 드롭다운에서 설정 선택합니다.
    2. 개발자를 클릭합니다.
    3. 액세스 토큰 옆에 있는 관리를 클릭합니다.
    4. 새 토큰 생성을 클릭합니다.
    5. (선택 사항) 나중에 이 토큰을 식별할 수 있도록 하는 설명을 입력하고 토큰의 기본 수명을 90일로 변경합니다. 수명이 없는 토큰을 만들려면(권장하지 않음) 수명(일) 상자를 비워 둡니다(공백).
    6. 생성을 클릭합니다.
    7. 표시된 토큰을 안전한 위치에 복사한 다음 완료를 클릭합니다.

    참고 항목

    복사한 토큰을 안전한 위치에 저장합니다. 복사한 토큰을 다른 사용자와 공유하지 마세요. 복사한 토큰을 분실하면 정확히 동일한 토큰을 다시 생성할 수 없습니다. 대신 이 프로시저를 반복하여 새 토큰을 만들어야 합니다. 복사한 토큰이 손실되었거나 토큰이 손상되었다고 생각되는 경우 Databricks는 액세스 토큰 페이지의 토큰 옆에 있는 휴지통(해지) 아이콘을 클릭하여 작업 영역에서 해당 토큰 을 즉시 삭제하는 것이 좋습니다.

    작업 영역에서 토큰을 만들거나 사용할 수 없는 경우 작업 영역 관리자가 토큰을 사용하지 않도록 설정했거나 토큰을 만들거나 사용할 수 있는 권한을 부여하지 않았기 때문일 수 있습니다. 작업 영역 관리자 또는 다음을 참조하세요.

    Azure Databricks 작업 영역 URL 및 개인 액세스 토큰을 제공하는 추가 방법은 GitHub의 R용 Databricks SDK 리포지토리에서 인증을 참조하세요.

    Important

    Azure Databricks 개인용 액세스 토큰과 같은 중요한 정보를 노출할 위험이 있으므로 버전 제어 시스템에 파일을 추가 .Renviron 하지 마세요.

  2. R용 Databricks SDK 패키지를 설치합니다. 예를 들어 RStudio Desktop의 콘솔 보기(콘솔로 포커스 이동 보기>)에서 한 번에 하나씩 다음 명령을 실행합니다.

    install.packages("devtools")
    library(devtools)
    install_github("databrickslabs/databricks-sdk-r")
    

    참고 항목

    R용 Databricks SDK 패키지는 CRAN에서 사용할 수 없습니다.

  3. R용 Databricks SDK를 참조하고 Azure Databricks 작업 영역의 모든 클러스터를 나열하는 코드를 추가합니다. 예를 들어 프로젝트의 main.r 파일에서 코드는 다음과 같습니다.

    require(databricks)
    
    client <- DatabricksClient()
    
    list_clusters(client)[, "cluster_name"]
    
  4. 스크립트를 실행합니다. 예를 들어 RStudio Desktop의 프로젝트 main.r 파일이 활성 상태인 스크립트 편집기에서 Echo가 있는 원본 > 또는 원본을 클릭합니다.

  5. 클러스터 목록이 나타납니다. 예를 들어 RStudio Desktop에서 콘솔 보기에 있습니다.

코드 예제

다음 코드 예제에서는 R용 Databricks SDK를 사용하여 클러스터를 만들고 삭제하고 작업을 만드는 방법을 보여 줍니다.

클러스터 만들기

이 코드 예제에서는 지정된 Databricks 런타임 버전 및 클러스터 노드 형식을 사용하여 클러스터를 만듭니다. 이 클러스터에는 하나의 작업자가 있으며, 클러스터는 15분의 유휴 시간 후에 자동으로 종료됩니다.

require(databricks)

client <- DatabricksClient()

response <- create_cluster(
  client = client,
  cluster_name = "my-cluster",
  spark_version = "12.2.x-scala2.12",
  node_type_id = "Standard_DS3_v2",
  autotermination_minutes = 15,
  num_workers = 1
)

# Get the workspace URL to be used in the following results message.
get_client_debug <- strsplit(client$debug_string(), split = "host=")
get_host <- strsplit(get_client_debug[[1]][2], split = ",")
host <- get_host[[1]][1]

# Make sure the workspace URL ends with a forward slash.
if (endsWith(host, "/")) {
} else {
  host <- paste(host, "/", sep = "")
}

print(paste(
  "View the cluster at ",
  host,
  "#setting/clusters/",
  response$cluster_id,
  "/configuration",
  sep = "")
)

클러스터 영구 삭제

이 코드 예제에서는 작업 영역에서 지정된 클러스터 ID를 사용하여 클러스터를 영구적으로 삭제합니다.

require(databricks)

client <- DatabricksClient()

cluster_id <- readline("ID of the cluster to delete (for example, 1234-567890-ab123cd4):")

delete_cluster(client, cluster_id)

작업 만들기

이 코드 예제에서는 지정된 클러스터에서 지정된 Notebook을 실행하는 데 사용할 수 있는 Azure Databricks 작업을 만듭니다. 이 코드가 실행되면 콘솔의 사용자로부터 기존 Notebook의 경로, 기존 클러스터 ID 및 관련 작업 설정을 가져옵니다.

require(databricks)

client <- DatabricksClient()

job_name <- readline("Some short name for the job (for example, my-job):")
description <- readline("Some short description for the job (for example, My job):")
existing_cluster_id <- readline("ID of the existing cluster in the workspace to run the job on (for example, 1234-567890-ab123cd4):")
notebook_path <- readline("Workspace path of the notebook to run (for example, /Users/someone@example.com/my-notebook):")
task_key <- readline("Some key to apply to the job's tasks (for example, my-key):")

print("Attempting to create the job. Please wait...")

notebook_task <- list(
  notebook_path = notebook_path,
  source = "WORKSPACE"
)

job_task <- list(
  task_key = task_key,
  description = description,
  existing_cluster_id = existing_cluster_id,
  notebook_task = notebook_task
)

response <- create_job(
  client,
  name = job_name,
  tasks = list(job_task)
)

# Get the workspace URL to be used in the following results message.
get_client_debug <- strsplit(client$debug_string(), split = "host=")
get_host <- strsplit(get_client_debug[[1]][2], split = ",")
host <- get_host[[1]][1]

# Make sure the workspace URL ends with a forward slash.
if (endsWith(host, "/")) {
} else {
  host <- paste(host, "/", sep = "")
}

print(paste(
  "View the job at ",
  host,
  "#job/",
  response$job_id,
  sep = "")
)

로깅

인기 있는 logging 패키지를 사용하여 메시지를 기록할 수 있습니다. 이 패키지는 여러 로깅 수준 및 사용자 지정 로그 형식을 지원합니다. 이 패키지를 사용하여 콘솔 또는 파일에 메시지를 기록할 수 있습니다. 메시지를 기록하려면 다음을 수행합니다.

  1. logging 패키지를 설치합니다. 예를 들어 RStudio Desktop의 콘솔 보기(콘솔로 포커스 이동 보기>)에서 다음 명령을 실행합니다.

    install.packages("logging")
    library(logging)
    
  2. 로깅 패키지를 부트스트랩하고, 메시지를 기록할 위치를 설정하고, 로깅 수준을 설정합니다. 예를 들어 다음 코드는 모든 ERROR 메시지를 파일에 기록합니다 results.log .

    basicConfig()
    addHandler(writeToFile, file="results.log")
    setLevel("ERROR")
    
  3. 필요에 따라 메시지를 기록합니다. 예를 들어 다음 코드는 코드가 사용 가능한 클러스터의 이름을 인증하거나 나열할 수 없는 경우 오류를 기록합니다.

    require(databricks)
    require(logging)
    
    basicConfig()
    addHandler(writeToFile, file="results.log")
    setLevel("ERROR")
    
    tryCatch({
      client <- DatabricksClient()
    }, error = function(e) {
      logerror(paste("Error initializing DatabricksClient(): ", e$message))
      return(NA)
    })
    
    tryCatch({
      list_clusters(client)[, "cluster_name"]
    }, error = function(e) {
      logerror(paste("Error in list_clusters(client): ", e$message))
      return(NA)
    })
    

테스팅

코드를 테스트하려면 testthat과 같은 R 테스트 프레임워크를 사용할 수 있습니다. Azure Databricks REST API 엔드포인트를 호출하거나 Azure Databricks 계정 또는 작업 영역의 상태를 변경하지 않고 시뮬레이션된 조건에서 코드를 테스트하려면 조롱과 같은 R 모의 라이브러리를 사용할 수 있습니다.

예를 들어 새 클러스터에 대한 정보를 반환하는 함수를 createCluster 포함하는 다음 파일을 지정 helpers.r 합니다.

library(databricks)

createCluster <- function(
  databricks_client,
  cluster_name,
  spark_version,
  node_type_id,
  autotermination_minutes,
  num_workers
) {
  response <- create_cluster(
    client = databricks_client,
    cluster_name = cluster_name,
    spark_version = spark_version,
    node_type_id = node_type_id,
    autotermination_minutes = autotermination_minutes,
    num_workers = num_workers
  )
  return(response)
}

함수를 호출 createCluster 하는 다음과 같은 파일이 제공됩니다main.R.

library(databricks)
source("helpers.R")

client <- DatabricksClient()

# Replace <spark-version> with the target Spark version string.
# Replace <node-type-id> with the target node type string.
response = createCluster(
  databricks_client = client,
  cluster_name = "my-cluster",
  spark_version = "<spark-version>",
  node_type_id = "<node-type-id>",
  autotermination_minutes = 15,
  num_workers = 1
)

print(response$cluster_id)

명명된 test-helpers.py 다음 파일은 함수가 createCluster 예상 응답을 반환하는지 여부를 테스트합니다. 이 테스트는 대상 작업 영역에서 클러스터를 만드는 대신 개체를 DatabricksClient 모의하고 모의 개체의 설정을 정의한 다음 모의 개체를 함수에 createCluster 전달합니다. 그런 다음 테스트는 함수가 모의 클러스터의 예상 ID를 반환하는지 여부를 검사.

# install.packages("testthat")
# install.pacakges("mockery")
# testthat::test_file("test-helpers.R")
lapply(c("databricks", "testthat", "mockery"), library, character.only = TRUE)
source("helpers.R")

test_that("createCluster mock returns expected results", {
  # Create a mock response.
  mock_response <- list(cluster_id = "abc123")

  # Create a mock function for create_cluster().
  mock_create_cluster <- mock(return_value = mock_response)

  # Run the test with the mock function.
  with_mock(
    create_cluster = mock_create_cluster,
    {
      # Create a mock Databricks client.
      mock_client <- mock()

      # Call the function with the mock client.
      # Replace <spark-version> with the target Spark version string.
      # Replace <node-type-id> with the target node type string.
      response <- createCluster(
        databricks_client = mock_client,
        cluster_name = "my-cluster",
        spark_version = "<spark-version>",
        node_type_id = "<node-type-id>",
        autotermination_minutes = 15,
        num_workers = 1
      )

      # Check that the function returned the correct mock response.
      expect_equal(response$cluster_id, "abc123")
    }
  )
})

추가 리소스

자세한 내용은 다음을 참조하세요.