Skip to content

Commit be4fb0a

Browse files
feat: write controller config atomically
It's possible to corrupt the controller config file if there is an exception during writing of the file. Instead, we want to only update the controller config atomically. This involves writing the yaml to a temp file and then do a atomic file replace (POSIX). This ensures that it will always be valid if the data is valid.
1 parent dfc4830 commit be4fb0a

1 file changed

Lines changed: 9 additions & 2 deletions

File tree

src/charm.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
import secrets
1010
import urllib.parse
1111
import yaml
12+
import tempfile
13+
import os
1214

1315
from charms.prometheus_k8s.v0.prometheus_scrape import MetricsEndpointProvider
1416
from ops.charm import CharmBase, CollectStatusEvent
@@ -234,8 +236,13 @@ def _update_config_file(self, bind_addresses):
234236
conf = dict()
235237
conf[self.ALL_BIND_ADDRS_KEY] = bind_addresses
236238

237-
with open(file_path, 'w') as conf_file:
238-
yaml.dump(conf, conf_file)
239+
dir_name = os.path.dirname(file_path)
240+
with tempfile.NamedTemporaryFile('w', dir=dir_name, delete=False) as tmp_file:
241+
yaml.dump(conf, tmp_file)
242+
temp_name = tmp_file.name
243+
244+
os.replace(temp_name, file_path)
245+
os.remove(temp_name)
239246

240247
self._request_config_reload()
241248
self._stored.all_bind_addresses = bind_addresses

0 commit comments

Comments
 (0)