다음을 통해 공유


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 개인용 액세스 토큰.

    참고 항목

    Azure Databricks 개인용 액세스 토큰 인증만 지원하는 R을 위한 Databricks SDK.

  • 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). <your-personal-access-token>을(를) Azure Databricks 개인용 액세스 토큰(예: dapi12345678901234567890123456789012)으로 변경합니다.

    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 파일이 활성화된 스크립트 편집기에서 > 소스 원본 제공 또는 에코를 사용하여 원본 제공을 클릭합니다.

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

코드 예제

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

클러스터 생성

이 코드 예제에서는 지정된 Databricks Runtime 버전 및 클러스터 노드 형식을 사용하여 클러스터를 만듭니다. 이 클러스터에는 하나의 작업자가 있으며 클러스터는 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")
    }
  )
})

추가 리소스

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