世界观察:【prometheus】-04 轻松搞定Prometheus Eureka服务发现

首页>资讯 > 正文
2023-03-24 08:04:35

来源:腾讯云

Prometheus服务发现机制之Eureka

概述

Eureka服务发现协议允许使用Eureka Rest API检索出Prometheus需要监控的targets,Prometheus会定时周期性的从Eureka调用Eureka Rest API,并将每个应用实例创建出一个target。

Eureka服务发现协议支持对如下元标签进行relabeling


(相关资料图)

__meta_eureka_app_name: the name of the app__meta_eureka_app_instance_id: the ID of the app instance__meta_eureka_app_instance_hostname: the hostname of the instance__meta_eureka_app_instance_homepage_url: the homepage url of the app instance__meta_eureka_app_instance_statuspage_url: the status page url of the app instance__meta_eureka_app_instance_healthcheck_url: the health check url of the app instance__meta_eureka_app_instance_ip_addr: the IP address of the app instance__meta_eureka_app_instance_vip_address: the VIP address of the app instance__meta_eureka_app_instance_secure_vip_address: the secure VIP address of the app instance__meta_eureka_app_instance_status: the status of the app instance__meta_eureka_app_instance_port: the port of the app instance__meta_eureka_app_instance_port_enabled: the port enabled of the app instance__meta_eureka_app_instance_secure_port: the secure port address of the app instance__meta_eureka_app_instance_secure_port_enabled: the secure port of the app instance__meta_eureka_app_instance_country_id: the country ID of the app instance__meta_eureka_app_instance_metadata_: app instance metadata__meta_eureka_app_instance_datacenterinfo_name: the datacenter name of the app instance__meta_eureka_app_instance_datacenterinfo_: the datacenter metadata

eureka_sd_configs配置可选项如下:

# The URL to connect to the Eureka server.server: # Sets the `Authorization` header on every request with the# configured username and password.# password and password_file are mutually exclusive.basic_auth:  [ username:  ]  [ password:  ]  [ password_file:  ]# Optional `Authorization` header configuration.authorization:  # Sets the authentication type.  [ type:  | default: Bearer ]  # Sets the credentials. It is mutually exclusive with  # `credentials_file`.  [ credentials:  ]  # Sets the credentials to the credentials read from the configured file.  # It is mutually exclusive with `credentials`.  [ credentials_file:  ]# Optional OAuth 2.0 configuration.# Cannot be used at the same time as basic_auth or authorization.oauth2:  [  ]# Configures the scrape request"s TLS settings.tls_config:  [  ]# Optional proxy URL.[ proxy_url:  ]# Configure whether HTTP requests follow HTTP 3xx redirects.[ follow_redirects:  | default = true ]# Refresh interval to re-read the app instance list.[ refresh_interval:  | default = 30s ]

协议分析

通过前面分析的Prometheus服务发现原理以及基于文件方式服务发现协议实现的分析,Eureka服务发现大致原理如下图:

通过解析配置中eureka_sd_configs协议的job生成Config,然后NewDiscovery方法创建出对应的Discoverer,最后调用Discoverer.Run()方法启动服务发现targets。

1、基于文件服务发现配置解析

假如我们定义如下job:

- job_name: "eureka"  eureka_sd_configs:    - server: http://localhost:8761/eureka    

会被解析成eureka.SDConfig如下:

eureka.SDConfig定义如下:

type SDConfig struct {    // eureka-server地址 Server           string                  `yaml:"server,omitempty"`    // http请求client配置,如:认证信息 HTTPClientConfig config.HTTPClientConfig `yaml:",inline"`    // 周期刷新间隔,默认30s RefreshInterval  model.Duration          `yaml:"refresh_interval,omitempty"`}

2、Discovery创建

func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { rt, err := config.NewRoundTripperFromConfig(conf.HTTPClientConfig, "eureka_sd", config.WithHTTP2Disabled()) if err != nil {  return nil, err } d := &Discovery{  client: &http.Client{Transport: rt},  server: conf.Server, } d.Discovery = refresh.NewDiscovery(  logger,  "eureka",  time.Duration(conf.RefreshInterval),  d.refresh, ) return d, nil}

3、Discovery创建完成,最后会调用Discovery.Run()启动服务发现:

和上一节分析的服务发现之File机制类似,执行Run方法时会执行tgs, err := d.refresh(ctx),然后创建定时周期触发器,不停执行tgs, err := d.refresh(ctx),将返回的targets结果信息通过channel传递出去。

4、上面Run方法核心是调用d.refresh(ctx)逻辑获取targets,基于Eureka发现协议主要实现逻辑就在这里:

func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { // 通过Eureka REST API接口从eureka拉取元数据:http://ip:port/eureka/apps apps, err := fetchApps(ctx, d.server, d.client) if err != nil {  return nil, err } tg := &targetgroup.Group{  Source: "eureka", } for _, app := range apps.Applications {//遍历app        // targetsForApp()方法将app下每个instance部分转成target  targets := targetsForApp(&app)        //假如到  tg.Targets = append(tg.Targets, targets...) } return []*targetgroup.Group{tg}, nil}

refresh方法主要有两个流程:

1、fetchApps():从eureka-server/eureka/apps接口拉取注册服务信息;

2、targetsForApp():遍历appinstance,将每个instance解析出一个target,并添加一堆元标签数据。

如下就是从eureka-server的/eureka/apps接口拉取的注册服务信息:

    1    UP_1_            SERVICE-PROVIDER-01                    localhost:service-provider-01:8001            192.168.3.121            SERVICE-PROVIDER-01            192.168.3.121            UP            UNKNOWN            8001            443            1                            MyOwn                                        30                90                1629385562130                1629385682050                0                1629385562132                                        8001                true                8080                        http://192.168.3.121:8001/            http://192.168.3.121:8001/actuator/info            http://192.168.3.121:8001/actuator/health            service-provider-01            service-provider-01            false            1629385562132            1629385562039            ADDED            

5、instance信息解析target

func targetsForApp(app *Application) []model.LabelSet { targets := make([]model.LabelSet, 0, len(app.Instances)) // Gather info about the app"s "instances". Each instance is considered a task. for _, t := range app.Instances {  var targetAddress string        // __address__取值方式:instance.hostname和port,没有port则默认port=80  if t.Port != nil {   targetAddress = net.JoinHostPort(t.HostName, strconv.Itoa(t.Port.Port))  } else {   targetAddress = net.JoinHostPort(t.HostName, "80")  }  target := model.LabelSet{   model.AddressLabel:  lv(targetAddress),   model.InstanceLabel: lv(t.InstanceID),   appNameLabel:                     lv(app.Name),   appInstanceHostNameLabel:         lv(t.HostName),   appInstanceHomePageURLLabel:      lv(t.HomePageURL),   appInstanceStatusPageURLLabel:    lv(t.StatusPageURL),   appInstanceHealthCheckURLLabel:   lv(t.HealthCheckURL),   appInstanceIPAddrLabel:           lv(t.IPAddr),   appInstanceVipAddressLabel:       lv(t.VipAddress),   appInstanceSecureVipAddressLabel: lv(t.SecureVipAddress),   appInstanceStatusLabel:           lv(t.Status),   appInstanceCountryIDLabel:        lv(strconv.Itoa(t.CountryID)),   appInstanceIDLabel:               lv(t.InstanceID),  }  if t.Port != nil {   target[appInstancePortLabel] = lv(strconv.Itoa(t.Port.Port))   target[appInstancePortEnabledLabel] = lv(strconv.FormatBool(t.Port.Enabled))  }  if t.SecurePort != nil {   target[appInstanceSecurePortLabel] = lv(strconv.Itoa(t.SecurePort.Port))   target[appInstanceSecurePortEnabledLabel] = lv(strconv.FormatBool(t.SecurePort.Enabled))  }  if t.DataCenterInfo != nil {   target[appInstanceDataCenterInfoNameLabel] = lv(t.DataCenterInfo.Name)   if t.DataCenterInfo.Metadata != nil {    for _, m := range t.DataCenterInfo.Metadata.Items {     ln := strutil.SanitizeLabelName(m.XMLName.Local)     target[model.LabelName(appInstanceDataCenterInfoMetadataPrefix+ln)] = lv(m.Content)    }   }  }  if t.Metadata != nil {   for _, m := range t.Metadata.Items {                // prometheus label只支持[^a-zA-Z0-9_]字符,其它非法字符都会被替换成下划线_    ln := strutil.SanitizeLabelName(m.XMLName.Local)    target[model.LabelName(appInstanceMetadataPrefix+ln)] = lv(m.Content)   }  }  targets = append(targets, target) } return targets}

解析比较简单,就不再分析,解析后的标签数据如下图:

标签中有两个特别说明下:

1、__address__:这个取值instance.hostname和port(默认80),所以要注意注册到eureka上的hostname准确性,不然可能无法抓取;

2、metadata-map数据会被转成__meta_eureka_app_instance_metadata_格式标签,prometheus进行relabeling一般操作metadata-map,可以自定义metric_path、抓取端口等;

3、prometheuslabel只支持[a-zA-Z0-9_],其它非法字符都会被转换成下划线,具体参加:strutil.SanitizeLabelName(m.XMLName.Local);但是eureka的metadata-map标签含有下划线时,注册到eureka-server上变成双下划线,如下配置:

eureka:  instance:    metadata-map:      scrape_enable: true      scrape.port: 8080

通过/eureka/apps获取如下:

总结

基于Eureka方式的服务原理如下图:

大概说明:Discoverer启动后定时周期触发从eureka server/eureka/apps接口拉取注册服务元数据,然后通过targetsForApp遍历app下的instance,将每个instance解析成target,并将其它元数据信息转换成target原标签可以用于target抓取前relabeling操作。

标签:

THE END
免责声明:本文系转载,版权归原作者所有;旨在传递信息,不代表热讯制鞋网的观点和立场。

相关热点

新华社电 上海市文化和旅游局近日发布《上海市密室剧本杀内容备案管理规定(征求意见稿)》,并截至12月8日面向社会公众广泛征求意见。这
2021-11-19 13:46:03
《中国证券报》17日刊发文章《备战2022 基金经理调仓换股布新局》。文章称,距离2021年结束仅剩一个多月,基金业绩分化明显。部分排名靠前
2021-11-19 13:46:03
交通运输部办公厅 中国人民银行办公厅 中国银行保险监督管理委员会办公厅关于进一步做好货车ETC发行服务有关工作的通知各省、自治区、直
2021-11-19 13:45:58
新华社北京11月17日电 题:从10月份市场供需积极变化看中国经济韧性新华社记者魏玉坤、丁乐读懂中国经济,一个直观的视角就是市场供需两端
2021-11-19 13:45:58
全国教育财务工作会议披露的消息称,2020年,中国国家财政性教育经费投入达4 29万亿元,占GDP总量的4 206%,我国国家财政性教育经费支出占G
2021-11-19 13:45:48
如果你也热爱“种草”,前方高能预警!让你心心念念、“浏览”忘返的网络平台,可能早已成为一块块“韭菜地”。近日,据《半月谈》报道,有...
2021-11-19 13:45:48
日前,工业和信息化部印发《“十四五”信息通信行业发展规划》(以下简称《规划》),描绘了未来5年信息通信行业的发展趋势。《规划》指出...
2021-11-19 13:45:40
本报讯(中青报·中青网记者 周围围)2021年快递业务旺季正式拉开帷幕。国家邮政局监测数据显示,仅11月1日当日,全国共揽收快递包裹5 69
2021-11-19 13:45:40
人民网曼谷11月17日电 (记者赵益普)17日上午,中国援柬埔寨第七批200万剂科兴新冠疫苗抵达金边国际机场。当天,柬埔寨政府在机场举行了
2021-11-19 13:45:35
金坛压缩空气储能国家试验示范项目主体工程一角受访者供图依托清华大学非补燃压缩空气储能技术,金坛压缩空气储能项目申请专利百余项,建立
2021-11-19 13:45:35
视觉中国供图42亿立方米据有关部门预计,今年山西煤炭产量有望突破12亿吨,12月份山西外送电能力将超过900万千瓦,今冬明春煤层气产量将达4
2021-11-19 13:44:34
14省份相继发布2021年企业工资指导线——引导企业合理提高职工工资今年以来,天津、新疆、内蒙古、陕西、西藏、山东、江西、山西、福建、四
2021-11-19 13:44:34
中新网客户端北京11月18日电 (记者 谢艺观)“一条路海角天涯,两颗心相依相伴,风吹不走誓言,雨打不湿浪漫,意济苍生苦与痛,情牵天下喜
2021-11-19 13:44:31
近日,交通运输部等三部门发布《关于进一步做好货车ETC发行服务有关工作的通知》。通知提到,对不具备授信条件的用户,商业银行可在依法合
2021-11-19 13:44:31
欧莱雅面膜陷优惠“年度最大”风波 涉及该事件集体投诉超6000人次美妆大牌双十一促销翻车?近日,因预售价格比双十一现货贵出66%,欧莱雅
2021-11-19 13:44:13
43 6%受访者会在工作两三年后考虑跳槽54 3%受访者认为跳槽对个人职业发展有利有弊如今对不少年轻人来说,想对一份工作“从一而终”不太容易
2021-11-19 13:44:13
超八成受访青年表示如有机会愿意开展副业 规划能力最重要64 4%受访青年指出做副业跟风心态最要不得如今,“身兼数职”已成为年轻人当中的
2021-11-19 13:44:01
发展氢能正当其时【科学随笔】氢能是一种二次能源,它通过一定的方法利用其他能源制取,具有清洁无污染、可储存、与多种能源便捷转换等优点
2021-11-19 13:44:01
“千杯不醉”的解酒“神药”能信吗?专家:网红“解酒药” 其实不算药俗话说,“酒逢知己千杯少”,酒一直是国人饭桌上至关重要的存在。尽...
2021-11-19 13:43:57
最新文章

相关推荐