Merge ~andersson123/autopkgtest-cloud:configparser-read-refactor into autopkgtest-cloud:master

Proposed by Tim Andersson
Status: Merged
Merged at revision: 9a8aaad5c28148157ab9030a45e1f219d661eaca
Proposed branch: ~andersson123/autopkgtest-cloud:configparser-read-refactor
Merge into: autopkgtest-cloud:master
Diff against target: 470 lines (+87/-57)
15 files modified
charms/focal/autopkgtest-cloud-worker/autopkgtest-cloud/tools/copy-swift-results (+2/-1)
charms/focal/autopkgtest-cloud-worker/autopkgtest-cloud/worker/worker (+2/-1)
charms/focal/autopkgtest-web/webcontrol/amqp-status-collector (+2/-3)
charms/focal/autopkgtest-web/webcontrol/browse.cgi (+7/-4)
charms/focal/autopkgtest-web/webcontrol/cache-amqp (+2/-3)
charms/focal/autopkgtest-web/webcontrol/db-backup (+2/-4)
charms/focal/autopkgtest-web/webcontrol/download-all-results (+2/-3)
charms/focal/autopkgtest-web/webcontrol/download-results (+2/-4)
charms/focal/autopkgtest-web/webcontrol/helpers/utils.py (+36/-0)
charms/focal/autopkgtest-web/webcontrol/indexed-packages (+3/-4)
charms/focal/autopkgtest-web/webcontrol/private_results/app.py (+9/-6)
charms/focal/autopkgtest-web/webcontrol/publish-db (+2/-3)
charms/focal/autopkgtest-web/webcontrol/request/submit.py (+2/-3)
charms/focal/autopkgtest-web/webcontrol/request/tests/test_submit.py (+11/-11)
charms/focal/autopkgtest-web/webcontrol/update-github-jobs (+3/-7)
Reviewer Review Type Date Requested Status
Skia Approve
Review via email: mp+462054@code.launchpad.net
To post a comment you must log in.
Revision history for this message
Tim Andersson (andersson123) wrote :

Amended now, unit tests are passing :)

Revision history for this message
Skia (hyask) wrote :

Looking good, only a few adjustments here and there.

review: Needs Fixing
Revision history for this message
Tim Andersson (andersson123) wrote :

amended and ready for re-review.

Revision history for this message
Skia (hyask) :
review: Needs Fixing
Revision history for this message
Tim Andersson (andersson123) wrote :

amended and ready for re-review

Revision history for this message
Skia (hyask) :
review: Needs Fixing
Revision history for this message
Tim Andersson (andersson123) wrote :

mb, I thought that syntax was correct, ready for re-review

Revision history for this message
Tim Andersson (andersson123) wrote :

hm, I need to fix a merge conflict too

Revision history for this message
Tim Andersson (andersson123) wrote :

merge conflict amended, ready for re-review

Revision history for this message
Skia (hyask) wrote :

