下載設定檔資料

本文說明如何將設定檔資料下載至本機系統,以及如何透過程式輔助方式,使用 Go 應用程式擷取設定檔資料。

使用 Google Cloud 控制台下載設定檔

如要下載火焰圖中顯示的設定檔,請按一下「下載」圖示

Profiler 會為下載的檔案使用下列命名慣例:

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

在這個運算式中:

  • SERVICE_NAME 包含您選取的「Service」(服務)
  • PROFILE_TYPE 包含您的「Profile type」(剖析類型) 選取項目
  • FROM_DATETO_DATE 包含您的時間範圍規格
  • ZONE 包含您的「Zone」(區域) 選取項目
  • VERSION 包含您的「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: %w", 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: %w", 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 工具。