使用CortexAPI 实现Cortex的基本操作

简介: 在第一次接触这个 Cortex 的时候,必须承认,笔者在网上能找到的资料甚少,逼着笔者一点一点的看官网,真的是受不了了。这里,笔者重点讲一下,官网API中的笔者遇到的一些坑,以及我们去使用这些API。 目前笔者在网上找到的资料基本都是介绍 Cortex 和 Prometheus 的多租户,要么是讲原理,而且原理还是官网上的,我看得懂官网的要看翻译干啥。所以这里简单的去介绍下Cortex 里面几个API。

官网上的 API 介绍

在官网上,提供了一下几种 API Remote API / Alerts & Rules API / Configs API / Endpoints / Manage Rules . 这里呢,我只说这里的 RemoteAPI .

我们先看一下这个 Remote API :
12.png

写的很详细,目前是算比较详细的,笔者在一开始看的时候就几行,第一行:支持Prometheus 的 remote_read / remote_write , 第二行 , 对于Http post 里面的请求体首先是 Protocol Buffers , 再来一个 snappy . 第三行是 远程读写 api . 目前来看是又修改了下。而且我们也能看到,当前的这个 Cortex 的APIS 正在编写中。

Remote API

这里的 remote api 官网讲了两个,这两个对应着的是 Prometheus 中的 remote_write / remote_read . 这里对这两个做个简单的介绍,笔者这里也主要用到了的 remote_write .

remote_write

刚刚说了,这里的 remote_write 对应着的是 Prometheus 里面的那个 remote_write .所以呢,我们现在需要到 Prometheus 里面看看这个remote_write 的基本配置是什么样的。

我们进入到Prometheus 的官网,去看一下。 我这里不贴全部的,全部的大家去官网查看就好:

# 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> ]

这里的配置,写的很清楚,这里笔者用到的主要是两个配置,一个是 url , 一个是 basic_auth ,大家可以参考我之前的一个文章使用Cortex实现Prometheus的多租户管理 . 很简单的一个remote_write 。

隐藏的 API

如果你以为,我这就完了,那你就错了。我这里讲的是 Cortex 里面的查询的 APIs , 这里的几个API 目前官网我还没看到,也可能是因为我没找到吧。

这里呢,没必要去跟大家介绍每一个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
}

可以看到,在这个 Client 里面,有几个client , alertmanagerClient / httpClient / querierClient . 先不要好奇为什么会有这么多的 client . 这里的每一个 client 对应着的都不一样。这里会涉及到Cortex 的微服务的架构问题,这个我们后期再说。我这里先说怎么使用 API 做查询。 以及我们的 Push 。

Query

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
}

我们先得到一个 client , 这里的 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
}

这样就好了。

Push

这里的 Push ,就是发送数据到 Cortex 里面的。Client 用我们之前拿到的那个 Client

// 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
}

其实就是一个客户端在往服务器里面写数据的过程。

总结

当然了,上面的程序都是有的。大家可以到 cortex 的源程序里面找到 , github 的速度很慢。

大家可以克隆到自己本地:

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

在里面我们可以找到这个 Cortex 的几个隐藏的 API。

相关文章
|
SQL 存储 关系型数据库
PostgreSQL 流复制搭建主从环境,同步和异步的解释,压力测试,主从角色切换|学习笔记
快速学习PostgreSQL 流复制搭建主从环境,同步和异步的解释,压力测试,主从角色切换
PostgreSQL 流复制搭建主从环境,同步和异步的解释,压力测试,主从角色切换|学习笔记
|
6月前
|
XML 人工智能 自然语言处理
真是太牛逼啦,报告自动生成,这个操作Word的MCP插件绝啦,搞定Word 的一切排版~~~
一款开源的Word文档MCP Server,基于Python开发,通过自然语言指令让AI(如Claude)自动生成和编辑.docx文件。支持标题、列表、表格、图片等结构化排版,一键完成内容与格式调整,特别适合撰写报告、PRD、周报等需高频交付文档的场景。无需懂Word底层技术,告别手动排版烦恼,提升写作效率。项目已开源,开发者、产品、运营等均可受益。
1670 0
|
6月前
|
人工智能 自然语言处理 数据可视化
Google Code Wiki:GitHub代码库秒变可交互文档
Google Code Wiki 利用 AI 为代码库构建动态知识层,通过 Tree-sitter 解析结构、生成知识图谱,并结合混合检索策略实现精准问答。支持自动文档生成、可视化图表与自然语言交互,让代码可读、可问、可演进,大幅提升理解效率。
844 6
Google Code Wiki:GitHub代码库秒变可交互文档
|
5月前
|
Web App开发 人工智能 运维
3分钟让Chrome变聪明!Google AI保姆级激活教程!
本文手把手教你开启Chrome内置Gemini AI功能:自动网页总结、智能填表、购物比价、图片修改等。无需编程基础,提供“快捷方式”和“脚本激活”两种方法,适配美区账号+英文语言设置,5分钟即可让Chrome拥有AI大脑!
4391 9
|
运维 Prometheus 监控
可观测告警运维系统调研——SLS告警与多款方案对比
本文介绍对比多款告警监控运维平台方案,覆盖阿里云SLS、Azure、AWS、自建系统(ELK、Prometheus、TICK)等方案。
5574 0
可观测告警运维系统调研——SLS告警与多款方案对比
|
SQL 存储 自然语言处理
|
存储 人工智能 运维
云监控 2.0:全栈智能可观测平台
云监控2.0是由阿里云智能集团资深产品专家司徒放分享的全栈智能可观测平台。该平台旨在解决传统监控系统的割裂问题,通过统一接入、存储和观测模型,实现基础设施、应用及用户体验的全面可观测。云监控2.0引入了智能体和大模型技术,支持全局搜索、问题排查和根因定位,大幅提升运维效率。未来将扩展更多智能洞察场景,并开放API供客户定制使用。
975 7
|
SQL 存储 数据库
零距离接触阿里云时序时空数据库TSDB
最近,Amazon新推出了完全托管的时间序列数据库Timestream,可见,各大厂商对未来时间序列数据库的重视与日俱增。阿里云TSDB是阿里巴巴集团数据库事业部研发的一款高性能分布式时序时空数据库(面向智联网领域),在即将过去的2018年,我们对TSDB进行了多次的系统架构改进,引入了倒排索引、无限时间线支持、时序数据高压缩比算法、内存缓存、数据预处理、分布式并行聚合、GPU加速等多项核心技术,并且引入了新的计算引擎层和分布式SQL层,使得引擎核心能力有了质的提升,也基本上统一了集团内部的监控存储业务。
13162 0
|
存储 监控 数据处理
不断突破极致:SPL新版数据加工能力焕新登场
SPL 算子不仅完成了旧版 DSL 加工向更强大语法和算子形式的过渡,更将性能调优和场景适配做到了极致,解锁了时序预测和日志分析的更多可能性。作为重要的基础设施模块,SPL 加工能力将持续优化演进。未来的规划将继续聚焦通用性、性能与产品能力,为用户提供更加强大、灵活的技术支持。
|
数据采集 SQL 数据处理
当实时消费遇到 SPL:让数据处理更高效、简单
SLS 对实时消费进行了功能升级,推出了 基于 SPL 的规则消费功能。在实时消费过程中,用户只需通过简单的 SPL 配置即可完成服务端的数据清洗和预处理操作。通过SPL消费可以将客户端复杂的业务逻辑“左移”到服务端,从而大幅降低了客户端的复杂性和计算开销。
646 56