Bagikan melalui


Databricks SDK for Go

Dalam artikel ini, Anda mempelajari cara mengotomatiskan operasi di akun Azure Databricks, ruang kerja, dan sumber daya terkait dengan Databricks SDK for Go. Artikel ini melengkapi Databricks SDK untuk Go README, referensi API, dan contoh.

Catatan

Fitur ini ada di Beta dan tidak apa-apa untuk digunakan dalam produksi.

Selama periode Beta, Databricks merekomendasikan agar Anda menyematkan dependensi pada versi minor tertentu dari Databricks SDK for Go yang bergantung pada kode Anda, misalnya, dalam file proyek go.mod . Untuk informasi selengkapnya tentang menyematkan dependensi, lihat Mengelola dependensi.

Sebelum Anda mulai

Sebelum Anda mulai menggunakan Databricks SDK for Go, komputer pengembangan Anda harus memiliki:

Mulai menggunakan Databricks SDK for Go

  1. Pada komputer pengembangan Anda dengan Go sudah diinstal, proyek kode Go yang sudah dibuat, dan autentikasi Azure Databricks dikonfigurasi, buat go.mod file untuk melacak dependensi kode Go Anda dengan menjalankan go mod init perintah, misalnya:

    go mod init sample
    
  2. Ambil dependensi pada paket Databricks SDK for Go dengan menjalankan go mod edit -require perintah , mengganti 0.8.0 dengan versi terbaru paket Databricks SDK for Go seperti yang tercantum dalam CHANGELOG:

    go mod edit -require github.com/databricks/databricks-sdk-go@v0.8.0
    

    Sekarang file go.mod Anda akan terlihat seperti ini:

    module sample
    
    go 1.18
    
    require github.com/databricks/databricks-sdk-go v0.8.0
    
  3. Dalam proyek Anda, buat file kode Go yang mengimpor Databricks SDK for Go. Contoh berikut, dalam file main.go bernama dengan konten berikut, mencantumkan semua kluster di ruang kerja Azure Databricks Anda:

    package main
    
    import (
      "context"
    
      "github.com/databricks/databricks-sdk-go"
      "github.com/databricks/databricks-sdk-go/service/compute"
    )
    
    func main() {
      w := databricks.Must(databricks.NewWorkspaceClient())
      all, err := w.Clusters.ListAll(context.Background(), compute.ListClustersRequest{})
      if err != nil {
        panic(err)
      }
      for _, c := range all {
        println(c.ClusterName)
      }
    }
    
  4. Tambahkan dependensi modul yang hilang dengan menjalankan go mod tidy perintah:

    go mod tidy
    

    Catatan

    Jika Anda mendapatkan kesalahan go: warning: "all" matched no packages, Anda lupa menambahkan file kode Go yang mengimpor Databricks SDK for Go.

  5. Ambil salinan semua paket yang diperlukan untuk mendukung build dan pengujian paket dalam modul Anda main , dengan menjalankan go mod vendor perintah:

    go mod vendor
    
  6. Siapkan komputer pengembangan Anda untuk autentikasi Azure Databricks.

  7. Jalankan file kode Go Anda, dengan asumsi file bernama main.go, dengan menjalankan go run perintah:

    go run main.go
    

    Catatan

    Dengan tidak mengatur *databricks.Config sebagai argumen dalam panggilan sebelumnya ke w := databricks.Must(databricks.NewWorkspaceClient()), Databricks SDK for Go menggunakan proses defaultnya untuk mencoba melakukan autentikasi Azure Databricks. Untuk mengambil alih perilaku default ini, lihat Mengautentikasi Databricks SDK for Go dengan akun atau ruang kerja Azure Databricks Anda.

Memperbarui SDK Databricks untuk Go

Untuk memperbarui proyek Go Anda untuk menggunakan salah satu paket Databricks SDK for Go seperti yang tercantum dalam CHANGELOG, lakukan hal berikut:

  1. go get Jalankan perintah dari akar proyek Anda, tentukan -u bendera untuk melakukan pembaruan, dan berikan nama dan nomor versi target paket Databricks SDK for Go. Misalnya, untuk memperbarui ke versi 0.12.0, jalankan perintah berikut:

    go get -u github.com/databricks/databricks-sdk-go@v0.12.0
    
  2. Tambahkan dan perbarui dependensi modul yang hilang dan kedaluarsa dengan menjalankan go mod tidy perintah:

    go mod tidy
    
  3. Ambil salinan semua paket baru dan yang diperbarui yang diperlukan untuk mendukung build dan pengujian paket dalam modul Anda main , dengan menjalankan go mod vendor perintah:

    go mod vendor
    

Mengautentikasi Databricks SDK for Go dengan akun atau ruang kerja Azure Databricks Anda

Databricks SDK for Go menerapkan standar autentikasi terpadu klien Databricks, pendekatan arsitektur dan terprogram yang terkonsolidasi dan konsisten untuk autentikasi. Pendekatan ini membantu menyiapkan dan mengotomatiskan autentikasi dengan Azure Databricks lebih terpusat dan dapat diprediksi. Ini memungkinkan Anda untuk mengonfigurasi autentikasi Databricks sekali dan kemudian menggunakan konfigurasi tersebut di beberapa alat Databricks dan SDK tanpa perubahan konfigurasi autentikasi lebih lanjut. Untuk informasi selengkapnya, termasuk contoh kode yang lebih lengkap di Go, lihat Autentikasi terpadu klien Databricks.

Beberapa pola pengkodian yang tersedia untuk menginisialisasi autentikasi Databricks dengan Databricks SDK for Go meliputi:

  • Gunakan autentikasi default Databricks dengan melakukan salah satu hal berikut:

    • Buat atau identifikasi profil konfigurasi Databricks kustom dengan bidang yang diperlukan untuk jenis autentikasi Databricks target. Kemudian atur DATABRICKS_CONFIG_PROFILE variabel lingkungan ke nama profil konfigurasi kustom.
    • Atur variabel lingkungan yang diperlukan untuk jenis autentikasi Databricks target.

    Kemudian buat contoh objek dengan autentikasi WorkspaceClient default Databricks sebagai berikut:

    import (
      "github.com/databricks/databricks-sdk-go"
    )
    // ...
    w := databricks.Must(databricks.NewWorkspaceClient())
    
  • Hard-coding bidang yang diperlukan didukung tetapi tidak disarankan, karena berisiko mengekspos informasi sensitif dalam kode Anda, seperti token akses pribadi Azure Databricks. Contoh host Azure Databricks kode keras berikut dan nilai token akses untuk autentikasi token Databricks:

    import (
      "github.com/databricks/databricks-sdk-go"
      "github.com/databricks/databricks-sdk-go/config"
    )
    // ...
    w := databricks.Must(databricks.NewWorkspaceClient(&databricks.Config{
      Host:  "https://...",
      Token: "...",
    }))
    

Lihat juga Autentikasi di SDK Databricks untuk Go README.

Contoh

Contoh kode berikut menunjukkan cara menggunakan Databricks SDK for Go untuk membuat dan menghapus kluster, menjalankan pekerjaan, dan mencantumkan pengguna akun. Contoh kode ini menggunakan proses autentikasi Azure Databricks SDK for Go default.

Untuk contoh kode tambahan, lihat folder contoh di repositori Databricks SDK for Go di GitHub.

Membuat kluster

Contoh kode ini membuat kluster dengan versi Databricks Runtime Long Term Support (LTS) terbaru yang tersedia dan jenis node kluster terkecil yang tersedia dengan disk lokal. Kluster ini memiliki satu pekerja, dan kluster akan secara otomatis berakhir setelah 15 menit waktu diam. Panggilan CreateAndWait metode menyebabkan kode dijeda hingga kluster baru berjalan di ruang kerja.

package main

import (
  "context"
  "fmt"

  "github.com/databricks/databricks-sdk-go"
  "github.com/databricks/databricks-sdk-go/service/compute"
)

func main() {
  const clusterName            = "my-cluster"
  const autoTerminationMinutes = 15
  const numWorkers             = 1

  w   := databricks.Must(databricks.NewWorkspaceClient())
  ctx := context.Background()

  // Get the full list of available Spark versions to choose from.
  sparkVersions, err := w.Clusters.SparkVersions(ctx)

  if err != nil {
    panic(err)
  }

  // Choose the latest Long Term Support (LTS) version.
  latestLTS, err := sparkVersions.Select(compute.SparkVersionRequest{
    Latest:          true,
    LongTermSupport: true,
  })

  if err != nil {
    panic(err)
  }

  // Get the list of available cluster node types to choose from.
  nodeTypes, err := w.Clusters.ListNodeTypes(ctx)

  if err != nil {
    panic(err)
  }

  // Choose the smallest available cluster node type.
  smallestWithLocalDisk, err := nodeTypes.Smallest(clusters.NodeTypeRequest{
    LocalDisk: true,
  })

  if err != nil {
    panic(err)
  }

  fmt.Println("Now attempting to create the cluster, please wait...")

  runningCluster, err := w.Clusters.CreateAndWait(ctx, compute.CreateCluster{
    ClusterName:            clusterName,
    SparkVersion:           latestLTS,
    NodeTypeId:             smallestWithLocalDisk,
    AutoterminationMinutes: autoTerminationMinutes,
    NumWorkers:             numWorkers,
  })

  if err != nil {
    panic(err)
  }

  switch runningCluster.State {
  case compute.StateRunning:
    fmt.Printf("The cluster is now ready at %s#setting/clusters/%s/configuration\n",
      w.Config.Host,
      runningCluster.ClusterId,
    )
  default:
    fmt.Printf("Cluster is not running or failed to create. %s", runningCluster.StateMessage)
  }

  // Output:
  //
  // Now attempting to create the cluster, please wait...
  // The cluster is now ready at <workspace-host>#setting/clusters/<cluster-id>/configuration
}

Hapus kluster secara permanen

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

package main

import (
  "context"

  "github.com/databricks/databricks-sdk-go"
  "github.com/databricks/databricks-sdk-go/service/clusters"
)

func main() {
  // Replace with your cluster's ID.
  const clusterId = "1234-567890-ab123cd4"

  w   := databricks.Must(databricks.NewWorkspaceClient())
  ctx := context.Background()

  err := w.Clusters.PermanentDelete(ctx, compute.PermanentDeleteCluster{
    ClusterId: clusterId,
  })

  if err != nil {
    panic(err)
  }
}

Menjalankan pekerjaan

Contoh kode ini membuat pekerjaan Azure Databricks yang menjalankan notebook yang ditentukan pada kluster yang ditentukan. Saat kode berjalan, kode mendapatkan jalur notebook yang ada, ID kluster yang ada, dan pengaturan pekerjaan terkait dari pengguna di terminal. Panggilan RunNowAndWait metode menyebabkan kode dijeda hingga pekerjaan baru selesai berjalan di ruang kerja.

package main

import (
  "bufio"
  "context"
  "fmt"
  "os"
  "strings"

  "github.com/databricks/databricks-sdk-go"
  "github.com/databricks/databricks-sdk-go/service/jobs"
)

func main() {
  w   := databricks.Must(databricks.NewWorkspaceClient())
  ctx := context.Background()

  nt := jobs.NotebookTask{
    NotebookPath: askFor("Workspace path of the notebook to run:"),
  }

  jobToRun, err := w.Jobs.Create(ctx, jobs.CreateJob{
    Name: askFor("Some short name for the job:"),
    Tasks: []jobs.JobTaskSettings{
      {
        Description:       askFor("Some short description for the job:"),
        TaskKey:           askFor("Some key to apply to the job's tasks:"),
        ExistingClusterId: askFor("ID of the existing cluster in the workspace to run the job on:"),
        NotebookTask:      &nt,
      },
    },
  })

  if err != nil {
    panic(err)
  }

  fmt.Printf("Now attempting to run the job at %s/#job/%d, please wait...\n",
    w.Config.Host,
    jobToRun.JobId,
  )

  runningJob, err := w.Jobs.RunNow(ctx, jobs.RunNow{
    JobId: jobToRun.JobId,
  })

  if err != nil {
    panic(err)
  }

  jobRun, err := runningJob.Get()

  if err != nil {
    panic(err)
  }

  fmt.Printf("View the job run results at %s/#job/%d/run/%d\n",
    w.Config.Host,
    jobRun.JobId,
    jobRun.RunId,
  )

  // Output:
  //
  // Now attempting to run the job at <workspace-host>/#job/<job-id>, please wait...
  // View the job run results at <workspace-host>/#job/<job-id>/run/<run-id>
}

