fmu-settings 0.3.2__py3-none-any.whl → 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of fmu-settings might be problematic. Click here for more details.

fmu/settings/_fmu_dir.py CHANGED
@@ -82,7 +82,9 @@ class FMUDirectoryBase:
82
82
  FileNotFoundError: If config file doesn't exist
83
83
  ValueError: If the updated config is invalid
84
84
  """
85
+ logger.info(f"Setting {key} in {self.path}")
85
86
  self.config.set(key, value)
87
+ logger.debug(f"Set {key} to {value}")
86
88
 
87
89
  def update_config(
88
90
  self: Self, updates: dict[str, Any]
@@ -147,6 +149,7 @@ class FMUDirectoryBase:
147
149
  relative_path: Path relative to the .fmu directory
148
150
  data: Bytes to write
149
151
  """
152
+ self._lock.ensure_can_write()
150
153
  file_path = self.get_file_path(relative_path)
151
154
  file_path.parent.mkdir(parents=True, exist_ok=True)
152
155
 
@@ -163,6 +166,7 @@ class FMUDirectoryBase:
163
166
  content: Text content to write
164
167
  encoding: Text encoding to use. Default utf-8
165
168
  """
169
+ self._lock.ensure_can_write()
166
170
  file_path = self.get_file_path(relative_path)
167
171
  file_path.parent.mkdir(parents=True, exist_ok=True)
168
172
 
@@ -0,0 +1,241 @@
1
+ """Functions related to finding and validating an existing global configuration."""
2
+
3
+ from pathlib import Path
4
+ from typing import Final
5
+
6
+ from fmu.config.utilities import yaml_load
7
+ from fmu.datamodels.fmu_results.global_configuration import GlobalConfiguration
8
+
9
+ from ._logging import null_logger
10
+
11
+ logger: Final = null_logger(__name__)
12
+
13
+ # These should all be normalized to lower case.
14
+ INVALID_NAMES: Final[tuple[str, ...]] = (
15
+ "drogon",
16
+ "drogon_2020",
17
+ "drogon_has_no_stratcolumn",
18
+ )
19
+ INVALID_UUIDS: Final[tuple[str, ...]] = (
20
+ "ad214d85-dac7-19da-e053-c918a4889309",
21
+ "ad214d85-8a1d-19da-e053-c918a4889310",
22
+ "00000000-0000-0000-0000-000000000000",
23
+ )
24
+ INVALID_STRAT_NAMES: Final[tuple[str, ...]] = (
25
+ "basevolantis",
26
+ "basetherys",
27
+ "basevalysar",
28
+ "basevolon",
29
+ "therys",
30
+ "toptherys",
31
+ "topvolantis",
32
+ "topvolon",
33
+ "topvalysar",
34
+ "valysar",
35
+ "volantis",
36
+ "volon",
37
+ )
38
+
39
+
40
+ def validate_global_configuration_strictly(cfg: GlobalConfiguration) -> None: # noqa: PLR0912
41
+ """Does stricter checks against a valid GlobalConfiguration file.
42
+
43
+ This is to prevent importing existing but incorrect data that should not make it
44
+ into a project .fmu configuration. An example of this is Drogon masterdata.
45
+
46
+ Args:
47
+ cfg: A GlobalConfiguration instance to be validated
48
+
49
+ Raises:
50
+ ValueError: If some value in the GlobalConfiguration is invalid or not allowed
51
+ """
52
+ # Check model and access
53
+ if cfg.model.name.lower() in INVALID_NAMES:
54
+ raise ValueError(f"Invalid name in 'model': {cfg.model.name}")
55
+ if cfg.access.asset.name.lower() in INVALID_NAMES:
56
+ raise ValueError(f"Invalid name in 'access.asset': {cfg.access.asset.name}")
57
+
58
+ # Check masterdata
59
+
60
+ # smda.country
61
+ for country in cfg.masterdata.smda.country:
62
+ if str(country.uuid) in INVALID_UUIDS:
63
+ raise ValueError(f"Invalid SMDA UUID in 'smda.country': {country.uuid}")
64
+
65
+ # smda.discovery
66
+ for discovery in cfg.masterdata.smda.discovery:
67
+ if discovery.short_identifier.lower() in INVALID_NAMES:
68
+ raise ValueError(
69
+ f"Invalid SMDA short identifier in 'smda.discovery': "
70
+ f"{discovery.short_identifier}"
71
+ )
72
+ if str(discovery.uuid) in INVALID_UUIDS:
73
+ raise ValueError(f"Invalid SMDA UUID in 'smda.discovery': {discovery.uuid}")
74
+
75
+ # smda.field
76
+ for field in cfg.masterdata.smda.field:
77
+ if field.identifier.lower() in INVALID_NAMES:
78
+ raise ValueError(
79
+ f"Invalid SMDA identifier in 'smda.field': {field.identifier}"
80
+ )
81
+ if str(field.uuid) in INVALID_UUIDS:
82
+ raise ValueError(f"Invalid SMDA UUID in 'smda.field': {field.uuid}")
83
+
84
+ # smda.coordinate_system
85
+ if (coord_uuid := str(cfg.masterdata.smda.coordinate_system.uuid)) in INVALID_UUIDS:
86
+ raise ValueError(f"Invalid SMDA UUID in 'smda.coordinate_system': {coord_uuid}")
87
+
88
+ # smda.stratigraphic_column
89
+ strat = cfg.masterdata.smda.stratigraphic_column
90
+ if strat.identifier.lower() in INVALID_NAMES:
91
+ raise ValueError(
92
+ f"Invalid SMDA identifier in 'smda.stratigraphic_column': "
93
+ f"{strat.identifier}"
94
+ )
95
+ if str(strat.uuid) in INVALID_UUIDS:
96
+ raise ValueError(
97
+ f"Invalid SMDA UUID in 'smda.stratigraphic_column': {strat.uuid}"
98
+ )
99
+
100
+ # Check stratigraphy
101
+
102
+ if cfg.stratigraphy:
103
+ for key in cfg.stratigraphy:
104
+ if key.lower() in INVALID_STRAT_NAMES:
105
+ raise ValueError(
106
+ f"Invalid stratigraphy name in 'smda.stratigraphy': {key}"
107
+ )
108
+
109
+
110
+ def load_global_configuration_if_present(
111
+ path: Path, fmu_load: bool = False
112
+ ) -> GlobalConfiguration | None:
113
+ """Loads a global config/global variables at a path.
114
+
115
+ This loads via fmu-config, which is capable of loading a global _config_, which is
116
+ different from the global _variables_ in that it may still be in separate files
117
+ linked by the custom '!include' directive.
118
+
119
+ Args:
120
+ path: The path to the yaml file
121
+ fmu_load: Whether or not to load in the custom 'fmu' format. Default False.
122
+
123
+ Returns:
124
+ GlobalConfiguration instance or None.
125
+ """
126
+ loader = "fmu" if fmu_load else "standard"
127
+ try:
128
+ global_variables_dict = yaml_load(path, loader=loader)
129
+ global_config = GlobalConfiguration.model_validate(global_variables_dict)
130
+ logger.debug(f"Global variables at {path} has valid settings data")
131
+ except Exception:
132
+ logger.debug(f"Global variables at {path} does not have valid settings data")
133
+ return None
134
+ return global_config
135
+
136
+
137
+ def _find_global_variables_file(paths: list[Path]) -> GlobalConfiguration | None:
138
+ """Finds a valid global variables file, or not.
139
+
140
+ This is the _output_ file after fmuconfig is run.
141
+
142
+ Args:
143
+ paths: A list of Paths to check.
144
+
145
+ Returns:
146
+ A validated GlobalConfiguration or None.
147
+ """
148
+ for path in paths:
149
+ if not path.exists():
150
+ continue
151
+
152
+ global_variables_path = path
153
+ # If the path is a dir, and doesn't contain the right file, move on.
154
+ if path.is_dir():
155
+ global_variables_path = path / "global_variables.yml"
156
+ if not global_variables_path.exists():
157
+ continue
158
+
159
+ logger.info(f"Found global variables at {path}")
160
+ global_config = load_global_configuration_if_present(global_variables_path)
161
+ if not global_config:
162
+ continue
163
+ return global_config
164
+
165
+ return None
166
+
167
+
168
+ def _find_global_config_file(paths: list[Path]) -> GlobalConfiguration | None:
169
+ """Finds a valid global configuration file, or not.
170
+
171
+ This is the _input_ file, before fmuconfig is run.
172
+
173
+ Args:
174
+ paths: A list of Paths to check.
175
+
176
+ Returns:
177
+ A validated GlobalConfiguration or None.
178
+ """
179
+ for path in paths:
180
+ if not path.exists():
181
+ continue
182
+
183
+ logger.info(f"Found global config at {path}")
184
+ # May be global_config*.yml or global_master*.yml
185
+ for global_config_path in path.glob("**/global*.yml"):
186
+ global_config = load_global_configuration_if_present(
187
+ global_config_path, fmu_load=True
188
+ )
189
+ if not global_config:
190
+ continue
191
+ return global_config
192
+
193
+ return None
194
+
195
+
196
+ def find_global_config(
197
+ base_path: str | Path,
198
+ extra_output_paths: list[Path] | None = None,
199
+ extra_input_dirs: list[Path] | None = None,
200
+ strict: bool = True,
201
+ ) -> GlobalConfiguration | None:
202
+ """Try to locate a global configuration with valid masterdata in known location.
203
+
204
+ Extra paths may be provided
205
+
206
+ Args:
207
+ base_path: The path to the project root
208
+ extra_output_paths: A list of extra paths to a global _variables_.
209
+ extra_input_dirs: A list of extra dirs to a global _config_ might be.
210
+ strict: If True, valid data but invalid _content_ is disallowed, i.e. Drogon
211
+ data. Default True.
212
+
213
+ Returns:
214
+ A valid GlobalConfiguration instance, or None.
215
+ """
216
+ base_path = Path(base_path)
217
+
218
+ # Loads with 'fmu_load=False'
219
+ known_output_paths = [base_path / "fmuconfig/output/global_variables.yml"]
220
+ if extra_output_paths:
221
+ known_output_paths += extra_output_paths
222
+
223
+ global_config = _find_global_variables_file(known_output_paths)
224
+ if global_config:
225
+ if strict:
226
+ validate_global_configuration_strictly(global_config)
227
+ return global_config
228
+
229
+ # Loads with 'fmu_load=True'
230
+ known_input_paths = [base_path / "fmuconfig/input"]
231
+ if extra_input_dirs:
232
+ known_input_paths += extra_input_dirs
233
+
234
+ global_config = _find_global_config_file(known_input_paths)
235
+ if global_config:
236
+ if strict:
237
+ validate_global_configuration_strictly(global_config)
238
+ return global_config
239
+
240
+ logger.info("No global variables or config with valid settings data found.")
241
+ return None
fmu/settings/_init.py CHANGED
@@ -4,6 +4,8 @@ from pathlib import Path
4
4
  from textwrap import dedent
5
5
  from typing import Any, Final
6
6
 
7
+ from fmu.datamodels.fmu_results.global_configuration import GlobalConfiguration
8
+
7
9
  from ._fmu_dir import ProjectFMUDirectory, UserFMUDirectory
8
10
  from ._logging import null_logger
9
11
  from .models.project_config import ProjectConfig
@@ -66,7 +68,9 @@ def _create_fmu_directory(base_path: Path) -> None:
66
68
 
67
69
 
68
70
  def init_fmu_directory(
69
- base_path: str | Path, config_data: ProjectConfig | dict[str, Any] | None = None
71
+ base_path: str | Path,
72
+ config_data: ProjectConfig | dict[str, Any] | None = None,
73
+ global_config: GlobalConfiguration | None = None,
70
74
  ) -> ProjectFMUDirectory:
71
75
  """Creates and initializes a .fmu directory.
72
76
 
@@ -74,9 +78,11 @@ def init_fmu_directory(
74
78
  function.
75
79
 
76
80
  Args:
77
- base_path: Directory where .fmu should be created
81
+ base_path: Directory where .fmu should be created.
78
82
  config_data: Optional ProjectConfig instance or dictionary with configuration
79
- data
83
+ data.
84
+ global_config: Optional GlobaConfiguration instance with existing global config
85
+ data.
80
86
 
81
87
  Returns:
82
88
  Instance of FMUDirectory
@@ -98,12 +104,14 @@ def init_fmu_directory(
98
104
  fmu_dir.config.reset()
99
105
  if config_data:
100
106
  if isinstance(config_data, ProjectConfig):
101
- config_dict = config_data.model_dump()
102
- fmu_dir.update_config(config_dict)
103
- elif isinstance(config_data, dict):
104
- fmu_dir.update_config(config_data)
107
+ config_data = config_data.model_dump()
108
+ fmu_dir.update_config(config_data)
105
109
 
106
- logger.debug(f"Successfully initialized .fmu directory at '{fmu_dir}'")
110
+ if global_config:
111
+ for key, value in global_config.model_dump().items():
112
+ fmu_dir.set_config_value(key, value)
113
+
114
+ logger.info(f"Successfully initialized .fmu directory at '{fmu_dir}'")
107
115
  return fmu_dir
108
116
 
109
117
 
@@ -168,6 +168,25 @@ class LockManager(PydanticResourceManager[LockInfo]):
168
168
  return False
169
169
  return self._is_mine(self._cache) and not self._is_stale()
170
170
 
171
+ def ensure_can_write(self: Self) -> None:
172
+ """Raise PermissionError if another process currently holds the lock."""
173
+ try:
174
+ lock_info = self.load(force=True, store_cache=False)
175
+ except Exception:
176
+ lock_info = None
177
+
178
+ if (
179
+ self.exists
180
+ and lock_info is not None
181
+ and not self.is_acquired()
182
+ and not self._is_stale(lock_info=lock_info)
183
+ ):
184
+ raise PermissionError(
185
+ "Cannot write to .fmu directory because it is locked by "
186
+ f"{lock_info.user}@{lock_info.hostname} (PID: {lock_info.pid}). "
187
+ f"Lock expires at {time.ctime(lock_info.expires_at)}."
188
+ )
189
+
171
190
  def refresh(self: Self) -> None:
172
191
  """Refresh/extend the lock expiration time.
173
192
 
@@ -239,9 +258,11 @@ class LockManager(PydanticResourceManager[LockInfo]):
239
258
  except Exception:
240
259
  return None
241
260
 
242
- def _is_stale(self: Self) -> bool:
261
+ def _is_stale(self: Self, lock_info: LockInfo | None = None) -> bool:
243
262
  """Check if existing lock is stale (expired or process dead)."""
244
- lock_info = self._safe_load()
263
+ if lock_info is None:
264
+ lock_info = self._safe_load()
265
+
245
266
  if not lock_info:
246
267
  return True
247
268
 
@@ -98,6 +98,7 @@ class PydanticResourceManager(Generic[T]):
98
98
  Args:
99
99
  model: Validated Pydantic model instance
100
100
  """
101
+ self.fmu_dir._lock.ensure_can_write()
101
102
  json_data = model.model_dump_json(by_alias=True, indent=2)
102
103
  self.fmu_dir.write_text_file(self.relative_path, json_data)
103
104
  self._cache = model
fmu/settings/_version.py CHANGED
@@ -28,7 +28,7 @@ version_tuple: VERSION_TUPLE
28
28
  commit_id: COMMIT_ID
29
29
  __commit_id__: COMMIT_ID
30
30
 
31
- __version__ = version = '0.3.2'
32
- __version_tuple__ = version_tuple = (0, 3, 2)
31
+ __version__ = version = '0.4.0'
32
+ __version_tuple__ = version_tuple = (0, 4, 0)
33
33
 
34
34
  __commit_id__ = commit_id = None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fmu-settings
3
- Version: 0.3.2
3
+ Version: 0.4.0
4
4
  Summary: A library for managing FMU settings
5
5
  Author-email: Equinor <fg-fmu_atlas@equinor.com>
6
6
  License: GPL-3.0
@@ -17,7 +17,9 @@ Classifier: Natural Language :: English
17
17
  Requires-Python: >=3.11
18
18
  Description-Content-Type: text/markdown
19
19
  License-File: LICENSE
20
+ Requires-Dist: PyYAML
20
21
  Requires-Dist: annotated_types
22
+ Requires-Dist: fmu-config
21
23
  Requires-Dist: fmu-datamodels
22
24
  Requires-Dist: pydantic
23
25
  Provides-Extra: dev
@@ -27,6 +29,7 @@ Requires-Dist: pytest-cov; extra == "dev"
27
29
  Requires-Dist: pytest-mock; extra == "dev"
28
30
  Requires-Dist: pytest-xdist; extra == "dev"
29
31
  Requires-Dist: ruff; extra == "dev"
32
+ Requires-Dist: types-PyYAML; extra == "dev"
30
33
  Dynamic: license-file
31
34
 
32
35
  # fmu-settings
@@ -1,23 +1,24 @@
1
1
  fmu/__init__.py,sha256=htx6HlMme77I6pZ8U256-2B2cMJuELsu3JN3YM2Efh4,144
2
2
  fmu/settings/__init__.py,sha256=CkEE7al_uBCQO1lxBKN5LzyCwzzH5Aq6kkEIR7f-zTw,336
3
- fmu/settings/_fmu_dir.py,sha256=Br_hcfAXshiuDyWqG_qx5VXFpsCBJO1XDMPzdxxesoE,10684
4
- fmu/settings/_init.py,sha256=5CT7tV2XHz5wuLh97XozyLiKpwogrsfjpxm2dpn7KWE,4097
3
+ fmu/settings/_fmu_dir.py,sha256=XeZjec78q0IUOpBq-VMkKoWtzXwBeQi2qWRIh_SIFwU,10859
4
+ fmu/settings/_global_config.py,sha256=YEl0_51_ZG28Ix-Km0q7lDL0myOsD3a0Sqky8T5Swcg,8021
5
+ fmu/settings/_init.py,sha256=ucueS0BlEsM3MkX7IaRISloH4vF7-_ZKSphrORbHgJ4,4381
5
6
  fmu/settings/_logging.py,sha256=nEdmZlNCBsB1GfDmFMKCjZmeuRp3CRlbz1EYUemc95Y,1104
6
- fmu/settings/_version.py,sha256=e8NqPtZ8fggRgk3GPrqZ_U_BDV8aSULw1u_Gn9NNbnk,704
7
+ fmu/settings/_version.py,sha256=2_0GUP7yBCXRus-qiJKxQD62z172WSs1sQ6DVpPsbmM,704
7
8
  fmu/settings/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
9
  fmu/settings/types.py,sha256=aeXEsznBTT1YRRY_LSRqK1j2gmMmyLYYTGYl3a9fweU,513
9
10
  fmu/settings/_resources/__init__.py,sha256=LHYR_F7lNGdv8N6R3cEwds5CJQpkOthXFqsEs24vgF8,118
10
11
  fmu/settings/_resources/config_managers.py,sha256=IjOtS2lSU55GE_TWqHjbBPAzE8xQyVBvpHcfm0hTSnI,6822
11
- fmu/settings/_resources/lock_manager.py,sha256=_xzSJNF_qcpKpo8AxMfEgOhPxKXl3fZ2lRi0_y2eUEg,9206
12
- fmu/settings/_resources/pydantic_resource_manager.py,sha256=NV9qGnKaZ2RYt6o2NMaHvKyiZDIsxwD5y3y2a6QQtHw,3555
12
+ fmu/settings/_resources/lock_manager.py,sha256=zdv1BZJlgB1BO9NepAdjY-YZ1-57HEJcTApE4UVS-8M,9995
13
+ fmu/settings/_resources/pydantic_resource_manager.py,sha256=TbwpX0RPV0XAJ_fuVYCJTi00DBykvmvJH82B7bhREWo,3601
13
14
  fmu/settings/models/__init__.py,sha256=lRlXgl55ba2upmDzdvzx8N30JMq2Osnm8aa_xxTZn8A,112
14
15
  fmu/settings/models/_enums.py,sha256=SQUZ-2mQcTx4F0oefPFfuQzMKsKTSFSB-wq_CH7TBRE,734
15
16
  fmu/settings/models/_mappings.py,sha256=Z4Ex7MtmajBr6FjaNzmwDRwtJlaZZ8YKh9NDmZHRKPI,2832
16
17
  fmu/settings/models/lock_info.py,sha256=-oHDF9v9bDLCoFvEg4S6XXYLeo19zRAZ8HynCv75VWg,711
17
18
  fmu/settings/models/project_config.py,sha256=pxb54JmpXNMVAFUu_yJ89dNrYEk6hrPuFfFUpf84Jh0,1099
18
19
  fmu/settings/models/user_config.py,sha256=dWFTcZY6UnEgNTuGqB-izraJ657PecsW0e0Nt9GBDhI,2666
19
- fmu_settings-0.3.2.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
20
- fmu_settings-0.3.2.dist-info/METADATA,sha256=CC-jegtLPAS2vpUajvXTd3D_Fyow5q62Dwy4WDH4ypA,2024
21
- fmu_settings-0.3.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
22
- fmu_settings-0.3.2.dist-info/top_level.txt,sha256=Z-FIY3pxn0UK2Wxi9IJ7fKoLSraaxuNGi1eokiE0ShM,4
23
- fmu_settings-0.3.2.dist-info/RECORD,,
20
+ fmu_settings-0.4.0.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
21
+ fmu_settings-0.4.0.dist-info/METADATA,sha256=btR8JyHVO9zr_ghzoKoV3I016ePj_Y2ijakSnFnbLMA,2116
22
+ fmu_settings-0.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
23
+ fmu_settings-0.4.0.dist-info/top_level.txt,sha256=Z-FIY3pxn0UK2Wxi9IJ7fKoLSraaxuNGi1eokiE0ShM,4
24
+ fmu_settings-0.4.0.dist-info/RECORD,,