Commit 336fbf3c authored by Stan Hu's avatar Stan Hu

Merge branch 'network-policy-metrics-query' into 'master'

Add packet flow metric query for network policy metrics

See merge request gitlab-org/gitlab!30006
parents cc1fca54 c0aa9caa
# frozen_string_literal: true
module Gitlab::Prometheus::Queries
class PacketFlowMetricsQuery < BaseQuery
def query(namespace)
total_query = sum_by_verdict(
increase_query(%{destination="#{namespace}"}),
increase_query(%{source="#{namespace}"})
)
transform_sum_result(client_query(total_query))
end
private
def sum_by_verdict(vec1, vec2)
%{sum by(verdict) (#{vec1} or on(source,destination,verdict) #{vec2})}
end
def increase_query(selector)
%{increase(hubble_flows_processed_total{#{selector}}[1w])}
end
# Returns the number of forwarded and dropped packets from an instant vector:
# [
# {"metric"=>{"verdict"=>"FORWARDED"}, "value"=>[1582231596.64, "73772.43143284984"]},
# {"metric"=>{"verdict"=>"DROPPED"}, "value"=>[1582231596.64, "5.002730665588791"]}
# ]
def transform_sum_result(vector)
values = vector.each_with_object({ "DROPPED" => 0, "FORWARDED" => 0 }) do |val, acc|
acc[val["metric"].first.second] = val["value"].last.to_i
end
{ forwards: values["FORWARDED"], drops: values["DROPPED"] }
end
end
end
# frozen_string_literal: true
require 'spec_helper'
describe Gitlab::Prometheus::Queries::PacketFlowMetricsQuery do
let(:namespace) { 'query-12345678-production' }
let(:query_response) do
[
{ "metric" => { "verdict" => "FORWARDED" }, "value" => [1582231596.64, "73772.43143284984"] },
{ "metric" => { "verdict" => "DROPPED" }, "value" => [1582231596.64, "5.002730665588791"] }
]
end
let(:client) { double('prometheus_client', query: query_response) }
subject { described_class.new(client) }
describe '#query' do
it 'sends prometheus query' do
query = 'sum by(verdict) (' \
'increase(hubble_flows_processed_total{destination="query-12345678-production"}[1w])' \
' or on(source,destination,verdict) ' \
'increase(hubble_flows_processed_total{source="query-12345678-production"}[1w]))'
subject.query(namespace)
expect(client).to have_received(:query).with(query)
end
it 'returns metrics' do
result = subject.query(namespace)
expect(result).to match(forwards: 73772, drops: 5)
end
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment