Lightning Engine meningkatkan konektivitas ke Cloud Storage untuk mengoptimalkan performa mesin native-nya. Konektor Cloud Storage yang ditingkatkan meminimalkan operasi metadata untuk mengurangi biaya, sementara file output committer yang dioptimalkan meningkatkan performa dan keandalan untuk workload Spark. Lengkapi formulir Akses Awal untuk meminta akses awal ke fitur pratinjau pribadi ini.
Tujuan
Tulis tugas wordcount Spark sederhana di Java, Scala, atau Python, lalu jalankan tugas di cluster Managed Service untuk Apache Spark.Biaya
Dalam dokumen ini, Anda akan menggunakan komponen Google Cloudyang dapat ditagih berikut:
- Compute Engine
- Managed Service for Apache Spark
- Cloud Storage
Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda,
gunakan kalkulator harga.
Sebelum memulai
Jalankan langkah-langkah di bawah untuk bersiap menjalankan kode dalam tutorial ini.
Menyiapkan project Anda. Jika perlu, siapkan project dengan Managed Service untuk Apache Spark, Compute Engine, dan Cloud Storage API yang diaktifkan serta Google Cloud CLI yang diinstal di komputer lokal Anda.
- Login ke akun Google Cloud Anda. Jika Anda baru menggunakan Google Cloud, buat akun untuk mengevaluasi performa produk kami dalam skenario dunia nyata. Pelanggan baru juga mendapatkan kredit gratis senilai $300 untuk menjalankan, menguji, dan men-deploy workload.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Dataproc, Compute Engine, and Cloud Storage APIs, if any are not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
Create a service account:
-
Ensure that you have the Create Service Accounts IAM role
(
roles/iam.serviceAccountCreator) and the Project IAM Admin role (roles/resourcemanager.projectIamAdmin). Learn how to grant roles. -
In the Google Cloud console, go to the Create service account page.
Go to Create service account - Select your project.
-
In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.
In the Service account description field, enter a description. For example,
Service account for quickstart. - Click Create and continue.
-
Grant the Project > Owner role to the service account.
To grant the role, find the Select a role list, then select Project > Owner.
- Click Continue.
-
Click Done to finish creating the service account.
Do not close your browser window. You will use it in the next step.
-
Ensure that you have the Create Service Accounts IAM role
(
-
Create a service account key:
- In the Google Cloud console, click the email address for the service account that you created.
- Click Keys.
- Click Add key, and then click Create new key.
- Click Create. A JSON key file is downloaded to your computer.
- Click Close.
-
Set the environment variable
GOOGLE_APPLICATION_CREDENTIALSto the path of the JSON file that contains your credentials. This variable applies only to your current shell session, so if you open a new session, set the variable again. -
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init -
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Dataproc, Compute Engine, and Cloud Storage APIs, if any are not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
Create a service account:
-
Ensure that you have the Create Service Accounts IAM role
(
roles/iam.serviceAccountCreator) and the Project IAM Admin role (roles/resourcemanager.projectIamAdmin). Learn how to grant roles. -
In the Google Cloud console, go to the Create service account page.
Go to Create service account - Select your project.
-
In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.
In the Service account description field, enter a description. For example,
Service account for quickstart. - Click Create and continue.
-
Grant the Project > Owner role to the service account.
To grant the role, find the Select a role list, then select Project > Owner.
- Click Continue.
-
Click Done to finish creating the service account.
Do not close your browser window. You will use it in the next step.
-
Ensure that you have the Create Service Accounts IAM role
(
-
Create a service account key:
- In the Google Cloud console, click the email address for the service account that you created.
- Click Keys.
- Click Add key, and then click Create new key.
- Click Create. A JSON key file is downloaded to your computer.
- Click Close.
-
Set the environment variable
GOOGLE_APPLICATION_CREDENTIALSto the path of the JSON file that contains your credentials. This variable applies only to your current shell session, so if you open a new session, set the variable again. -
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
Membuat bucket Cloud Storage. Anda memerlukan Cloud Storage untuk menyimpan data tutorial. Jika Anda belum memiliki bucket yang siap digunakan, buat bucket baru di project Anda.
- Di konsol Google Cloud , buka halaman Buckets Cloud Storage.
- Klik Create.
- Di halaman Buat bucket, masukkan informasi bucket Anda. Untuk melanjutkan ke
langkah berikutnya, klik Lanjutkan.
-
Di bagian Mulai, lakukan tindakan berikut:
- Masukkan nama yang unik secara global yang memenuhi persyaratan penamaan bucket.
- Untuk menambahkan label bucket, luaskan bagian Labels (), klik add_box
Add label, lalu tentukan
keydanvalueuntuk label Anda.
-
Di bagian Pilih tempat untuk menyimpan data Anda, lakukan tindakan berikut:
- Pilih Location type.
- Pilih lokasi tempat data bucket Anda disimpan secara permanen dari menu drop-down Location type.
- Jika memilih jenis lokasi dual-region, Anda juga dapat memilih untuk mengaktifkan replikasi turbo dengan menggunakan kotak centang yang relevan.
- Untuk menyiapkan replikasi lintas bucket, pilih
Tambahkan replikasi lintas bucket melalui Storage Transfer Service dan
ikuti langkah-langkah berikut:
Menyiapkan replikasi lintas bucket
- Di menu Bucket, pilih bucket.
Di bagian Replication settings, klik Configure guna mengonfigurasi setelan untuk tugas replikasi.
Panel Konfigurasi replikasi lintas bucket akan muncul.
- Untuk memfilter objek yang akan direplikasi berdasarkan awalan nama objek, masukkan awalan yang ingin Anda sertakan atau kecualikan objek, lalu klik Tambahkan awalan.
- Untuk menetapkan kelas penyimpanan bagi objek yang direplikasi, pilih kelas penyimpanan dari menu Storage class. Jika Anda melewati langkah ini, objek yang direplikasi akan menggunakan kelas penyimpanan bucket tujuan secara default.
- Klik Done.
-
Di bagian Choose how to store your data, lakukan tindakan berikut:
- Pilih kelas penyimpanan default untuk bucket atau Autoclass untuk pengelolaan kelas penyimpanan otomatis untuk data bucket Anda.
- Untuk mengaktifkan namespace hierarkis, di bagian Optimalkan penyimpanan untuk workload intensif data, pilih Aktifkan namespace hierarkis di bucket ini.
- Di bagian Choose how to control access to objects, pilih apakah bucket Anda menerapkan pencegahan akses publik atau tidak, lalu pilih metode kontrol akses untuk objek bucket Anda.
-
Di bagian Choose how to protect object data, lakukan hal berikut:
- Pilih salah satu opsi di bagian Perlindungan data yang ingin Anda tetapkan untuk bucket.
- Untuk mengaktifkan penghapusan sementara, klik kotak centang Kebijakan penghapusan sementara (Untuk pemulihan data), dan tentukan jumlah hari yang Anda inginkan untuk menyimpan objek setelah penghapusan.
- Untuk menetapkan Object Versioning, klik kotak centang Object versioning (Untuk kontrol versi), lalu tentukan jumlah maksimum versi per objek dan jumlah hari setelah versi lama tidak berlaku.
- Untuk mengaktifkan kebijakan retensi pada objek dan bucket, klik kotak centang Retensi (Untuk kepatuhan), lalu lakukan hal berikut:
- Untuk mengaktifkan Kunci Retensi Objek, centang kotak Aktifkan retensi objek.
- Untuk mengaktifkan Bucket Lock, centang kotak Set bucket retention policy, lalu pilih satuan waktu dan lama periode retensi data.
- Untuk memilih cara data objek Anda akan dienkripsi, luaskan bagian Data encryption (), lalu pilih metode Data encryption.
- Pilih salah satu opsi di bagian Perlindungan data yang ingin Anda tetapkan untuk bucket.
-
Di bagian Mulai, lakukan tindakan berikut:
- Klik Create.
Tetapkan variabel lingkungan lokal. Tetapkan variabel lingkungan di komputer lokal Anda. Tetapkan Google Cloud project-id dan nama bucket Cloud Storage yang akan Anda gunakan untuk tutorial ini. Berikan juga nama dan region cluster Managed Service untuk Apache Spark yang sudah ada atau baru. Anda dapat membuat cluster untuk digunakan dalam tutorial ini di langkah berikutnya.
PROJECT=project-id
BUCKET_NAME=bucket-name
CLUSTER=cluster-name
REGION=cluster-region Example: "us-central1"
Buat cluster Managed Service untuk Apache Spark. Jalankan perintah di bawah untuk membuat cluster Managed Service untuk Apache Spark satu node di zona Compute Engine yang ditentukan.
gcloud dataproc clusters create ${CLUSTER} \ --project=${PROJECT} \ --region=${REGION} \ --single-nodeSalin data publik ke bucket Cloud Storage Anda. Salin cuplikan teks Shakespeare data publik ke folder
inputdi bucket Cloud Storage Anda:gcloud storage cp gs://pub/shakespeare/rose.txt \ gs://${BUCKET_NAME}/input/rose.txtSiapkan lingkungan pengembangan Java (Apache Maven), Scala (SBT), atau Python.
Menyiapkan tugas wordcount Spark
Pilih tab di bawah untuk mengikuti langkah-langkah menyiapkan paket tugas atau file untuk dikirimkan ke cluster Anda. Anda dapat menyiapkan salah satu jenis pekerjaan berikut;
- Tugas Spark di Java menggunakan Apache Maven untuk membangun paket JAR
- Tugas Spark di Scala menggunakan SBT untuk membangun paket JAR
- Tugas Spark di Python (PySpark)
Java
- Salin file
pom.xmlke komputer lokal Anda. Filepom.xmlberikut menentukan dependensi library Scala dan Spark, yang diberi cakupanprovideduntuk menunjukkan bahwa cluster Managed Service untuk Apache Spark akan menyediakan library ini saat runtime. Filepom.xmltidak menentukan dependensi Cloud Storage karena konektor menerapkan antarmuka HDFS standar. Saat tugas Spark mengakses file cluster Cloud Storage (file dengan URI yang diawali dengangs://), sistem akan otomatis menggunakan konektor Cloud Storage untuk mengakses file di Cloud Storage<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>dataproc.codelab</groupId> <artifactId>word-count</artifactId> <version>1.0</version> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-library</artifactId> <version>Scala version, for example,
2.11.8</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-core_Scala major.minor.version, for example,2.11</artifactId> <version>Spark version, for example,2.3.1</version> <scope>provided</scope> </dependency> </dependencies> </project> - Salin kode
WordCount.javayang tercantum di bawah, ke komputer lokal Anda.- Buat serangkaian direktori dengan jalur
src/main/java/managed-spark/codelab:mkdir -p src/main/java/managed-spark/codelab
- Salin
WordCount.javake komputer lokal Anda ke dalamsrc/main/java/managed-spark/codelab:cp WordCount.java src/main/java/managed-spark/codelab
WordCount.javaadalah tugas Spark di Java yang membaca file teks dari Cloud Storage, melakukan penghitungan kata, lalu menulis hasil file teks ke Cloud Storage.package dataproc.codelab; import java.util.Arrays; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import scala.Tuple2; public class WordCount { public static void main(String[] args) { if (args.length != 2) { throw new IllegalArgumentException("Exactly 2 arguments are required: <inputUri> <outputUri>"); } String inputPath = args[0]; String outputPath = args[1]; JavaSparkContext sparkContext = new JavaSparkContext(new SparkConf().setAppName("Word Count")); JavaRDD<String> lines = sparkContext.textFile(inputPath); JavaRDD<String> words = lines.flatMap( (String line) -> Arrays.asList(line.split(" ")).iterator() ); JavaPairRDD<String, Integer> wordCounts = words.mapToPair( (String word) -> new Tuple2<>(word, 1) ).reduceByKey( (Integer count1, Integer count2) -> count1 + count2 ); wordCounts.saveAsTextFile(outputPath); } }
- Buat serangkaian direktori dengan jalur
- Bangun paket.
Jika build berhasil,mvn clean package
target/word-count-1.0.jarakan dibuat. - Tempatkan paket ke Cloud Storage.
gcloud storage cp target/word-count-1.0.jar \ gs://${BUCKET_NAME}/java/word-count-1.0.jar
Scala
- Salin file
build.sbtke komputer lokal Anda. Filebuild.sbtberikut menentukan dependensi library Scala dan Spark, yang diberi cakupanprovideduntuk menunjukkan bahwa cluster Managed Service untuk Apache Spark akan menyediakan library ini saat runtime. Filebuild.sbttidak menentukan dependensi Cloud Storage karena konektor menerapkan antarmuka HDFS standar. Saat tugas Spark mengakses file cluster Cloud Storage (file dengan URI yang dimulai dengangs://), sistem akan otomatis menggunakan konektor Cloud Storage untuk mengakses file di Cloud StoragescalaVersion := "Scala version, for example,
2.11.8" name := "word-count" organization := "dataproc.codelab" version := "1.0" libraryDependencies ++= Seq( "org.scala-lang" % "scala-library" % scalaVersion.value % "provided", "org.apache.spark" %% "spark-core" % "Spark version, for example,2.3.1" % "provided" ) - Salin
word-count.scalake komputer lokal Anda. Ini adalah tugas Spark di Java yang membaca file teks dari Cloud Storage, melakukan penghitungan kata, lalu menulis hasil file teks ke Cloud Storage.package dataproc.codelab import org.apache.spark.SparkContext import org.apache.spark.SparkConf object WordCount { def main(args: Array[String]) { if (args.length != 2) { throw new IllegalArgumentException( "Exactly 2 arguments are required: <inputPath> <outputPath>") } val inputPath = args(0) val outputPath = args(1) val sc = new SparkContext(new SparkConf().setAppName("Word Count")) val lines = sc.textFile(inputPath) val words = lines.flatMap(line => line.split(" ")) val wordCounts = words.map(word => (word, 1)).reduceByKey(_ + _) wordCounts.saveAsTextFile(outputPath) } }
- Bangun paket.
Jika build berhasil,sbt clean package
target/scala-2.11/word-count_2.11-1.0.jarakan dibuat. - Tempatkan paket ke Cloud Storage.
gcloud storage cp target/scala-2.11/word-count_2.11-1.0.jar \ gs://${BUCKET_NAME}/scala/word-count_2.11-1.0.jar
Python
- Salin
word-count.pyke komputer lokal Anda. Ini adalah tugas Spark di Python menggunakan PySpark yang membaca file teks dari Cloud Storage, melakukan penghitungan kata, lalu menulis hasil file teks ke Cloud Storage.#!/usr/bin/env python import pyspark import sys if len(sys.argv) != 3: raise Exception("Exactly 2 arguments are required: <inputUri> <outputUri>") inputUri=sys.argv[1] outputUri=sys.argv[2] sc = pyspark.SparkContext() lines = sc.textFile(sys.argv[1]) words = lines.flatMap(lambda line: line.split()) wordCounts = words.map(lambda word: (word, 1)).reduceByKey(lambda count1, count2: count1 + count2) wordCounts.saveAsTextFile(sys.argv[2])
Mengirim tugas
Jalankan perintah gcloud berikut untuk mengirimkan tugas wordcount ke cluster Managed Service untuk Apache Spark.
Java
gcloud dataproc jobs submit spark \
--cluster=${CLUSTER} \
--class=dataproc.codelab.WordCount \
--jars=gs://${BUCKET_NAME}/java/word-count-1.0.jar \
--region=${REGION} \
-- gs://${BUCKET_NAME}/input/ gs://${BUCKET_NAME}/output/
Scala
gcloud dataproc jobs submit spark \
--cluster=${CLUSTER} \
--class=dataproc.codelab.WordCount \
--jars=gs://${BUCKET_NAME}/scala/word-count_2.11-1.0.jar \
--region=${REGION} \
-- gs://${BUCKET_NAME}/input/ gs://${BUCKET_NAME}/output/
Python
gcloud dataproc jobs submit pyspark word-count.py \
--cluster=${CLUSTER} \
--region=${REGION} \
-- gs://${BUCKET_NAME}/input/ gs://${BUCKET_NAME}/output/
Melihat output
Setelah tugas selesai, jalankan perintah gcloud CLI berikut untuk melihat output wordcount.
gcloud storage cat gs://${BUCKET_NAME}/output/*
Output jumlah kata akan terlihat seperti berikut:
(a,2) (call,1) (What's,1) (sweet.,1) (we,1) (as,1) (name?,1) (any,1) (other,1) (rose,1) (smell,1) (name,1) (would,1) (in,1) (which,1) (That,1) (By,1)
Pembersihan
Setelah menyelesaikan tutorial, Anda dapat membersihkan resource yang dibuat agar tidak lagi menggunakan kuota dan menimbulkan tagihan. Bagian berikut menjelaskan cara menghapus atau menonaktifkan resource ini.
Menghapus project
Cara termudah untuk menghilangkan penagihan adalah dengan menghapus project yang Anda buat untuk tutorial.
Untuk menghapus project:
- Di konsol Google Cloud , buka halaman Manage resources.
- Pada daftar project, pilih project yang ingin Anda hapus, lalu klik Delete.
- Pada dialog, ketik project ID, lalu klik Shut down untuk menghapus project.
Menghapus cluster Managed Service untuk Apache Spark
Daripada menghapus project, Anda mungkin hanya ingin menghapus cluster dalam project.
Menghapus bucket Cloud Storage
KonsolGoogle Cloud
- Di konsol Google Cloud , buka halaman Buckets Cloud Storage.
- Klik kotak centang untuk bucket yang ingin Anda dihapus.
- Untuk menghapus bucket, klik Hapus, lalu ikuti petunjuk.
Command line
-
Hapus bucket:
gcloud storage buckets delete BUCKET_NAME