// Get job settings from the user.
func askFor(prompt string) string {
  var s string
  r := bufio.NewReader(os.Stdin)
  for {
    fmt.Fprint(os.Stdout, prompt+" ")
    s, _ = r.ReadString('\n')
    if s != "" {
      break
    }
  }
  return strings.TrimSpace(s)
}

Mengelola file dalam volume Katalog Unity

Contoh kode ini menunjukkan berbagai panggilan ke files fungsionalitas dalam WorkspaceClient untuk mengakses volume Katalog Unity.

package main

import (
  "context"
  "io"
  "os"

  "github.com/databricks/databricks-sdk-go"
  "github.com/databricks/databricks-sdk-go/service/files"
)

func main() {
  w := databricks.Must(databricks.NewWorkspaceClient())

  catalog          := "main"
  schema           := "default"
  volume           := "my-volume"
  volumePath       := "/Volumes/" + catalog + "/" + schema + "/" + volume // /Volumes/main/default/my-volume
  volumeFolder     := "my-folder"
  volumeFolderPath := volumePath + "/" + volumeFolder // /Volumes/main/default/my-volume/my-folder
  volumeFile       := "data.csv"
  volumeFilePath   := volumeFolderPath + "/" + volumeFile // /Volumes/main/default/my-volume/my-folder/data.csv
  uploadFilePath   := "./data.csv"

  // Create an empty folder in a volume.
  err := w.Files.CreateDirectory(
    context.Background(),
    files.CreateDirectoryRequest{DirectoryPath: volumeFolderPath},
  )
  if err != nil {
    panic(err)
  }

  // Upload a file to a volume.
  fileUpload, err := os.Open(uploadFilePath)
  if err != nil {
    panic(err)
  }
  defer fileUpload.Close()

  w.Files.Upload(
    context.Background(),
    files.UploadRequest{
      Contents:  fileUpload,
      FilePath:  volumeFilePath,
      Overwrite: true,
    },
  )

  // List the contents of a volume.
  items := w.Files.ListDirectoryContents(
    context.Background(),
    files.ListDirectoryContentsRequest{DirectoryPath: volumePath},
  )

  for {
    if items.HasNext(context.Background()) {
      item, err := items.Next(context.Background())
      if err != nil {
        break
      }
      println(item.Path)

    } else {
      break
    }
  }

  // List the contents of a folder in a volume.
  itemsFolder := w.Files.ListDirectoryContents(
    context.Background(),
    files.ListDirectoryContentsRequest{DirectoryPath: volumeFolderPath},
  )

  for {
    if itemsFolder.HasNext(context.Background()) {
      item, err := itemsFolder.Next(context.Background())
      if err != nil {
        break
      }
      println(item.Path)
    } else {
      break
    }
  }

  // Print the contents of a file in a volume.
  file, err := w.Files.DownloadByFilePath(
    context.Background(),
    volumeFilePath,
  )
  if err != nil {
    panic(err)
  }

  bufDownload := make([]byte, file.ContentLength)

  for {
    file, err := file.Contents.Read(bufDownload)
    if err != nil && err != io.EOF {
      panic(err)
    }
    if file == 0 {
      break
    }

    println(string(bufDownload[:file]))
  }

  // Delete a file from a volume.
  w.Files.DeleteByFilePath(
    context.Background(),
    volumeFilePath,
  )

  // Delete a folder from a volume.
  w.Files.DeleteDirectory(
    context.Background(),
    files.DeleteDirectoryRequest{
      DirectoryPath: volumeFolderPath,
    },
  )
}

Mencantumkan pengguna akun

Contoh kode ini mencantumkan pengguna yang tersedia dalam akun Azure Databricks.

package main

import (
  "context"

  "github.com/databricks/databricks-sdk-go"
  "github.com/databricks/databricks-sdk-go/service/iam"
)

func main() {
  a := databricks.Must(databricks.NewAccountClient())
  all, err := a.Users.ListAll(context.Background(), iam.ListAccountUsersRequest{})
  if err != nil {
    panic(err)
  }
  for _, u := range all {
    println(u.UserName)
  }
}

Sumber Daya Tambahan:

Untuk informasi selengkapnya, lihat: