Debian Codegraph @

contrib/coordinator-statsd.py

raw symbols SCIP
1 #! /usr/bin/env python3
2 #
3 # Copyright 2022 Garmin Ltd. or its subsidiaries
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 # All metrics are optionally prefixed by a set of tag values which can be
18 # specified with the --tag command line option.
19 #
20 # This program will connect to a labgrid coordinator and report the following
21 # stats about places to a statsd server on a periodic basis:
22 #
23 # labgrid.places.[TAG[.TAG]].acquired (gauge): The number of places that are
24 # currently acquired with this
25 # set of tags
26 # labgrid.places.[TAG[.TAG]].total (gauge): The number of places attached to
27 # the coordinator with this set of
28 # tags
29 #
30 # It also can report metrics about reservations with the following format:
31 #
32 # labgrid.reservations.GROUP.[TAG[.TAG]].STATE (gauge): The number of
33 # reservations in the
34 # given STATE
35 #
36 # where:
37 # GROUP is the name of the filter group used for the reservation. Currently,
38 # just "main"
39 #
40 # STATE is the state of the reservation, e.g. "acquired", "waiting", etc.
41
42
43 import sys
44 import argparse
45 import os
46 import time
47 import asyncio
48
49 from labgrid.remote.client import start_session, Error
50 from labgrid.remote.generated import labgrid_coordinator_pb2
51 from labgrid.remote.common import Reservation
52 import statsd
53
54
55 def inc_gauge(gauges, key):
56 gauges.setdefault(key, 0)
57 gauges[key] += 1
58
59
60 async def report_reservations(session, tags, gauges):
61 request = labgrid_coordinator_pb2.GetReservationsRequest()
62
63 response = await session.stub.GetReservations(request)
64 reservations = [Reservation.from_pb2(x) for x in response.reservations]
65
66 for reservation in reservations:
67 groups = reservation.filters
68
69 if not groups:
70 groups = {"": {}}
71
72 for group_name, group in groups.items():
73 inc_gauge(
74 gauges,
75 ".".join(["reservations", group_name] + [group.get(t, "") for t in tags] + [reservation.state.name]),
76 )
77
78
79 async def report_places(session, tags, gauges):
80 acquired_count = 0
81 total_count = 0
82
83 for name, place in session.places.items():
84 prefix = ".".join(["places"] + [place.tags.get(t, "") for t in tags])
85 inc_gauge(gauges, f"{prefix}.total")
86 if place.acquired:
87 inc_gauge(gauges, f"{prefix}.acquired")
88
89
90 def main():
91 parser = argparse.ArgumentParser(description="Report Labgrid usage metrics to statsd")
92 parser.add_argument(
93 "-x",
94 "--coordinator",
95 metavar="ADDRESS",
96 help="Coordinator address as HOST[:PORT]. Default is %(default)s",
97 default=os.environ.get("LG_COORDINATOR", "127.0.0.1:20408"),
98 )
99 parser.add_argument(
100 "--period",
101 help="How often to report reservations stats to statsd. Default is %(default)s",
102 type=int,
103 default=60,
104 )
105 parser.add_argument(
106 "--statsd-protocol",
107 metavar="PROTOCOL",
108 choices=("udp", "tcp"),
109 default="udp",
110 help="Use specified protocol for statsd",
111 )
112 parser.add_argument(
113 "--statsd-prefix",
114 metavar="PREFIX",
115 help="Prefix for statsd stats",
116 default="labgrid",
117 )
118 parser.add_argument(
119 "--statsd-server",
120 metavar="HOST",
121 help="Statsd server",
122 default="localhost",
123 )
124 parser.add_argument(
125 "--statsd-port",
126 metavar="PORT",
127 help="Statsd server port",
128 type=int,
129 default=8125,
130 )
131 parser.add_argument(
132 "--tag",
133 metavar="TAG",
134 dest="tags",
135 help="Tag values to include in statsd path for reservations. Repeat to include multiple tags",
136 action="append",
137 default=[],
138 )
139
140 args = parser.parse_args()
141
142 loop = asyncio.new_event_loop()
143 asyncio.set_event_loop(loop)
144
145 statsd_client = None
146 gauges = {}
147
148 next_time = time.monotonic()
149
150 while True:
151 if statsd_client is None:
152 if args.statsd_protocol == "udp":
153 statsd_client = statsd.StatsClient(
154 host=args.statsd_server,
155 port=args.statsd_port,
156 prefix=args.statsd_prefix,
157 )
158 elif args.statsd_protocol == "tcp":
159 statsd_client = statsd.TCPStatsClient(
160 host=args.statsd_server,
161 port=args.statsd_port,
162 prefix=args.statsd_prefix,
163 )
164
165 # Reset all known gauges to 0
166 for key in gauges:
167 gauges[key] = 0
168
169 sleep_time = next_time - time.monotonic()
170 if sleep_time > 0:
171 time.sleep(sleep_time)
172
173 next_time = time.monotonic() + args.period
174 try:
175 session = start_session(args.coordinator, loop=loop)
176 try:
177 loop.run_until_complete(
178 asyncio.gather(
179 report_places(session, args.tags, gauges),
180 report_reservations(session, args.tags, gauges),
181 )
182 )
183 finally:
184 loop.run_until_complete(session.stop())
185 loop.run_until_complete(session.close())
186 except Error as e:
187 print(f"Error communicating with labgrid: {e}")
188 continue
189
190 try:
191 with statsd_client.pipeline() as pipe:
192 for k, v in gauges.items():
193 pipe.gauge(k, v)
194 except OSError as e:
195 print(f"Error communication with statsd server: {e}")
196 statsd_client = None
197 continue
198
199
200 if __name__ == "__main__":
201 sys.exit(main())