All good! :-)
Thanks

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1diff --git a/charms/focal/autopkgtest-cloud-worker/autopkgtest-cloud/tools/copy-swift-results b/charms/focal/autopkgtest-cloud-worker/autopkgtest-cloud/tools/copy-swift-results
2index ba8a40e..9484539 100755
3--- a/charms/focal/autopkgtest-cloud-worker/autopkgtest-cloud/tools/copy-swift-results
4+++ b/charms/focal/autopkgtest-cloud-worker/autopkgtest-cloud/tools/copy-swift-results
5@@ -48,7 +48,8 @@ releases = "noble mantic jammy focal lunar"
6
7
8 conf = configparser.ConfigParser()
9-conf.read(creds_file)
10+with open(creds_file, "r") as f:
11+ conf.read_file(f)
12
13 swift_creds = {
14 "old": {
15diff --git a/charms/focal/autopkgtest-cloud-worker/autopkgtest-cloud/worker/worker b/charms/focal/autopkgtest-cloud-worker/autopkgtest-cloud/worker/worker
16index 6424ef4..3511171 100755
17--- a/charms/focal/autopkgtest-cloud-worker/autopkgtest-cloud/worker/worker
18+++ b/charms/focal/autopkgtest-cloud-worker/autopkgtest-cloud/worker/worker
19@@ -1529,7 +1529,8 @@ def main():
20 },
21 allow_no_value=True,
22 )
23- cfg.read(args.config)
24+ with open(args.config, "r") as f:
25+ cfg.read_file(f)
26
27 logging.basicConfig(
28 level=(args.debug and logging.DEBUG or logging.INFO),
29diff --git a/charms/focal/autopkgtest-web/webcontrol/amqp-status-collector b/charms/focal/autopkgtest-web/webcontrol/amqp-status-collector
30index a61a949..1169f2e 100755
31--- a/charms/focal/autopkgtest-web/webcontrol/amqp-status-collector
32+++ b/charms/focal/autopkgtest-web/webcontrol/amqp-status-collector
33@@ -2,7 +2,6 @@
34 # Pick up running tests, their status and logtail from the "teststatus" fanout
35 # queue, and regularly write it into /run/amqp-status-collector/running.json
36
37-import configparser
38 import json
39 import logging
40 import os
41@@ -11,6 +10,7 @@ import time
42 import urllib.parse
43
44 import amqplib.client_0_8 as amqp
45+from helpers.utils import get_autopkgtest_cloud_conf
46
47 exchange_name = "teststatus.fanout"
48 running_name = os.path.join(
49@@ -26,8 +26,7 @@ last_update = 0
50 def amqp_connect():
51 """Connect to AMQP server"""
52
53- cp = configparser.ConfigParser()
54- cp.read(os.path.expanduser("~ubuntu/autopkgtest-cloud.conf"))
55+ cp = get_autopkgtest_cloud_conf()
56 amqp_uri = cp["amqp"]["uri"]
57 parts = urllib.parse.urlsplit(amqp_uri, allow_fragments=False)
58 amqp_con = amqp.Connection(
59diff --git a/charms/focal/autopkgtest-web/webcontrol/browse.cgi b/charms/focal/autopkgtest-web/webcontrol/browse.cgi
60index a1c87d9..47eb8a0 100755
61--- a/charms/focal/autopkgtest-web/webcontrol/browse.cgi
62+++ b/charms/focal/autopkgtest-web/webcontrol/browse.cgi
63@@ -2,7 +2,6 @@
64
65 """Browse autopkgtest results"""
66
67-import configparser
68 import json
69 import os
70 import re
71@@ -13,7 +12,12 @@ from wsgiref.handlers import CGIHandler
72 import flask
73 from helpers.admin import select_abnormally_long_jobs
74 from helpers.exceptions import RunningJSONNotFound
75-from helpers.utils import get_all_releases, get_supported_releases, setup_key
76+from helpers.utils import (
77+ get_all_releases,
78+ get_autopkgtest_cloud_conf,
79+ get_supported_releases,
80+ setup_key,
81+)
82 from werkzeug.middleware.proxy_fix import ProxyFix
83
84 # Initialize app
85@@ -43,8 +47,7 @@ RUNNING_CACHE = "/run/amqp-status-collector/running.json"
86 def init_config():
87 global db_con, swift_container_url, INDEXED_PACKAGES_FP
88
89- cp = configparser.ConfigParser()
90- cp.read(os.path.expanduser("~ubuntu/autopkgtest-cloud.conf"))
91+ cp = get_autopkgtest_cloud_conf()
92
93 db_con = sqlite3.connect(
94 "file:%s?mode=ro" % cp["web"]["database_ro"],
95diff --git a/charms/focal/autopkgtest-web/webcontrol/cache-amqp b/charms/focal/autopkgtest-web/webcontrol/cache-amqp
96index d8cd653..adfd4df 100755
97--- a/charms/focal/autopkgtest-web/webcontrol/cache-amqp
98+++ b/charms/focal/autopkgtest-web/webcontrol/cache-amqp
99@@ -1,7 +1,6 @@
100 #!/usr/bin/python3
101
102 import argparse
103-import configparser
104 import json
105 import logging
106 import os
107@@ -14,6 +13,7 @@ import urllib.request
108
109 import amqplib.client_0_8 as amqp
110 from amqplib.client_0_8.exceptions import AMQPChannelException
111+from helpers.utils import get_autopkgtest_cloud_conf
112
113 AMQP_CONTEXTS = ["ubuntu", "huge", "ppa", "upstream"]
114
115@@ -236,8 +236,7 @@ if __name__ == "__main__":
116
117 args = parser.parse_args()
118
119- cp = configparser.ConfigParser()
120- cp.read(os.path.expanduser("~ubuntu/autopkgtest-cloud.conf"))
121+ cp = get_autopkgtest_cloud_conf()
122
123 logger = logging.getLogger()
124 formatter = logging.Formatter(
125diff --git a/charms/focal/autopkgtest-web/webcontrol/db-backup b/charms/focal/autopkgtest-web/webcontrol/db-backup
126index 08b8513..b03100b 100755
127--- a/charms/focal/autopkgtest-web/webcontrol/db-backup
128+++ b/charms/focal/autopkgtest-web/webcontrol/db-backup
129@@ -5,7 +5,6 @@ and clears up old backups
130 """
131
132 import atexit
133-import configparser
134 import datetime
135 import gzip
136 import hashlib
137@@ -17,7 +16,7 @@ import sys
138 from pathlib import Path
139
140 import swiftclient
141-from helpers.utils import init_db
142+from helpers.utils import get_autopkgtest_cloud_conf, init_db
143
144 DB_PATH = ""
145 DB_NAME = ""
146@@ -36,8 +35,7 @@ def db_connect() -> sqlite3.Connection:
147 global DB_NAME
148 global DB_BACKUP_NAME
149 global DB_BACKUP_PATH
150- cp = configparser.ConfigParser()
151- cp.read(os.path.expanduser("~ubuntu/autopkgtest-cloud.conf"))
152+ cp = get_autopkgtest_cloud_conf()
153 DB_PATH = Path(cp["web"]["database"])
154 DB_NAME = DB_PATH.name
155 DB_BACKUP_NAME = "%s.bak" % DB_NAME
156diff --git a/charms/focal/autopkgtest-web/webcontrol/download-all-results b/charms/focal/autopkgtest-web/webcontrol/download-all-results
157index 9a8c8d3..157c052 100755
158--- a/charms/focal/autopkgtest-web/webcontrol/download-all-results
159+++ b/charms/focal/autopkgtest-web/webcontrol/download-all-results
160@@ -26,7 +26,7 @@ import urllib.parse
161 import amqplib.client_0_8 as amqp
162 import swiftclient
163 from distro_info import UbuntuDistroInfo
164-from helpers.utils import SqliteWriterConfig
165+from helpers.utils import SqliteWriterConfig, get_autopkgtest_cloud_conf
166
167 LOGGER = logging.getLogger(__name__)
168 SWIFT_CREDS_FILE = "/home/ubuntu/public-swift-creds"
169@@ -229,8 +229,7 @@ if __name__ == "__main__":
170 )
171 releases.sort(key=UbuntuDistroInfo().all.index, reverse=True)
172
173- config = configparser.ConfigParser()
174- config.read(os.path.expanduser("~ubuntu/autopkgtest-cloud.conf"))
175+ config = get_autopkgtest_cloud_conf()
176 amqp_con = amqp_connect()
177 db_con = sqlite3.connect(
178 "file:%s%s" % (config["web"]["database"], "?mode=ro"), uri=True
179diff --git a/charms/focal/autopkgtest-web/webcontrol/download-results b/charms/focal/autopkgtest-web/webcontrol/download-results
180index ac19f39..1297a66 100755
181--- a/charms/focal/autopkgtest-web/webcontrol/download-results
182+++ b/charms/focal/autopkgtest-web/webcontrol/download-results
183@@ -1,6 +1,5 @@
184 #!/usr/bin/python3
185
186-import configparser
187 import datetime
188 import json
189 import logging
190@@ -11,7 +10,7 @@ import time
191 import urllib.parse
192
193 import amqplib.client_0_8 as amqp
194-from helpers.utils import SqliteWriterConfig
195+from helpers.utils import SqliteWriterConfig, get_autopkgtest_cloud_conf
196
197 EXCHANGE_NAME = "testcomplete.fanout"
198 amqp_con = None
199@@ -20,8 +19,7 @@ amqp_con = None
200 def amqp_connect():
201 """Connect to AMQP server"""
202
203- cp = configparser.ConfigParser()
204- cp.read(os.path.expanduser("~ubuntu/autopkgtest-cloud.conf"))
205+ cp = get_autopkgtest_cloud_conf()
206 amqp_uri = cp["amqp"]["uri"]
207 parts = urllib.parse.urlsplit(amqp_uri, allow_fragments=False)
208 amqp_con = amqp.Connection(
209diff --git a/charms/focal/autopkgtest-web/webcontrol/helpers/utils.py b/charms/focal/autopkgtest-web/webcontrol/helpers/utils.py
210index 9b007d5..9b95cc8 100644
211--- a/charms/focal/autopkgtest-web/webcontrol/helpers/utils.py
212+++ b/charms/focal/autopkgtest-web/webcontrol/helpers/utils.py
213@@ -1,12 +1,16 @@
214 """
215 utilities for autopkgtest-web webcontrol
216 """
217+import configparser
218+
219 # pylint: disable=protected-access
220 import logging
221 import os
222+import pathlib
223 import random
224 import sqlite3
225 import time
226+import typing
227
228 # introduced in python3.7, we use 3.8
229 from dataclasses import dataclass
230@@ -34,6 +38,38 @@ class SqliteWriterConfig:
231 retry_time_limit = 120 # seconds
232
233
234+def read_config_file(
235+ filepath: typing.Union[str, pathlib.Path], cfg_key: str = None
236+):
237+ """
238+ Reads a given config file, whether it be a key=value env file or
239+ properly formatted config file
240+ :param filepath
241+ Path to config file. Can be a string or pathlib.Path
242+ :type filepath: ``type[str | pathlib.Path]``
243+ :param cfg_key
244+ Variable only necessary when parsing a key=value env file.
245+ indicates the first key to be used e.g. cfg["cfg_key"]["env_file_value"]
246+ This is a configparser "section" name.
247+ :type cfg_key ``str``
248+ """
249+ config = configparser.ConfigParser()
250+ if cfg_key is None:
251+ with open(filepath, "r") as f:
252+ config.read_file(f)
253+ return config
254+ else:
255+ with open(filepath, "r") as fp:
256+ config.read_string(
257+ ("[%s]\n" % cfg_key) + fp.read().replace('"', "")
258+ ) # read_string preserves "" quotes
259+ return config
260+
261+
262+def get_autopkgtest_cloud_conf():
263+ return read_config_file("/home/ubuntu/autopkgtest-cloud.conf")
264+
265+
266 def get_all_releases():
267 udi = distro_info.UbuntuDistroInfo()
268 return udi.all
269diff --git a/charms/focal/autopkgtest-web/webcontrol/indexed-packages b/charms/focal/autopkgtest-web/webcontrol/indexed-packages
270index 82502b1..1122bd2 100755
271--- a/charms/focal/autopkgtest-web/webcontrol/indexed-packages
272+++ b/charms/focal/autopkgtest-web/webcontrol/indexed-packages
273@@ -1,10 +1,10 @@
274 #!/usr/bin/python3
275
276-import configparser
277 import json
278-import os
279 import sqlite3
280
281+from helpers.utils import get_autopkgtest_cloud_conf
282+
283
284 def srchash(src):
285 if src.startswith("lib"):
286@@ -14,8 +14,7 @@ def srchash(src):
287
288
289 if __name__ == "__main__":
290- cp = configparser.ConfigParser()
291- cp.read(os.path.expanduser("~ubuntu/autopkgtest-cloud.conf"))
292+ cp = get_autopkgtest_cloud_conf()
293 indexed_packages_fp = cp["web"]["indexed_packages_fp"]
294
295 db_con = sqlite3.connect(
296diff --git a/charms/focal/autopkgtest-web/webcontrol/private_results/app.py b/charms/focal/autopkgtest-web/webcontrol/private_results/app.py
297index 0a793bc..36b1fd0 100644
298--- a/charms/focal/autopkgtest-web/webcontrol/private_results/app.py
299+++ b/charms/focal/autopkgtest-web/webcontrol/private_results/app.py
300@@ -1,5 +1,4 @@
301 """Test Result Fetcher Flask App"""
302-import configparser
303 import logging
304 import os
305 import sys
306@@ -15,7 +14,11 @@ from flask import (
307 session,
308 )
309 from flask_openid import OpenID
310-from helpers.utils import setup_key
311+from helpers.utils import (
312+ get_autopkgtest_cloud_conf,
313+ read_config_file,
314+ setup_key,
315+)
316 from request.submit import Submit
317 from werkzeug.middleware.proxy_fix import ProxyFix
318
319@@ -94,11 +97,11 @@ secret_path = os.path.join(PATH, "secret_key")
320 setup_key(app, secret_path)
321 oid = OpenID(app, os.path.join(PATH, "openid"), safe_roots=[])
322 # Load configuration
323-cfg = configparser.ConfigParser()
324-cfg.read(os.path.expanduser("~ubuntu/swift-web-credentials.conf"))
325+cfg = read_config_file(
326+ os.path.expanduser("~ubuntu/swift-web-credentials.conf")
327+)
328 # The web configuration as well
329-cfg_web = configparser.ConfigParser()
330-cfg_web.read(os.path.expanduser("~ubuntu/autopkgtest-cloud.conf"))
331+cfg_web = get_autopkgtest_cloud_conf()
332 # Build swift credentials
333 auth_url = cfg.get("swift", "auth_url")
334 if "/v2.0" in auth_url:
335diff --git a/charms/focal/autopkgtest-web/webcontrol/publish-db b/charms/focal/autopkgtest-web/webcontrol/publish-db
336index ef4d1ef..03c8b10 100755
337--- a/charms/focal/autopkgtest-web/webcontrol/publish-db
338+++ b/charms/focal/autopkgtest-web/webcontrol/publish-db
339@@ -6,7 +6,6 @@ This is being used for statistics, and is used by britney and other
340 external monitoring tools.
341 """
342
343-import configparser
344 import gzip
345 import logging
346 import os
347@@ -15,6 +14,7 @@ import tempfile
348 import urllib.request
349
350 import apt_pkg
351+from helpers.utils import get_autopkgtest_cloud_conf
352
353 config = None
354 db_con = None
355@@ -185,8 +185,7 @@ if __name__ == "__main__":
356 if "DEBUG" in os.environ:
357 logging.basicConfig(level=logging.DEBUG)
358
359- config = configparser.ConfigParser()
360- config.read(os.path.expanduser("~ubuntu/autopkgtest-cloud.conf"))
361+ config = get_autopkgtest_cloud_conf()
362
363 target = config["web"]["database_ro"]
364 target_new = "{}.new".format(target)
365diff --git a/charms/focal/autopkgtest-web/webcontrol/request/submit.py b/charms/focal/autopkgtest-web/webcontrol/request/submit.py
366index d2e5b0d..30caaa5 100644
367--- a/charms/focal/autopkgtest-web/webcontrol/request/submit.py
368+++ b/charms/focal/autopkgtest-web/webcontrol/request/submit.py
369@@ -4,7 +4,6 @@ Author: Martin Pitt <martin.pitt@ubuntu.com>
370 """
371
372 import base64
373-import configparser
374 import json
375 import logging
376 import os
377@@ -26,6 +25,7 @@ from helpers.exceptions import (
378 RequestInQueue,
379 RequestRunning,
380 )
381+from helpers.utils import get_autopkgtest_cloud_conf
382
383 # Launchpad REST API base
384 LP = "https://api.launchpad.net/1.0/"
385@@ -56,8 +56,7 @@ RUNNING_FP = "/run/amqp-status-collector/running.json"
386
387 class Submit:
388 def __init__(self):
389- cp = configparser.ConfigParser()
390- cp.read(os.path.expanduser("~ubuntu/autopkgtest-cloud.conf"))
391+ cp = get_autopkgtest_cloud_conf()
392
393 # read valid releases and architectures from DB
394 self.db_con = sqlite3.connect(
395diff --git a/charms/focal/autopkgtest-web/webcontrol/request/tests/test_submit.py b/charms/focal/autopkgtest-web/webcontrol/request/tests/test_submit.py
396index 4e9e1f7..5fefef5 100644
397--- a/charms/focal/autopkgtest-web/webcontrol/request/tests/test_submit.py
398+++ b/charms/focal/autopkgtest-web/webcontrol/request/tests/test_submit.py
399@@ -21,9 +21,18 @@ from helpers.exceptions import (
400 class SubmitTestBase(TestCase):
401 """Common setup of tests of Submit class"""
402
403- @patch("request.submit.configparser.ConfigParser")
404 @patch("request.submit.sqlite3")
405- def setUp(self, mock_sqlite, mock_configparser):
406+ @patch(
407+ "request.submit.get_autopkgtest_cloud_conf",
408+ MagicMock(
409+ return_value={
410+ "amqp": {"uri": "amqp://user:s3kr1t@1.2.3.4"},
411+ "web": {"database": "/ignored", "database_ro": "/ignored"},
412+ "autopkgtest": {"releases": "testy grumpy"},
413+ }
414+ ),
415+ )
416+ def setUp(self, mock_sqlite):
417 test_db = sqlite3.connect(":memory:")
418 test_db.execute(
419 "CREATE TABLE test ("
420@@ -44,15 +53,6 @@ class SubmitTestBase(TestCase):
421 test_db.commit()
422 mock_sqlite.connect.return_value = test_db
423
424- # mock config values
425- cfg = {
426- "amqp": {"uri": "amqp://user:s3kr1t@1.2.3.4"},
427- "web": {"database": "/ignored", "database_ro": "/ignored"},
428- "autopkgtest": {"releases": "testy grumpy"},
429- }
430- mock_configparser.return_value = MagicMock()
431- mock_configparser.return_value.__getitem__.side_effect = cfg.get
432-
433 self.submit = request.submit.Submit()
434 self.submit.releases.add("testy")
435
436diff --git a/charms/focal/autopkgtest-web/webcontrol/update-github-jobs b/charms/focal/autopkgtest-web/webcontrol/update-github-jobs
437index 9aeb8e7..4308183 100755
438--- a/charms/focal/autopkgtest-web/webcontrol/update-github-jobs
439+++ b/charms/focal/autopkgtest-web/webcontrol/update-github-jobs
440@@ -1,6 +1,5 @@
441 #!/usr/bin/python3
442
443-import configparser
444 import datetime
445 import io
446 import json
447@@ -12,6 +11,7 @@ import tarfile
448 from datetime import datetime, timedelta
449
450 import swiftclient
451+from helpers.utils import get_autopkgtest_cloud_conf, read_config_file
452 from request.submit import Submit
453
454 PENDING_DIR = "/run/autopkgtest_webcontrol/github-pending"
455@@ -216,13 +216,9 @@ if __name__ == "__main__":
456 logging.info("%s does not exist, nothing to do", PENDING_DIR)
457 sys.exit(0)
458
459- config = configparser.ConfigParser()
460- config.read("/home/ubuntu/autopkgtest-cloud.conf")
461+ config = get_autopkgtest_cloud_conf()
462 external_url = config["web"]["ExternalURL"]
463- swift_cfg = configparser.ConfigParser()
464- # Nice way of passing an environment-like file to configparser
465- with open(SWIFT_CREDS_FILE, "r") as fp:
466- swift_cfg.read_string("[swift]\n" + fp.read())
467+ swift_cfg = read_config_file(filepath=SWIFT_CREDS_FILE, cfg_key="swift")
468
469 swift_creds = {
470 "authurl": swift_cfg["swift"]["OS_AUTH_URL"],

Subscribers

People subscribed via source and target branches