שימוש ב-Cloud Storage בפעם הראשונה

מערכת Google Display & Video 360 שומרת באופן אוטומטי קובצי קריאה של ישויות ב-Google Cloud Storage. הקבצים האלה נגישים רק לחשבונות שקיבלו גישה.

יוצרים פרויקט

יוצרים פרויקט ומגדירים אותו באופן הבא:

  1. עוברים אל דף ממשקי ה-API שמופעלים על ידי Google API Console.

    אם עוד לא נכנסת ל-Google, תתבקש להיכנס.

  2. בתפריט הנפתח של הפרויקט, בוחרים פרויקט קיים או יוצרים פרויקט חדש.
    • אם יש לכם כמה פרויקטים, חשוב לבחור את הפרויקט שעבורו אתם רוצים להפעיל את Google Cloud Storage ולבחור באפשרות Continue (המשך).
    • אם אין לכם פרויקט, בוחרים באפשרות Create a new project (יצירת פרויקט חדש), מזינים את שם הפרויקט ובוחרים באפשרות Create (יצירה).

      הערה: חשוב לזכור שחלק ממזהי המשאבים (כמו מזהי פרויקט) יישמרו גם כשהפרויקט יסתיים. לכן כדאי להימנע מאחסון מידע רגיש במזהי המשאבים.

  3. ברשימת ממשקי ה-API המופעלים, מוודאים שהרכיב של Google Cloud Storage מופיע. אם הוא לא מופיע, לוחצים על הכרטיסייה Google APIs, מחפשים את הרכיב Google Cloud Storage, בוחרים אותו ולוחצים על Enable API.

    שימו לב: ברוב הפרויקטים, הרכיב של Google Cloud Storage כבר מופעל. אם אתם מתכוונים לגשת ל-Google Cloud Storage באמצעות JSON API, עליכם גם לוודא ש-Google Cloud Storage JSON API מופעל.

  4. מפעילים את החיוב בפרויקט.

    אם עדיין לא עשיתם זאת, לפני שתוכלו להשתמש ב-Google Cloud Storage, תצטרכו להפעיל את החיוב בפרויקט. הפעלת החיוב לא בהכרח כרוכה בחיוב. מידע נוסף זמין במאמר תמחור.

    1. עדיין בתוך הפרויקט של האחסון בענן, לוחצים על תפריט הגלריה בפינה הימנית העליונה ובוחרים באפשרות חיוב.
    2. אם עדיין אין לכם חשבון לחיוב, צריך לפעול לפי ההוראות ליצירת חשבון חדש לחיוב.
    3. אם יש לכם חשבון קיים לחיוב, בוחרים אותו ואז בוחרים באפשרות Set account.

ב-Google API Console, נשארים באותו פרויקט ועוברים לקטע הבא.

הגדרת הגישה ל-Cloud Storage

  1. מתוך Google API Console בתוך הפרויקט הנדרש, לוחצים על תפריט הגלריה בפינה הימנית העליונה, בוחרים APIs & Services ואז לוחצים על Credentials. בדף Credentials, מחפשים Service account Keys.

    מוצאים את כתובת האימייל של מפתח חשבון השירות:

    1. בוחרים את הקישור Manage Service Accounts (ניהול חשבונות שירות) (מימין לקטע 'מפתחות של חשבונות שירות').
    2. ניתן לצפות בכתובת האימייל בדף הרשאות שמתקבל.

    אם אין מפתחות של חשבונות שירות, יוצרים חשבון שירות חדש:

    1. בתפריט הנפתח, לוחצים על Create credentials ואז על Service account key.
    2. בתפריט הנפתח Service account, בוחרים באפשרות New service Account (חשבון שירות חדש).
    3. נותנים שם לחשבון השירות. Service account ID נוצר באופן אוטומטי מהשם ומשם הפרויקט.
    4. רושמים לעצמכם את כתובת האימייל של מספר חשבון השירות gserviceaccount.com. הוא לא מוצג בדף פרטי הכניסה אחרי שבוחרים באפשרות יצירה.
    5. בקטע סוג מפתח, בוחרים באפשרות JSON.
    6. לוחצים על Create. קובץ ה-JSON עם זוג המפתחות הציבורי/הפרטי של החשבון יישמר בתיקייה 'הורדות'. המפתח הזה משמש לאימות האפליקציה ב-API ולחתימה על כל הבקשות שהיא שולחת ל-API. מאחסנים את קובץ ה-JSON שנוצר במקום בטוח, במקום שבו לאפליקציה תהיה גישה אליו.
  2. צריך לפנות לצוות התמיכה של Display & Video 360 כדי לבקש הפעלה של קובצי קריאה של ישויות ו/או של Google Bid Manager API.

    אחרי שצוות התמיכה יאשר את הגישה, צריך ליצור קבוצה ייעודית ב-Google (או קבוצות) ולעדכן את השדות הבאים בפרטי השותפים ב-Display & Video 360 (חשוב לשים לב שרק משתמשים עם גישה ברמת השותף יוכלו לבצע את העדכונים האלה):

    • רישום של קבוצת Google לקריאה בלבד
      לקבוצה עם הרשאת קריאה בלבד יש הרשאה רק לקרוא קבצים ולהציג את התוכן של קטגוריות האחסון.
    • קבוצת Google לניהול יומנים
      לקבוצת הניהול יש את כל ההרשאות של הקבוצה לקריאה בלבד, אבל היא יכולה גם לשנות את רשימות ה-ACL של הקבצים שבתוך הקטגוריות. שימו לב שאפילו לקבוצת הניהול אין הרשאה לשנות רשימות ACL של קטגוריות, וגם אין לה הרשאה ליצור, לשנות או למחוק קבצים.

    אחרי הוספת קבוצת Google, אפשר להוסיף משתמשים לקבוצת Google ולהסיר ממנה משתמשים לפי הצורך, ללא מעורבות נוספת של צוות התמיכה של Display & Video 360. רק למשתמשים שנכללים בקבוצה תהיה גישה לנתונים.

גישה לנתונים

גישה לנתונים באמצעות gsutil

הכלי gsutil הוא אפליקציית שורת פקודה שמאפשרת לגשת בקלות לנתוני Google Cloud Storage ללא צורך בניסיון בתכנות. לדוגמה, ניתן להשתמש ב-gsutil כחלק מסקריפט או מקובץ אצווה במקום ליצור אפליקציות מותאמות אישית.

כדי להתחיל להשתמש ב-gsutil, קרא את התיעוד של gsutil. עדיין יהיה עליך לאמת באמצעות OAuth 2 כמו קודם, אבל gsutil עצמו יבקש ממך את פרטי הכניסה בפעם הראשונה שתשתמש בהם, ואז יאחסן אותם לשימוש בהמשך.

גישה פרוגרמטית לנתונים

ב-Google Cloud Storage יש ממשקי API למגוון שפות תכנות שמאפשרים לגשת לנתונים בצורה פרוגרמטית. הדוגמה הבאה מראה איך להוריד בקלות את אחד מהקבצים שנקראו על ידי ישויות מ-Google Cloud Storage. חשוב לזכור שרק קבצים של קריאה לישויות שגלויים לכולם מאוחסנים בקטגוריה gdbm-public. הקבצים הפרטיים שלכם לקריאה של ישויות יישמרו בקטגוריות שספציפיות לשותף ולמפרסם.

Java

בדוגמה הבאה נשתמש בספריית הלקוח של Google APIs עבור Java, שמאפשרת לגשת בקלות לנתונים שמאוחסנים ב-Google Cloud Storage. בנוסף לספריית הלקוח הכללית הראשית של Google APIs, תצטרכו גם להוריד את הספרייה הנפרדת של Cloud Storage API.

כדי לקבל הרשאה לגשת לנתונים שלך, קודם צריך להגדיר את פרטי הכניסה לשימוש בתקשורת עם ה-API. כדי לעשות זאת, יוצרים אובייקט Credential שמשתמש בכתובת האימייל developer.gserviceaccount.com של חשבון השירות בתור ServiceAccountId, וגם טוען את קובץ המפתח הפרטי שהורדת מ-Google API Console כשיצרת את חשבון השירות. הפעולה הזו תבטיח שכל הבקשות העתידיות ל-API ייחתמו באמצעות המפתח הפרטי של חשבון השירות:

NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();
JacksonFactory JSON_FACTORY = new JacksonFactory();

...

Credential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
   .setJsonFactory(JSON_FACTORY)
   .setServiceAccountId("...@developer.gserviceaccount.com")
   .setServiceAccountScopes(StorageScopes.DEVSTORAGE_READ_ONLY)
   .setServiceAccountPrivateKeyFromP12File(new File("...-privatekey.p12"))
   .build();

אחרי שיוצרים את האובייקט Credential, אפשר להשתמש בו כדי ליצור אובייקט Storage חדש שישמש בכל הבקשות העתידיות ל-Google Cloud Storage API:

Storage storage = new Storage(HTTP_TRANSPORT, JSON_FACTORY, credential);

עכשיו יש לך אובייקט Storage חדש, ועכשיו אפשר להתחיל לשלוח בקשות ל-API. זוהי בקשה לאחזר פריט ספציפי bucketObjectName מהקטגוריה bucket. הספרייה מטפלת בהורדת הקובץ ב-HTTP מ-Google Cloud Storage, ואז אפשר פשוט להדפיס את התוכן במסוף:

Get bucketObject = storage.objects().get(bucketName, bucketObjectName);

ByteArrayOutputStream output = new ByteArrayOutputStream();
bucketObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
bucketObject.executeAndDownloadTo(output);

System.out.println(output.toString());

הערכים של bucket ושל bucketObjectName ישתנו בהתאם לחלק ב-API שאליו נכנסת. יש לעיין בקטע המתאים בנושא מוסכמות מתן שמות.

C#

בדוגמה הבאה נשתמש בספריית הלקוח של Google APIs עבור .NET, שעוזרת לכם לגשת בקלות לנתונים שמאוחסנים ב-Google Cloud Storage.

כדי לקבל הרשאה לגשת לנתונים שלכם, קודם צריך להגדיר את פרטי הכניסה לשימוש בתקשורת עם ה-API. לשם כך, יוצרים אובייקט AssertionFlowClient שמשתמש בכתובת האימייל developer.gserviceaccount.com של חשבון השירות בתור ServiceAccountId, וגם טוען את קובץ המפתח הפרטי שהורד מ-Google API Console כשיצרת את חשבון השירות.

string keyPath = @"...-privatekey.p12";
X509Certificate2 certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
    ServiceAccountId = "...@developer.gserviceaccount.com",
    Scope = StorageService.Scopes.DevstorageRead_only.GetStringValue()
};

אחרי שיוצרים את האובייקט AssertionFlowClient, אפשר להשתמש בו כדי ליצור אובייקט OAuth2Authenticator חדש שבו אפשר ליצור מופע חדש של Storage לכל הבקשות העתידיות לממשק ה-API של Google Cloud Storage:

var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
StorageService service = new StorageService(auth);

עכשיו יש לכם אובייקט Storage חדש, ועכשיו אתם יכולים להתחיל לשלוח בקשות ל-API. זוהי בקשה לאחזור פריט ספציפי, bucketObjectName, מהקטגוריה bucket. אנחנו משתמשים במחלקות סטנדרטיות של ספריית לקוח .NET כדי לטפל בהורדת HTTP מ-Google Cloud Storage, אבל צריך לטפל באופן ידני במקרה שבו יש הפניה לכתובת אחרת, כדי לוודא שתמיד יש בבקשה את הכותרת Authorization הנכונה והנכונה:

var results = service.Objects.Get(bucketName, bucketObjectName).Fetch();

HttpWebRequest request = createRequest(results.Media.Link, auth);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

// Handle redirects manually to ensure that the Authorization header is present if
// your request is redirected.
if (response.StatusCode == HttpStatusCode.TemporaryRedirect)
{
    request = createRequest(response.Headers["Location"], auth);
    response = (HttpWebResponse)request.GetResponse();
}

לאחר מכן, אפשר יהיה לקרוא את תוכן התגובה מהאובייקט HttpWebResponse באמצעות GetResponseStream כרגיל. הערכים של bucket ושל bucketObjectName ישתנו בהתאם לחלק ב-API שאליו מתבצעת גישה. יש לעיין בקטע המתאים בנושא מוסכמות מתן שמות.

נספח: דגימות מלאות

Java

/*
 * Copyright (c) 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.bidmanager.api.samples;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStreamReader;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.Storage.Objects.Get;
import com.google.api.services.storage.StorageScopes;

/**
 * A simple class that demonstrates how to download a specific object from a bucket using a
 * service account
 */
public class ServiceDownload {

  /**
   * This is the HTTP Transport object used for automatically refreshing access tokens.
   */
  static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  /**
   * This is the JSON factory used for parsing refresh token responses.Your first requirement
   */
  static final JacksonFactory JSON_FACTORY = new JacksonFactory();

  /**
   * The main method will attempt to download a specific named object from the gdbm-public bucket
   * using a service account.
   *
   * @param args Not used.
   */
  public static void main(String[] args) {

    try {
      // Prompt the user for the details of the object to download.
      System.out.print("Name of object to download, e.g. entity/20130430.0.Browser.json:");
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      String bucketObjectName = in.readLine();
      in.close();
      String bucketName = "gdbm-public";

      Credential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
           .setJsonFactory(JSON_FACTORY)
           .setServiceAccountId("...@developer.gserviceaccount.com")
           .setServiceAccountScopes(StorageScopes.DEVSTORAGE_READ_ONLY)
           .setServiceAccountPrivateKeyFromP12File(
               new File("...-privatekey.p12"))
           .build();

      Storage storage = new Storage(HTTP_TRANSPORT, JSON_FACTORY, credential);

      Get bucketObject = storage.objects().get(bucketName, bucketObjectName);

      ByteArrayOutputStream output = new ByteArrayOutputStream();
      bucketObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
      bucketObject.executeAndDownloadTo(output);
      System.out.println(output.toString());

    } catch (Exception e) {
      System.err.println("Unexpected exception caught: " + e.getMessage());
      e.printStackTrace();
    }

  }


}

C#

/*
 * Copyright (c) 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;

using DotNetOpenAuth.OAuth2;

using Google.Apis;
using Google.Apis.Requests;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Storage.v1beta1;
using Google.Apis.Storage.v1beta1.Data;
using Google.Apis.Util;

namespace ApiSamples
{
    /// <summary>
    /// A simple class that demonstrates how to download a specific object from a bucket using a
    /// service account
    /// </summary>
    class ServiceDownload
    {
        /// <summary>
        /// The main method will attempt to download a specific named object from the
        /// gdbm-public bucket using a service account.
        /// </summary>
        /// <param name="args">Not used.</param>
        public static void Main(string[] args)
        {

            // Prompt the user for the details of the object to download
            Console.WriteLine("Name of object to download, e.g. entity/20130430.0.Browser.json:");
            string bucketObjectName = Console.ReadLine();
            string bucketName = "gdbm-public";

            try
            {
                string keyPath = @"...-privatekey.p12";
                X509Certificate2 certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable);
                var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
                {
                    ServiceAccountId = "...@developer.gserviceaccount.com",
                    Scope = StorageService.Scopes.DevstorageRead_only.GetStringValue()
                };
                var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);

                StorageService service = new StorageService(auth);
                var results = service.Objects.Get(bucketName, bucketObjectName).Fetch();

                HttpWebRequest request = createRequest(results.Media.Link, auth);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                // Handle redirects manully to ensure that the Authorization header is present if
                // our request is redirected.
                if (response.StatusCode == HttpStatusCode.TemporaryRedirect)
                {
                    request = createRequest(response.Headers["Location"], auth);
                    response = (HttpWebResponse)request.GetResponse();
                }

                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                String data = reader.ReadToEnd();
                Console.Write(data);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception caught: " + e.Message);
                Console.Write(e.StackTrace);
            }
            Console.ReadKey();
        }

        /// <summary>
        /// Generate a HttpWebRequest for the given URL with the appropriate OAuth2 authorization
        /// header applied.  The HttpWebRequest object returned has its AllowAutoRedirect option
        /// disabled to allow us to manually handle redirects.
        /// </summary>
        /// <param name="url">URL that is to be requested with this object</param>
        /// <param name="auth">The OAuth2Authenticator instance that contains the appropriate keys.</param>
        /// <returns>HttpWebRequest object ready to be used to make requests to the API</returns>
        private static HttpWebRequest createRequest(string url, OAuth2Authenticator<AssertionFlowClient> auth)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Authorization", "Bearer " + auth.State.AccessToken);
            request.AllowAutoRedirect = false;
            return request;
        }

    }
}