hbs在整個open-falcon項目中承擔的角色就是鏈接數據庫,做爲數據庫緩存,緩存配置,主要給agent和judge提供服務。sql
hbs源碼分析將列出其對外提供的rpc服務以及其緩存的數據,並在最後嘗試闡述其最重要的兩個rpc服務GetExpressions和GetStrategies的執行過程。數據庫
hbs對外提供服務的方式有RPC和http,主要使用的是其rpc服務,其對外提供服務的rpc接口列表以下:express
接口名 | 提供對象 | 提供服務 |
---|---|---|
MinePlugins | agent | 經過agent提供的hostname獲取其對應的主機組列表,再找到對應plugin list返回 |
ReportStatus | agent | 獲取agent的信息緩存並插入或更新到數據庫中的host中(hostname, ip, agent_version, plugin_version) |
TrustableIps | agent | 若是配置文件中配置了信任IP,則把信任IP列表發給agent |
BuiltinMetrics | agent | 經過agent的hostname獲取其對應的主機組列表,並找到templat list,從strategy表中篩選出('net.port.listen', 'proc.num', 'du.bs', 'url.check.health')這些metric的metric和tags |
GetExpressions | judge | 返回數據庫中全部生效的Expressions |
GetStrategies | judge | 獲取全部的strategys並按照hostname:strategys的方式組織數據返回 |
hbs啓動了一個定時任務,每間隔一分鐘去數據庫讀取數據並緩存起來。下表是其緩存的數據列表:緩存
緩存名稱 | 含義 | 執行sql |
---|---|---|
GroupPlugins | 緩存全部的plugins路徑 | select grp_id, dir from plugin_dir |
GroupTemplates | 緩存主機組和模板對應關係 | select grp_id, tpl_id from grp_tpl |
HostGroupsMap | 緩存主機和主機組對應關係 | select grp_id, host_id from grp_host |
HostMap | 緩存全部主機 | select id, hostname from host |
TemplateCache | 緩存全部模板 | select id, tpl_name, parent_id, action_id, create_user from tpl |
Strategies | 緩存全部strategys | "select %s from strategy as s where (s.run_begin='' and s.run_end='') or (s.run_begin <= '%s' and s.run_end > '%s')","s.id, s.metric, s.tags, s.func, s.op, s.right_value, s.max_step, s.priority, s.note, s.tpl_id",now,now |
HostTemplateIds | 緩存主機與模板對應關係 | select a.tpl_id, b.host_id from grp_tpl as a inner join grp_host as b on a.grp_id=b.grp_id |
ExpressionCache | 緩存全部正常的Expression | select id, expression, func, op, right_value, max_step, priority, note, action_id from expression where action_id>0 and pause=0 |
MonitoredHosts | 緩存全部不處於維護狀態的主機 | "select id, hostname from host where maintain_begin > %d or maintain_end < %d", now, now |
GetExpressions
服務調用cache.ExpressionCache.Get()
方法獲取緩存中存儲的全部Expression
GetStrategies
服務先調用cache.HostTemplateIds.GetMap()
方法獲取每一個主機id對應的全部template id
,再調用cache.MonitoredHosts.Get()
方法獲取不處於維護狀態的主機名與id列表。調用cache.TemplateCache.GetMap()
方法獲取全部的模板,調用cache.Strategies.GetMap()
獲取全部的strategies
。調用Tpl2Strategies(strategies)
對tpl_id和strategies作了一個字典映射,這樣經過tpl_id就能找到對應的全部strategies。循環每臺主機,調用CalcInheritStrategies
方法獲取每臺主機對應的strategies
,再將主機名和對應的strategies
組合成一個結構體,將全部這些結構體組合在hostStrategies
中返回給judge。
Tpl2Strategies
方法循環strategies
,將tplid
做爲key
,value
是strategies
組成的array
,返回給調用者,目的是能夠直接經過tplid
找到對應的全部strategies
。CalcInheritStrategies
方法首先遍歷主機對應的模板列表,對每一個模板都尋找其父模板,生成一個模板bucket
,這樣,就使得原先的每一個模板都變成了一個模板列表。bucket
,生成uniq_tpl_buckets
uniq_tpl_buckets
,找到全部的strategies
,並用子模板的strategies
覆蓋父模板相同的strategies
。strategies
。優勢:源碼分析
缺點:優化
strategys
功能代碼太複雜,建議優化的更簡潔。