ErikaRosas
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Cloud Dataproc Dataproc en GCP nos permitirá tener el mismo ecosistema opensource de Hadoop y Spark. Esto permite correr los mismos códigos para Big Data que tengan hechos directamente en GCP, sin cambios, y con la ventaja de tener un cluster en cosa de minutos. En este ejemplo, veremos lo sencillo que es crear un cluster en Dataproc, con un nodo maestro y dos workers. Para ejemplificar el uso del cluster usaremos Spark SQL usando Jupyter Notebooks que ejecutará el trabajo sobre este cluster de Dataproc. Los datos a analizar los pondremos primero en HDFS y luego en Cloud Storage, para desacoplar la computación del almacenamiento. Finalmente, pasaremos el trabajo del notebook a un archivo python para que sea lanzado como un trabajo (job) al cluster. ## Cluster de Cloud Dataproc Buscaremos Dataproc en el menú de navegación, y le pondremos un pin para encontrarlo rápidamente la siguiente vez. Habilite la API en caso que no esté habilitada con anterioridad. Haz click en **CREATE CLUSTER**. ![](https://i.imgur.com/KcjEMpm.png) Luego da la opción entre usar Compute Engine o GKE, elegiremos Compute Engine. ![](https://i.imgur.com/ak387i2.png) Le pondremos un nombre a nuestro cluster, por ejemplo "midataproccluster", seleccionamos región, el tipo de cluster dejaremos el **Standard**. ![](https://i.imgur.com/agoNiH2.png) Luego pon **CHANGE** en la sección **Versioning** y selecciona 2.0 (Debian 10, Hadoop 3.2, Spark 3.1). Aquí es donde ajustas las versiones de los software que necesitas y si no están puedes proveer una imagen hecha por ti. Pon **SELECT**. ![](https://i.imgur.com/IyHiIhG.png) En la sección **Components**, haz click en **Enable component gateway**. Y en **Optional Components** selecciona **Jupyter Notebooks**. ![](https://i.imgur.com/h588Ybh.png) Explora las configuraciones opcionales, pero deja los valores por defecto. Haz click en Equivalent Command Line para ver el gcloud command que crea el cluster que configuraste sin necesidad de tantos clicks. Puedes copiarlo, es útil el caso de que tengas que cerrar el trabajo antes de terminar el lab y luego quieras partir sin perder minutos en configuración. ![](https://i.imgur.com/3TSpfjr.png) Luego presiona **CREATE** para crear el cluster. Deberías ver luego de unos minutos el cluster en estado *Running*, como en la siguiente figura. ![](https://i.imgur.com/i3DlgSi.png) ***UPDATE*** Si no te deja crear el cluster con la configuración que tienes, intenta cambiando el tipo de máquinas del cluster. Esto se hace en "Configure nodes. Allí puedes elegir nodos de la Serie N1, tanto para el Manager como para los dos nodos Workers. ![](https://hackmd.io/_uploads/SylpeBXA3.png) ## Usando software instalado en Dataproc (Jupyter) Abre el cloud Shell y sube el notebook que está en el siguiente link que ocuparemos como ejemplo. [Archivo spark-hdfs2.ipynb](https://drive.google.com/file/d/1ze0lIwYJ6cjfyKoV2kXIEKcKGHgMTVR_/view?usp=sharing). Este notebook tenemos que almacenarlo en el bucket que usa Cloud Dataproc, lo puedes encontrar entre los datos del cluster: ![](https://i.imgur.com/WpR8FEq.png) Una vez que tengas el archivo en tu Cloud Shell lo subes Cloud Storage con el siguiente commando, reemplaza $DP_STORAGE por el nombre del bucket de Dataproc: ``` gsutil -m cp spark-hfds.ipynb gs://$DP_STORAGE/notebooks/jupyter ``` Sabemos que el cluster tiene instalado Hadoop, Spark, entre otros, de hecho tenemos acceso a su interfaz gráfica al entrar a los detalles del cluster, en **Web Interfaces > Component gateway**. Haz click sobre el que dice **Jupyter**. ![](https://i.imgur.com/zQOXAFb.png) Te aparecerá algo como, dado que se el contenido de la carpeta notebooks/jupyter que está en Cloud Storage y tiene el notebook que acabas de subir: ![](https://i.imgur.com/d80Lixd.png) Haz click en el notebook dentro de GCS para abrirlo. ![](https://i.imgur.com/SDMPwqS.png) Luego haz click en **Cells > Run All**. Esto ejecutará todas las celdas del notebook. Explora como se van ejecutando cada etapa. El dataset analizado en este ejemplo es de la competencia KDD de 1999, que era sobre detección de intrusos y contiene datos de conexiones TCP que están tageadas como normales o ataques, que pueden ser DoS, acceso no autorizado, escaneo de puertos, entre otros. Más información del dataset en el siguiente [Link](http://kdd.ics.uci.edu/databases/kddcup99/task.html) En el video asociado a este tutorial explicaremos el contenido del notebook, el uso de HFDS y Spark SQL. #### Descoplar Computación y Almacenamiento Ahora modificaremos el notebook para que en vez de leer de HDFS (hdfs://) lo haga de Cloud Storage (gs://). Vamos primero a crear un bucket y almacenaremos ahí los datos, para eso usaremos Cloud Shell. ``` export PROJECT_ID=$(gcloud info --format='value(config.project)') gsutil mb gs://$PROJECT_ID ``` ``` wget https://archive.ics.uci.edu/ml/machine-learning-databases/kddcup99-mld/kddcup.data_10_percent.txt gsutil cp kddcup.data_10_percent.txt gs://$PROJECT_ID/ ``` De vuelta en Jupyter Notebook, haz una copia del archivo y nombralo como spark-cs (File > Make a Copy). El notebook que estabas ocupando antes spark-hdfs cierralo (File > Close and Halt). Regresa al otro notebook. Para borrar celdas en el notebook, selecciona la celda y haz click en cut que tiene el símbolo de las tijeras en el toolbar. Los comentarios iniciales y celdas [1] [2] y [3]. Para que el notebook comience en Reading Data. Luego reemplaza el contenido de la celda [4] con este código donde debes poner el nombre del bucket donde están los datos. ```python= from pyspark.sql import SparkSession, SQLContext, Row gcs_bucket='Nombre-De-Tu-Bucket' spark = SparkSession.builder.appName("kdd").getOrCreate() sc = spark.sparkContext data_file = "gs://"+gcs_bucket+"//kddcup.data_10_percent.txt" raw_rdd = sc.textFile(data_file).cache() raw_rdd.take(5) ``` Luego click en **Cell > Run All**, el resultado es el mismo anterior pero está desacoplado la computación del almacenamiento. ## Usando Dataproc con Jobs en Python Al cluster de Dataproc podemos enviar distintos trabajo que se ejecutan sobre el cluster creado. Transformaremos el código en el Jupyter notebook a Python y lo lanzaremos como un trabajo. Copia el notebook llamado spark-cs a otro que se llame spark-python (File > Make a Copy). Luego cierra el notebook spark-cs (File > Close and Halt). En el notebook spark-python haz click en la primera celda y agrega otra celda arriba (Insert > Insert Cell Above) Pega el siguiente código en esa celda para hacer los import necesarios y manejo de parámetros: ```python= %%writefile spark_analysis.py import matplotlib matplotlib.use('agg') import argparse parser = argparse.ArgumentParser() parser.add_argument("--bucket", help="bucket for input and output") args = parser.parse_args() BUCKET = args.bucket ``` Ahora, al comienzo de cada una de las otras celdas del notebook agrega: ```python= %%writefile -a spark_analysis.py ```` En la última celda, borra %matplotlib inline, ya que no graficaremos así. Agrega una celda bajo la última celda del notebook (Insert > Insert Cell Below), y poen el siguiente código: ```python= %%writefile -a spark_analysis.py ax[0].get_figure().savefig('report.png'); ``` Agrega una celda más con el siguiente código, ojo que está dos veces el nombre del cluster, que se debe ajustar si es que no usaron el mismo: ```python= %%writefile -a spark_analysis.py import google.cloud.storage as gcs bucket = gcs.Client().get_bucket(BUCKET) for blob in bucket.list_blobs(prefix='midataproccluster/'): blob.delete() bucket.blob('midataproccluster/report.png').upload_from_filename('report.png') ``` En una nueva celda al final del notebook pon el siguiente código, nuevamente ojo con el nombre del cluster en la última línea: ```python= %%writefile -a spark_analysis.py connections_by_protocol.write.format("csv").mode("overwrite").save( "gs://{}/midataproccluster/connections_by_protocol".format(BUCKET)) ``` En una nueva celda al final del documento agrega lo siguiente: ```python= BUCKET_list = !gcloud info --format='value(config.project)' BUCKET=BUCKET_list[0] print('Writing to {}'.format(BUCKET)) !/opt/conda/miniconda3/bin/python spark_analysis.py --bucket=$BUCKET ``` En una nueva celda agrega ```python= !gsutil ls gs://$BUCKET/midataproccluster/** ``` En una nueva celda agrega ```python= !gsutil cp spark_analysis.py gs://$BUCKET/midataproccluster/spark_analysis.py ``` Haz click en **Cell** y **Run All** para correr todas las celdas del notebook. Ahora vamos a correr esto como un trabajo en Cloud Dataproc, para eso vamos al Cloud Shell y copiamos el script the pyhton de Cloud Storage: ```` gsutil cp gs://$PROJECT_ID/midataproccluster/spark_analysis.py spark_analysis.py ```` Lanza el trabajo con el siguiente comando, este es el correcto, en el Video falta un doble guión: ``` gcloud dataproc jobs submit pyspark \ --cluster midataproccluster \ --region us-central1 \ spark_analysis.py \ -- --bucket=$PROJECT_ID ``` Puedes ver el trabajo ejecutándose en la consola en **Jobs**, haz click en el nombre y mira el progreso del trabajo: ![](https://i.imgur.com/LonzUr6.png) Cuando haya terminado, puedes ver el resultado en el bucket de Cloud Storage, abriendo el archivo midataproccluster/report.png. **RECUERDA BORAR EL CLUSTER DE DATAPROC CREADO y el bucket con los datos en cloud Storage** ``` gcloud dataproc clusters delete [DATAPROC_CLUSTER_NAME] ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully