Databricks SDK untuk R

Catatan

Artikel ini membahas Databricks SDK untuk R oleh Databricks Labs, yang dalam keadaan Eksperimental. Untuk memberikan umpan balik, mengajukan pertanyaan, dan melaporkan masalah, gunakan tab Masalah di repositori Databricks SDK for R di GitHub.

Dalam artikel ini, Anda mempelajari cara mengotomatiskan operasi Azure Databricks di ruang kerja Azure Databricks dengan Databricks SDK for R. Artikel ini melengkapi dokumentasi Databricks SDK for R.

Catatan

Databricks SDK for R tidak mendukung otomatisasi operasi di akun Azure Databricks. Untuk memanggil operasi tingkat akun, gunakan Databricks SDK yang berbeda, misalnya:

Sebelum Anda mulai

Sebelum Anda mulai menggunakan Databricks SDK untuk R, komputer pengembangan Anda harus memiliki:

  • Token akses pribadi Azure Databricks untuk ruang kerja Azure Databricks target yang ingin Anda otomatisasi.

    Catatan

    Databricks SDK for R hanya mendukung autentikasi token akses pribadi Azure Databricks.

  • R, dan secara opsional lingkungan pengembangan terintegrasi (IDE) yang kompatibel dengan R. Databricks merekomendasikan RStudio Desktop dan menggunakannya dalam instruksi artikel ini.

Mulai menggunakan Databricks SDK untuk R

  1. Buat URL ruang kerja Azure Databricks dan token akses pribadi Anda tersedia untuk skrip proyek R Anda. Misalnya, Anda dapat menambahkan yang berikut ini ke file proyek .Renviron R. Ganti <your-workspace-url> dengan URL per ruang kerja Anda, misalnya https://adb-1234567890123456.7.azuredatabricks.net. Ganti <your-personal-access-token> dengan token akses pribadi Azure Databricks Anda, misalnya dapi12345678901234567890123456789012.

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

    Untuk membuat token akses pribadi Azure Databricks, ikuti langkah-langkah di Membuat token akses pribadi untuk pengguna ruang kerja.

    Untuk cara tambahan untuk menyediakan URL ruang kerja Azure Databricks dan token akses pribadi Anda, lihat Autentikasi di repositori Databricks SDK for R di GitHub.

    Penting

    Jangan menambahkan .Renviron file ke sistem kontrol versi, karena risiko ini mengekspos informasi sensitif seperti token akses pribadi Azure Databricks.

  2. Instal paket Databricks SDK untuk R. Misalnya, di RStudio Desktop, di tampilan Konsol (Lihat > Pindahkan Fokus ke Konsol), jalankan perintah berikut, satu per satu:

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

    Catatan

    Paket Databricks SDK untuk R tidak tersedia di CRAN.

  3. Tambahkan kode untuk mereferensikan Databricks SDK untuk R dan untuk mencantumkan semua kluster di ruang kerja Azure Databricks Anda. Misalnya, dalam file proyek main.r , kodenya mungkin sebagai berikut:

    require(databricks)
    
    client <- DatabricksClient()
    
    list_clusters(client)[, "cluster_name"]
    
  4. Jalankan skrip Anda. Misalnya, di RStudio Desktop, di editor skrip dengan file proyek main.r aktif, klik Sumber Sumber > atau Sumber dengan Echo.

  5. Daftar kluster muncul. Misalnya, di RStudio Desktop, ini ada di tampilan Konsol .

Contoh kode

Contoh kode berikut menunjukkan cara menggunakan Databricks SDK untuk R untuk membuat dan menghapus kluster, dan membuat pekerjaan.

Membuat kluster

Contoh kode ini membuat kluster dengan versi Databricks Runtime dan jenis node kluster yang ditentukan. Kluster ini memiliki satu pekerja, dan kluster secara otomatis berakhir setelah 15 menit waktu diam.

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 = "")
)

Hapus kluster secara permanen

Contoh kode ini menghapus kluster secara permanen dengan ID kluster yang ditentukan dari ruang kerja.

require(databricks)

client <- DatabricksClient()

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

delete_cluster(client, cluster_id)

Membuat pekerjaan

Contoh kode ini membuat pekerjaan Azure Databricks yang dapat digunakan untuk menjalankan buku catatan yang ditentukan pada kluster yang ditentukan. Saat kode ini berjalan, kode ini mendapatkan jalur notebook yang ada, ID kluster yang ada, dan pengaturan pekerjaan terkait dari pengguna di konsol.

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 = "")
)

Pencatatan

Anda dapat menggunakan paket populer logging untuk mencatat pesan. Paket ini menyediakan dukungan untuk beberapa tingkat pengelogan dan format log kustom. Anda dapat menggunakan paket ini untuk mencatat pesan ke konsol atau ke file. Untuk mencatat pesan, lakukan hal berikut:

  1. Pasang paket logging. Misalnya, di RStudio Desktop, di tampilan Konsol (Lihat > Pindahkan Fokus ke Konsol), jalankan perintah berikut:

    install.packages("logging")
    library(logging)
    
  2. Bootstrap paket pencatatan log, atur tempat untuk mencatat pesan, dan mengatur tingkat pencatatan log. Misalnya, kode berikut mencatat semua pesan ERROR dan tingkat di bawahnya ke dalam file results.log.

    basicConfig()
    addHandler(writeToFile, file="results.log")
    setLevel("ERROR")
    
  3. Catat pesan sesuai kebutuhan. Misalnya, kode berikut mencatat kesalahan apa pun jika kode tidak dapat mengautentikasi atau mencantumkan nama kluster yang tersedia.

    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)
    })
    

Pengujian

Untuk menguji kode, Anda dapat menggunakan kerangka kerja pengujian R seperti testthat. Untuk menguji kode Anda dalam kondisi simulasi tanpa memanggil titik akhir REST API Azure Databricks atau mengubah keadaan akun atau ruang kerja Azure Databricks, Anda dapat menggunakan pustaka mocking R seperti mockery.

Misalnya, diberikan file berikut bernama helpers.r yang berisi fungsi createCluster yang mengembalikan informasi tentang kluster baru:

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)
}

Dan diberikan file berikut bernama main.R yang memanggil createCluster fungsi:

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)

File berikut bernama test-helpers.py menguji apakah createCluster fungsi mengembalikan respons yang diharapkan. Daripada membuat kluster di ruang kerja target, pengujian ini mensimulasikan objek DatabricksClient, mendefinisikan pengaturan objek yang disimulasikan, kemudian meneruskan objek yang disimulasikan ke fungsi createCluster. Pengujian kemudian memeriksa apakah fungsi mengembalikan ID yang diharapkan dari kluster baru yang di-mock.

# 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")
    }
  )
})

Sumber Daya Tambahan:

Untuk informasi selengkapnya, lihat: