プロファイル データをダウンロードする

このドキュメントでは、ローカル システムにプロファイル データをダウンロードする方法と、Go アプリケーションを使用してプログラムでプロファイル データを取得する方法について説明します。

Google Cloud コンソールを使用してプロファイルをダウンロードする

フレームグラフに表示されているプロファイルをダウンロードするには、[ダウンロード] をクリックします。

Profiler では、ダウンロードしたファイルに次の命名規則が適用されます。

profiler_[SERVICE_NAME]_[PROFILE_TYPE]_[FROM_DATE]_[TO_DATE]_[ZONE]_[VERSION].pb.gz

以下に例を示します。

  • SERVICE_NAME は、[サービス] で選択した名前です。
  • PROFILE_TYPE は、[プロファイルの種類] で選択した種類です。
  • FROM_DATETO_DATE は、期間の設定で指定した期間です。
  • ZONE は、[ゾーン] で選択したゾーンです。
  • VERSION は、[バージョン] で選択したバージョンです。

例: profiler_docdemo-service_HEAP_2018-04-22T20_25_31Z_2018-05-22T20_25_31Z_us-east1-c.pb.gz

プログラムでプロファイルをダウンロードする

プロファイル データを取得するには、ListProfiles API メソッドを使用します。次のサンプル Go プログラムは、この API の使用方法を示しています。

サンプル プログラムでは、実行用のディレクトリにフォルダが作成され、番号が付いた pprof ファイルのセットが生成されます。各ファイルの命名規則は profile000042.pb.gz のようになります。各ディレクトリにはプロファイル データとメタデータ ファイル metadata.csv が含まれています。このファイルには、ダウンロードしたファイルに関する情報が含まれています。


// Sample export shows how ListProfiles API can be used to download
// existing pprof profiles for a given project from GCP.
package main

import (
	"bytes"
	"context"
	"encoding/csv"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	cloudprofiler "cloud.google.com/go/cloudprofiler/apiv2"
	pb "cloud.google.com/go/cloudprofiler/apiv2/cloudprofilerpb"
	"google.golang.org/api/iterator"
)

var project = flag.String("project", "", "GCP project ID from which profiles should be fetched")
var pageSize = flag.Int("page_size", 100, "Number of profiles fetched per page. Maximum 1000.")
var pageToken = flag.String("page_token", "", "PageToken from a previous ListProfiles call. If empty, the listing will start from the begnning. Invalid page tokens result in error.")
var maxProfiles = flag.Int("max_profiles", 1000, "Maximum number of profiles to fetch across all pages. If this is <= 0, will fetch all available profiles")

const ProfilesDownloadedSuccessfully = "Read max allowed profiles"

// This function reads profiles for a given project and stores them into locally created files.
// The profile metadata gets stored into a 'metdata.csv' file, while the individual pprof files
// are created per profile.
func downloadProfiles(ctx context.Context, w io.Writer, project, pageToken string, pageSize, maxProfiles int) error {
	client, err := cloudprofiler.NewExportClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()
	log.Printf("Attempting to fetch %v profiles with a pageSize of %v for %v\n", maxProfiles, pageSize, project)

	// Initial request for the ListProfiles API
	request := &pb.ListProfilesRequest{
		Parent:    fmt.Sprintf("projects/%s", project),
		PageSize:  int32(pageSize),
		PageToken: pageToken,
	}

	// create a folder for storing profiles & metadata
	profilesDirName := fmt.Sprintf("profiles_%v", time.Now().Unix())
	if err := os.Mkdir(profilesDirName, 0750); err != nil {
		log.Fatal(err)
	}
	// create a file for storing profile metadata
	metadata, err := os.Create(fmt.Sprintf("%s/metadata.csv", profilesDirName))
	if err != nil {
		return err
	}
	defer metadata.Close()

	writer := csv.NewWriter(metadata)
	defer writer.Flush()

	writer.Write([]string{"File", "Name", "ProfileType", "Target", "Duration", "Labels"})

	profileCount := 0
	// Keep calling ListProfiles API till all profile pages are fetched or max pages reached
	profilesIterator := client.ListProfiles(ctx, request)
	for {
		// Read individual profile - the client will automatically make API calls to fetch next pages
		profile, err := profilesIterator.Next()

		if err == iterator.Done {
			log.Println("Read all available profiles")
			break
		}
		if err != nil {
			return fmt.Errorf("error reading profile from response: %v", err)
		}
		profileCount++

		filename := fmt.Sprintf("%s/profile%06d.pb.gz", profilesDirName, profileCount)
		err = os.WriteFile(filename, profile.ProfileBytes, 0640)

		if err != nil {
			return fmt.Errorf("unable to write file %s: %v", filename, err)
		}
		fmt.Fprintf(w, "deployment target: %v\n", profile.Deployment.Labels)

		labelBytes, err := json.Marshal(profile.Labels)
		if err != nil {
			return err
		}

		err = writer.Write([]string{filename, profile.Name, profile.Deployment.Target, profile.Duration.String(), string(labelBytes)})
		if err != nil {
			return err
		}

		if maxProfiles > 0 && profileCount >= maxProfiles {
			fmt.Fprintf(w, "result: %v", ProfilesDownloadedSuccessfully)
			break
		}

		if profilesIterator.PageInfo().Remaining() == 0 {
			// This signifies that the client will make a new API call internally
			log.Printf("next page token: %v\n", profilesIterator.PageInfo().Token)
		}
	}
	return nil
}

func main() {
	flag.Parse()
	// validate project ID
	if *project == "" {
		log.Fatalf("No project ID provided, please provide the GCP project ID via '-project' flag")
	}
	var writer bytes.Buffer
	if err := downloadProfiles(context.Background(), &writer, *project, *pageToken, *pageSize, *maxProfiles); err != nil {
		log.Fatal(err)
	}
	log.Println("Finished reading all profiles")
}

サンプル プログラムは次のコマンドライン引数を受け入れます。

  • project: プロファイルを取得するプロジェクト。必須。
  • page_size: API 呼び出しごとに取得されるプロファイルの最大数。page_size の最大値は 1000 です。指定しない場合、このフィールドは 100 に設定されます。
  • page_token: プログラムの前回の実行によって生成され、ダウンロードを再開する文字列トークン。省略可。
  • max_profiles: 取得するプロファイルの最大数。正でない整数が指定されている場合、プログラムはすべてのプロファイルを取得しようとします。
    省略可。

サンプル アプリケーションを実行する

サンプルアプリケーションを実行するには、次の手順を行います。

  1. リポジトリのクローンを作成します。

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git
    
  2. サンプルプログラムが含まれているディレクトリに移動します。

    cd golang-samples/profiler/export
    
  3. YOUR_GCP_PROJECT を Google Cloud プロジェクトの ID に置き換えてから、プログラムを実行します。

    go run main.go -project YOUR_GCP_PROJECT -page_size 1000 -max_profiles 10000
    

プログラムが完了するまでにかなりの時間がかかることがあります。現在のページを取得した後、次のページのトークンを出力します。プログラムが中断された場合、このトークンを使用してプロセスを再開できます。

ダウンロードしたプロファイルを表示する

シリアル化されたプロトコル バッファ形式で書き込まれたダウンロード ファイルを読み取るには、オープンソースの pprof ツールを使用します。