皮質はCortexAPIの基本的な操作を使用して実装しました

この皮質との最初の接触は、私は非常に少ない、インターネット上で見つけることができる情報は、私は少し教えて強制することを認めなければならない場合にはどのようなネットワーク、実際にそれを我慢できません。ここでは、私はAPIの公式ウェブサイトに遭遇したピットのいくつかについての話に焦点を当てる、と我々はこれらのAPIを使用しようとしています。現在、私は、インターネット上の情報は基本的にマルチテナントのCortexとプロメテウスを紹介し、いずれかの原則について話しますが、原理は、公式ウェブサイトのまま、私は翻訳をしているを見て、公式サイトを理解することができました。そこでここでは、単にいくつかのAPI内のCortexを導入します。

APIは、公式サイトを紹介します

公式サイト、リモートAPI /アラート&ルールはAPI / ConfigsにAPI /エンドポイント/ルールを管理するには、以下のいくつかのAPIを提供します。ここでは、私はちょうどここRemoteAPIを言います。

私たちは、リモートAPIを見て:

12.png

、remote_readのプロメテウスのサポート/ remote_write、リクエストボディのHttpための第二行はまずプロトコルバッファ内の投稿:非常に詳細に書かれて、今より詳細に検討され、私は彼が最初の行が数行を見て始めましたもう一つてきぱき。第三のラインは、リモートリーダーAPIである。今、次を編集します。そして、我々はまた、準備中APISの皮質の現在のことがわかります。

リモートAPI

ここでプロメテウスのremote_write / remote_readのように、2つの2に相当程度のリモートAPI公式サイトだ。ここでは、これら二つは簡単な紹介を行い、ここで著者は、主にremote_writeを使用しています。

remote_write

ただ、remote_writeここで、言うプロメテウスremote_write。だから、私たちは今remote_write何であるプロメテウスの基本的な構成を見る必要があるの内側に対応しています。

私たちは、プロメテウスの公式ウェブサイトに入力し、見てみましょう。私は、すべて、ここに掲載されていない、あなたのすべては次のようにビューに公式サイトにアクセスしてください:

# The URL of the endpoint to send samples to.
url: <string>

# Timeout for requests to the remote write endpoint.
[ remote_timeout: <duration> | default = 30s ]

# List of remote write relabel configurations.
write_relabel_configs:
  [ - <relabel_config> ... ]

# Sets the `Authorization` header on every remote write request with the
# configured username and password.
# password and password_file are mutually exclusive.
basic_auth:
  [ username: <string> ]
  [ password: <string> ]
  [ password_file: <string> ]

# Sets the `Authorization` header on every remote write request with
# the configured bearer token. It is mutually exclusive with `bearer_token_file`.
[ bearer_token: <string> ]

# Sets the `Authorization` header on every remote write request with the bearer token
# read from the configured file. It is mutually exclusive with `bearer_token`.
[ bearer_token_file: /path/to/bearer/token/file ]

# Configures the remote write request's TLS settings.
tls_config:
  [ <tls_config> ]

# Optional proxy URL.
[ proxy_url: <string> ]

著者たちは、私が以前の記事を参照することができ、主に二つの構成、1つのURL、1 BASIC_AUTH、使用ここでは、非常に明確に書かれた、ここで設定プロメテウスの皮質マルチテナント管理を使用する。A非常に単純なremote_write 。

隠されたAPI

あなたが思うなら、私はあなたが間違っている、終了することがあります。私はここで、私はそれを見つけられませんでしたので、それがあってよく、ここでは現在、私は公式サイトを見ていないいくつかのAPIがあります、クエリ内のAPIのCortexについて話しています。

ここでは、各APIについてあなたに話をする必要はありません。私たちは、APIインタフェースを見てすることは明らかです。

// API provides bindings for Prometheus's v1 API.
type API interface {
    // Alerts returns a list of all active alerts.
    Alerts(ctx context.Context) (AlertsResult, error)
    // AlertManagers returns an overview of the current state of the Prometheus alert manager discovery.
    AlertManagers(ctx context.Context) (AlertManagersResult, error)
    // CleanTombstones removes the deleted data from disk and cleans up the existing tombstones.
    CleanTombstones(ctx context.Context) error
    // Config returns the current Prometheus configuration.
    Config(ctx context.Context) (ConfigResult, error)
    // DeleteSeries deletes data for a selection of series in a time range.
    DeleteSeries(ctx context.Context, matches []string, startTime time.Time, endTime time.Time) error
    // Flags returns the flag values that Prometheus was launched with.
    Flags(ctx context.Context) (FlagsResult, error)
    // LabelNames returns all the unique label names present in the block in sorted order.
    LabelNames(ctx context.Context) ([]string, api.Warnings, error)
    // LabelValues performs a query for the values of the given label.
    LabelValues(ctx context.Context, label string) (model.LabelValues, api.Warnings, error)
    // Query performs a query for the given time.
    Query(ctx context.Context, query string, ts time.Time) (model.Value, api.Warnings, error)
    // QueryRange performs a query for the given range.
    QueryRange(ctx context.Context, query string, r Range) (model.Value, api.Warnings, error)
    // Series finds series by label matchers.
    Series(ctx context.Context, matches []string, startTime time.Time, endTime time.Time) ([]model.LabelSet, api.Warnings, error)
    // Snapshot creates a snapshot of all current data into snapshots/<datetime>-<rand>
    // under the TSDB's data directory and returns the directory as response.
    Snapshot(ctx context.Context, skipHead bool) (SnapshotResult, error)
    // Rules returns a list of alerting and recording rules that are currently loaded.
    Rules(ctx context.Context) (RulesResult, error)
    // Targets returns an overview of the current state of the Prometheus target discovery.
    Targets(ctx context.Context) (TargetsResult, error)
    // TargetsMetadata returns metadata about metrics currently scraped by the target.
    TargetsMetadata(ctx context.Context, matchTarget string, metric string, limit string) ([]MetricMetadata, error)
}

これはちょうど良い理解ではありませんか?

我々が使用するときは、最初の構造を知っておく必要があります。

type Client struct {
    alertmanagerClient promapi.Client
    distributorAddress string
    timeout            time.Duration
    httpClient         *http.Client
    querierClient      promv1.API
    orgID              string
}

いくつかのクライアントは、alertmanagerClient / HttpClientを/ querierClientがあり、そこにこのクライアントで見ることができます。クライアントのなぜこれほど多くの疑問しないでください。各クライアントを、ここで対応は同じではありません。ここではそれは我々が遅れていると言う、マイクロアーキテクチャの問題のCortexサービスを伴います。私はお問い合わせをするためにAPIを使用する方法を言うためにここにいます。そして、私たちのプッシュ。

質問

func NewClient(distributorAddress string, querierAddress string, alertmanagerAddress string, orgID string) (*Client, error) {
    // Create querier API client
    querierAPIClient, err := promapi.NewClient(promapi.Config{
        Address:      "http://" + querierAddress + "/api/prom",
        RoundTripper: &addOrgIDRoundTripper{orgID: orgID, next: http.DefaultTransport},
    })
    if err != nil {
        return nil, err
    }

    c := &Client{
        distributorAddress: distributorAddress,
        timeout:            5 * time.Second,
        httpClient:         &http.Client{},
        querierClient:      promv1.NewAPI(querierAPIClient),
        orgID:              orgID,
    }
    return c, nil
}

私たちは、最初のクライアントを取得し、promv1はここでパッケージ「github.com/prometheus/client_golang/api/prometheus/v1」です。

// Query runs a query
func (c *Client) Query(query string, ts time.Time) (model.Value, error) {
    value, _, err := c.querierClient.Query(context.Background(), query, ts)
    return value, err
}

それがすべてです。

押す

ここで押し、データは内部のCortexへ送信されます。我々が得る前とクライアントクライアント

// Push the input timeseries to the remote endpoint
func (c *Client) Push(timeseries []prompb.TimeSeries) (*http.Response, error) {
    // Create write request
    data, err := proto.Marshal(&prompb.WriteRequest{Timeseries: timeseries})
    if err != nil {
        return nil, err
    }

    // Create HTTP request
    compressed := snappy.Encode(nil, data)
    req, err := http.NewRequest("POST", fmt.Sprintf("http://%s/api/prom/push", c.distributorAddress), bytes.NewReader(compressed))
    if err != nil {
        return nil, err
    }

    req.Header.Add("Content-Encoding", "snappy")
    req.Header.Set("Content-Type", "application/x-protobuf")
    req.Header.Set("X-Prometheus-Remote-Write-Version", "0.1.0")
    req.Header.Set("X-Scope-OrgID", c.orgID)

    ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
    defer cancel()

    // Execute HTTP request
    res, err := c.httpClient.Do(req.WithContext(ctx))
    if err != nil {
        return nil, err
    }

    defer res.Body.Close()
    return res, nil
}

実際には、プロセスデータへのクライアント・サーバは、内部に書かれました。

概要

もちろん、上記の手順があります。私たちは、元の皮質内で見つけることができ、githubのが遅い、あなたが見るためにこの場所に行くことができ皮質を

あなたは、ローカルに自分自身を複製することができます。

git clone https://gitee.com/sun-iot/cortex.git

我々はいくつかの隠された皮質のAPIを見つけることができます内部。

おすすめ

転載: www.cnblogs.com/sun-iot/p/12409485.html