Skip to content

Commit dda06ee

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 d3808d6 commit dda06ee

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
@@ -238,8 +240,13 @@ def _update_config_file(self, bind_addresses):
238240
conf = dict()
239241
conf[self.ALL_BIND_ADDRS_KEY] = bind_addresses
240242

241-
with open(file_path, 'w') as conf_file:
242-
yaml.dump(conf, conf_file)
243+
dir_name = os.path.dirname(file_path)
244+
with tempfile.NamedTemporaryFile('w', dir=dir_name, delete=False) as tmp_file:
245+
yaml.dump(conf, tmp_file)
246+
temp_name = tmp_file.name
247+
248+
os.replace(temp_name, file_path)
249+
os.remove(temp_name)
243250

244251
self._request_config_reload()
245252
self._stored.all_bind_addresses = bind_addresses

0 commit comments

Comments
 (0)