Debian Codegraph @

contrib/sync-places.py

raw symbols SCIP
1 #! /usr/bin/env python3
2 #
3 # Copyright 2021 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 import argparse
18 import asyncio
19 from contextlib import contextmanager
20 from labgrid.remote.client import start_session
21 from labgrid.remote.generated import labgrid_coordinator_pb2
22 from labgrid.util.proxy import proxymanager
23 import os
24 import sys
25 import textwrap
26 import yaml
27
28
29 def main():
30 @contextmanager
31 def get_file(name, mode, standard):
32 if name == "-":
33 yield standard
34 else:
35 with open(name, mode) as f:
36 yield f
37
38 async def do_sync(session, args):
39 with get_file(args.places, "r", sys.stdin) as f:
40 config = yaml.safe_load(f)
41
42 config.setdefault("places", {})
43
44 changed = False
45 seen_places = set()
46 remove_places = set()
47 for name, place in session.places.items():
48 if name in config["places"]:
49 seen_places.add(name)
50 else:
51 remove_places.add(name)
52
53 for name in remove_places:
54 print(f"Removing place {name}")
55 if not args.dry_run:
56 request = labgrid_coordinator_pb2.DeletePlaceRequest(name=name)
57 await session.stub.DeletePlace(request)
58 await session.sync_with_coordinator()
59
60 changed = True
61
62 for name in config["places"]:
63 if not name in seen_places:
64 print(f"Adding place {name}")
65 if not args.dry_run:
66 request = labgrid_coordinator_pb2.AddPlaceRequest(name=name)
67 await session.stub.AddPlace(request)
68 await session.sync_with_coordinator()
69
70 changed = True
71
72 for name in config["places"]:
73 matches = []
74 for m in config["places"][name].get("matches", []):
75 if isinstance(m, dict):
76 match = list(m.keys())[0]
77 matches.append((match, m[match]))
78 else:
79 matches.append((m, None))
80
81 seen_matches = set()
82 remove_matches = set()
83 place_tags = {}
84 if name in seen_places:
85 place = session.places[name]
86 for m in [(repr(x), x.rename) for x in place.matches]:
87 if m in matches:
88 seen_matches.add(m)
89 else:
90 remove_matches.add(m)
91 place_tags = place.tags
92
93 for m in remove_matches:
94 match, rename = m
95 if rename:
96 print(f"Deleting named match '{match} -> {rename}' for place {name}")
97 else:
98 print(f"Deleting match '{match}' for place {name}")
99 if not args.dry_run:
100 request = labgrid_coordinator_pb2.DeletePlaceMatchRequest(placename=name, pattern=match)
101 await session.stub.DeletePlaceMatch(request)
102 await session.sync_with_coordinator()
103
104 changed = True
105
106 for m in matches:
107 if not m in seen_matches:
108 match, rename = m
109 if rename:
110 print(f"Adding named match '{match} -> {rename}' for place {name}")
111 else:
112 print(f"Adding match '{match}' for place {name}")
113
114 if not args.dry_run:
115 request = labgrid_coordinator_pb2.AddPlaceMatchRequest(
116 placename=name, pattern=match, rename=rename
117 )
118 await session.stub.AddPlaceMatch(request)
119 await session.sync_with_coordinator()
120 changed = True
121
122 tags = {str(k): str(v) for k, v in config["places"][name].get("tags", {}).items()}
123
124 if place_tags != tags:
125 print(
126 "Setting tags for place %s to %s"
127 % (
128 name,
129 ", ".join("%s=%s" % (key, value) for (key, value) in tags.items()),
130 )
131 )
132
133 # Set the empty string for tags that should be removed
134 for k in place_tags:
135 if k not in tags:
136 tags[k] = ""
137
138 if not args.dry_run:
139 request = labgrid_coordinator_pb2.SetPlaceTagsRequest(placename=name, tags=tags)
140 await session.stub.SetPlaceTags(request)
141 await session.sync_with_coordinator()
142
143 changed = True
144
145 async def do_dump(session, args):
146 config = {"places": {}}
147 for name, place in session.places.items():
148 config["places"][name] = {
149 "matches": [{repr(m): m.rename} if m.rename else repr(m) for m in place.matches],
150 "tags": {k: v for k, v in place.tags.items()},
151 }
152
153 with get_file(args.dest, "w", sys.stdout) as f:
154 yaml.dump(config, f)
155
156 parser = argparse.ArgumentParser(
157 description="Synchronize Labgrid places",
158 epilog=textwrap.dedent(
159 """\
160 The YAML files describe what places should exist and what match
161 strings and tags should be assigned to those places. The files are
162 structured like:
163
164 places: # A dictonary of places where each key is a place name
165 my-place1: # Replace with your place
166 matches: # A list of match patterns. Replace with your match patterns
167 - "*/my-place1/*"
168 - "exporter/my-place1/resource": name # named matches supported
169 tags: # A dictionary of key/value tags. Replace with your tags
170 board: awesomesauce
171 bar: baz
172
173 When syncing places, tags, and matches will be added or removed until the
174 remote configuration matches the one in the YAML file
175 """
176 ),
177 formatter_class=argparse.RawDescriptionHelpFormatter,
178 )
179 parser.add_argument(
180 "--coordinator",
181 "-x",
182 metavar="ADDRESS",
183 default=os.environ.get("LG_COORDINATOR", "127.0.0.1:20408"),
184 help="Coordinator address as HOST[:PORT] (default: %(default)s)",
185 )
186 parser.add_argument("--proxy", "-P", help="Proxy connections via given ssh host")
187
188 subparsers = parser.add_subparsers()
189 subparsers.required = True
190
191 sync_parser = subparsers.add_parser("sync", help="Synchronize coordinator places with file")
192 sync_parser.add_argument(
193 "places",
194 metavar="FILE",
195 help="Places configuration YAML file. Use '-' for stdin",
196 )
197 sync_parser.add_argument(
198 "--dry-run",
199 "-n",
200 action="store_true",
201 help="Don't make any changes, only show what would be done",
202 )
203 sync_parser.set_defaults(func=do_sync)
204
205 dump_parser = subparsers.add_parser(
206 "dump",
207 help="Dump existing places configuration to a YAML file. The dumped file is suitable for passing to `sync`",
208 )
209 dump_parser.add_argument(
210 "dest",
211 metavar="FILE",
212 nargs="?",
213 default="-",
214 help="Destination file. Use '-' for stdout. Default is '%(default)s'",
215 )
216 dump_parser.set_defaults(func=do_dump)
217
218 args = parser.parse_args()
219
220 if args.proxy:
221 proxymanager.force_proxy(args.proxy)
222
223 loop = asyncio.new_event_loop()
224 asyncio.set_event_loop(loop)
225
226 session = start_session(
227 args.coordinator,
228 loop=loop,
229 )
230
231 try:
232 return loop.run_until_complete(args.func(session, args))
233 finally:
234 loop.run_until_complete(session.stop())
235 loop.run_until_complete(session.close())
236
237
238 if __name__ == "__main__":
239 sys.exit(main())