File: model.py

package info (click to toggle)
zabbix-cli 3.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,980 kB
  • sloc: python: 19,920; makefile: 5
file content (793 lines) | stat: -rw-r--r-- 27,230 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
# Authors:
# rafael@postgresql.org.es / http://www.postgresql.org.es/
#
# Copyright (c) 2014-2016 USIT-University of Oslo
#
# This file is part of Zabbix-CLI
# https://github.com/rafaelma/zabbix-cli
#
# Zabbix-CLI is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Zabbix-CLI is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Zabbix-CLI.  If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations

import functools
import logging
from pathlib import Path
from typing import Any
from typing import Optional
from typing import TypeVar
from typing import Union
from typing import overload

from pydantic import AliasChoices
from pydantic import ConfigDict
from pydantic import Field
from pydantic import PrivateAttr
from pydantic import RootModel
from pydantic import SecretStr
from pydantic import SerializationInfo
from pydantic import TypeAdapter
from pydantic import ValidationError
from pydantic import field_serializer
from pydantic import field_validator
from pydantic import model_validator
from typing_extensions import Self

from zabbix_cli._v2_compat import CONFIG_PRIORITY as CONFIG_PRIORITY_LEGACY
from zabbix_cli.bulk import BulkRunnerMode
from zabbix_cli.config.base import BaseModel
from zabbix_cli.config.commands import CommandConfig
from zabbix_cli.config.constants import AUTH_FILE
from zabbix_cli.config.constants import AUTH_TOKEN_FILE
from zabbix_cli.config.constants import HISTORY_FILE
from zabbix_cli.config.constants import LOG_FILE
from zabbix_cli.config.constants import SESSION_FILE
from zabbix_cli.config.constants import OutputFormat
from zabbix_cli.config.constants import SecretMode
from zabbix_cli.config.utils import find_config
from zabbix_cli.config.utils import fmt_deprecated_fields
from zabbix_cli.config.utils import get_deprecated_fields_set
from zabbix_cli.config.utils import load_config_conf
from zabbix_cli.config.utils import load_config_toml
from zabbix_cli.config.utils import replace_deprecated_fields
from zabbix_cli.dirs import EXPORT_DIR
from zabbix_cli.exceptions import ConfigError
from zabbix_cli.exceptions import ConfigOptionNotFound
from zabbix_cli.exceptions import PluginConfigTypeError
from zabbix_cli.exceptions import ZabbixCLIFileError
from zabbix_cli.logs import LogLevelStr
from zabbix_cli.pyzabbix.enums import ExportFormat
from zabbix_cli.utils.fs import mkdir_if_not_exists

T = TypeVar("T")

logger = logging.getLogger("zabbix_cli.config")


class APIConfig(BaseModel):
    """Configuration for the Zabbix API."""

    url: str = Field(
        default="https://zabbix.example.com",
        # Changed in V3: zabbix_api_url -> url
        validation_alias=AliasChoices("url", "zabbix_api_url"),
        description="URL of the Zabbix API host. Should not include `/api_jsonrpc.php`.",
        examples=["https://zabbix.example.com"],
    )
    username: str = Field(
        default="Admin",
        # Changed in V3: system_id -> username
        validation_alias=AliasChoices("username", "system_id"),
        description="Username for the Zabbix API.",
        examples=["Admin"],
    )
    password: SecretStr = Field(
        default=SecretStr(""),
        description="Password for user.",
        examples=["zabbix"],
    )
    auth_token: SecretStr = Field(
        default=SecretStr(""),
        description="API auth token.",
        examples=["API_TOKEN_123"],
    )
    verify_ssl: Union[bool, Path] = Field(
        default=True,
        # Changed in V3: cert_verify -> verify_ssl
        validation_alias=AliasChoices("verify_ssl", "cert_verify"),
        description="Verify SSL certificate of the Zabbix API host. Can also be a path to a CA bundle.",
    )
    timeout: Optional[int] = Field(
        default=0,
        description="API request timeout in seconds.",
    )

    @model_validator(mode="after")
    def _validate_model(self) -> Self:
        # Convert 0 timeout to None
        if self.timeout == 0:
            self.timeout = None
        return self

    @field_serializer("timeout", when_used="json")
    def _serialize_timeout(self, timeout: Optional[int]) -> int:
        """Represent None timeout as 0 in serialized output."""
        return timeout if timeout is not None else 0

    @field_serializer("password", "auth_token", when_used="json")
    def dump_secret(self, v: Any, info: SerializationInfo) -> Any:
        """Dump secrets if enabled in serialization context."""
        if not isinstance(v, SecretStr):
            logger.debug("%s from field %s is not a SecretStr", v, info)
            return v

        mode = SecretMode.from_context(info.context)
        if mode == SecretMode.PLAIN:
            return v.get_secret_value()
        elif mode == SecretMode.MASK:
            return str(v)  # SecretStr masks by default
        else:  # fall back on hidden otherwise
            return ""


class OutputConfig(BaseModel):
    """Configuration for output formatting."""

    format: OutputFormat = Field(
        default=OutputFormat.TABLE,
        description="Default output format.",
    )
    color: bool = Field(
        default=True,
        description="Use colors in terminal output.",
    )
    paging: bool = Field(
        default=False,
        description="Use paging in terminal output.",
    )
    theme: str = Field(
        default="default",
        description="Color theme to use.",
        exclude=True,
    )

    @field_validator("format", mode="before")
    @classmethod
    def _ignore_enum_case(cls, v: Any) -> Any:
        """Ignore case when validating enum value."""
        if isinstance(v, str):
            return v.lower()
        return v


class AutoUpdateConfig(BaseModel):
    """Configuration for automatic config updates."""

    enabled: bool = Field(
        default=True,
        description="Automatically update config with new config fields and migrate deprecated fields on startup.",
    )
    backup: bool = Field(
        default=True,
        description="Create a backup of the config file before updating it.",
    )


class AppConfig(BaseModel):
    """Configuration for app defaults and behavior."""

    # Auth
    use_session_file: bool = Field(
        default=True,
        validation_alias=AliasChoices("use_session_file", "use_auth_token_file"),
        description="Use session file for storing API session IDs for persistent sessions.",
    )

    session_file: Path = Field(
        default=SESSION_FILE,
        description="Path to session file.",
    )
    auth_token_file: Path = Field(
        default=AUTH_TOKEN_FILE,
        description="Path to legacy auth token file.",
        deprecated=True,
    )

    use_auth_file: bool = Field(
        default=True,
        description="Look for user credentials stored in plaintext in auth file.",
    )
    auth_file: Path = Field(
        default=AUTH_FILE,
        description="Path to auth file.",
    )
    # TODO: rename symbol to allow_insecure_auth
    allow_insecure_auth_file: bool = Field(
        default=True,
        # Changed in V3: allow_insecure_authfile -> allow_insecure_auth_file
        validation_alias=AliasChoices(
            "allow_insecure_auth",
            "allow_insecure_auth_file",
            "allow_insecure_authfile",
        ),
    )
    config_auto_update: AutoUpdateConfig = Field(
        default_factory=AutoUpdateConfig,
        description="Configuration for automatic config updates.",
    )

    # History
    history: bool = Field(
        default=True,
        description="Enable command history.",
    )
    history_file: Path = Field(
        default=HISTORY_FILE,
        description="Path to history file.",
    )

    bulk_mode: BulkRunnerMode = Field(
        default=BulkRunnerMode.STRICT,
        description="Bulk mode error handling.",
    )

    # Deprecated/moved fields
    output_format: OutputFormat = Field(
        default=OutputFormat.TABLE,
        deprecated=True,
        exclude=True,
        json_schema_extra={"replacement": "app.output.format"},
    )
    use_colors: bool = Field(
        default=True,
        deprecated=True,
        exclude=True,
        json_schema_extra={"replacement": "app.output.color"},
    )
    use_paging: bool = Field(
        default=False,
        deprecated=True,
        exclude=True,
        json_schema_extra={"replacement": "app.output.paging"},
    )
    system_id: str = Field(
        default="",
        validation_alias=AliasChoices("username", "system_id"),
        deprecated=True,
        exclude=True,
        json_schema_extra={"replacement": "api.username"},
    )
    default_hostgroups: list[str] = Field(
        default=[],
        validation_alias=AliasChoices("default_hostgroups", "default_hostgroup"),
        deprecated=True,
        exclude=True,
        json_schema_extra={"replacement": "app.commands.create_host.hostgroups"},
    )
    default_admin_usergroups: list[str] = Field(
        default=[],
        validation_alias=AliasChoices(
            "default_admin_usergroups", "default_admin_usergroup"
        ),
        description=(
            "Default user groups to give read/write permissions to groups "
            "created with `create_hostgroup` and `create_templategroup` "
            "when `--rw-groups` option is not provided."
        ),
        deprecated=True,
        exclude=True,
        json_schema_extra={"replacement": "app.commands.create_hostgroup.rw_groups"},
    )
    default_create_user_usergroups: list[str] = Field(
        default=[],
        validation_alias=AliasChoices(
            "default_create_user_usergroups", "default_create_user_usergroup"
        ),
        deprecated=True,
        exclude=True,
        json_schema_extra={
            "replacement": [
                "app.commands.create_user.usergroups",
                "app.commands.create_hostgroup.ro_groups",
            ]
        },
    )
    default_notification_users_usergroups: list[str] = Field(
        default=[],
        validation_alias=AliasChoices(
            "default_notification_users_usergroups",
            "default_notification_users_usergroup",
        ),
        deprecated=True,
        exclude=True,
        json_schema_extra={
            "replacement": "app.commands.create_notification_user.usergroups"
        },
    )
    export_directory: Path = Field(
        default=EXPORT_DIR,
        deprecated=True,
        exclude=True,
        json_schema_extra={"replacement": "app.commands.export.directory"},
    )
    export_format: ExportFormat = Field(
        default=ExportFormat.JSON,
        deprecated=True,
        exclude=True,
        json_schema_extra={"replacement": "app.commands.export.format"},
    )
    export_timestamps: bool = Field(
        default=False,
        deprecated=True,
        exclude=True,
        json_schema_extra={"replacement": "app.commands.export.timestamps"},
    )

    # Legacy options
    legacy_json_format: bool = Field(
        default=False,
        description="Use legacy JSON format.",
    )
    """Mimicks V2 behavior where the JSON output was ALWAYS a dict, where
    each entry was stored under the keys "0", "1", "2", etc.
    """

    is_legacy: bool = Field(  # TODO: use PrivateAttr instead of Field
        default=False,
        exclude=True,
    )
    """Marks whether the configuration was loaded from a legacy config file."""

    # Sub-models
    commands: CommandConfig = Field(default_factory=CommandConfig)
    output: OutputConfig = Field(default_factory=OutputConfig)

    @field_validator(
        "default_admin_usergroups",
        "default_create_user_usergroups",
        "default_hostgroups",
        "default_notification_users_usergroups",
        mode="before",
    )
    @classmethod
    def _validate_maybe_comma_separated(cls, v: Any) -> Any:
        """Validate argument that can be a single comma-separated values string
        or a list of strings.

        Used for backwards-compatibility with V2 config files, where multiple arguments
        were specified as comma-separated strings.
        """
        if isinstance(v, str):
            return v.strip().split(",")
        return v

    @field_validator("output_format", mode="before")
    @classmethod
    def _ignore_enum_case(cls, v: Any) -> Any:
        """Ignore case when validating enum value."""
        if isinstance(v, str):
            return v.lower()
        return v

    @model_validator(mode="after")
    def ensure_history_file(self) -> Self:
        if not self.history:
            return self

        if self.history_file.exists():
            if self.history_file.is_file():
                return self
            raise ConfigError(
                f"History file {self.history_file} is a directory, not a file. Disable history or specify a different path in the configuration file."
            )

        # If user passes in path to non-existent directory, we have to create that too
        # TODO: add some abstraction for creating files & directories and raising exceptions
        try:
            mkdir_if_not_exists(self.history_file.parent)
        except ZabbixCLIFileError as e:
            # TODO: print path to config file in error message
            raise ConfigError(
                f"Unable to create history file {self.history_file}. Disable history or specify a different path in the configuration file."
            ) from e
        return self


class LoggingConfig(BaseModel):
    """Configuration for application logs."""

    enabled: bool = Field(
        default=True,
        # Changed in V3: logging -> enabled (we also allow enable [why?])
        validation_alias=AliasChoices("logging", "enabled", "enable"),
        description="Enable logging.",
    )
    log_level: LogLevelStr = Field(
        default="INFO",
        description="Log level.",
    )
    log_file: Optional[Path] = Field(
        # TODO: define this default path elsewhere
        default=LOG_FILE,
        description=(
            "File for storing logs. "
            "Can be omitted to log to stderr (**warning:** NOISY)."
        ),
    )

    @field_validator("log_file", mode="before")
    @classmethod
    def _empty_string_is_none(cls, v: Any) -> Any:
        """Passing in an empty string to `log_file` sets it to `None`,
        while omitting the option altogether sets it to the default.

        Examples:
        -------
        To get `LoggingConfig.log_file == None`:

        ```toml
        [logging]
        log_file = ""
        ```

        To get `LoggingConfig.log_file == <default_log_file>`:

        ```toml
        [logging]
        # log_file = ""
        ```
        """
        if v == "":
            return None
        return v


# Can consider moving this elsewhere
@functools.cache
def _get_type_adapter(type: type[T]) -> TypeAdapter[T]:
    """Get a type adapter for a given type."""
    return TypeAdapter(type)


NotSet = object()


class PluginConfig(BaseModel):
    module: str = ""
    """Name or path to module to load.

    Should always be specified for plugins loaded from local modules.
    Can be omitted for plugins loaded from entry points.
    TOML table name is used as the module name for entry point plugins."""

    enabled: bool = True
    optional: bool = False
    """Do not raise an error if the plugin fails to load."""

    model_config = ConfigDict(extra="allow")

    # No default no type
    @overload
    def get(self, key: str) -> Any: ...

    # Type with no default
    @overload
    def get(self, key: str, *, type: type[T]) -> T: ...

    # No type with default
    @overload
    def get(self, key: str, default: T) -> Any | T: ...

    # Type with default
    @overload
    def get(
        self,
        key: str,
        default: T,
        type: type[T],
    ) -> T: ...

    # Union type with no default
    @overload
    def get(
        self,
        key: str,
        *,
        type: Optional[type[T]],
    ) -> Optional[T]: ...

    # Union type with default
    @overload
    def get(
        self,
        key: str,
        default: Optional[T],
        type: Optional[type[T]],
    ) -> Optional[T]: ...

    def get(
        self,
        key: str,
        default: Union[T, Any] = NotSet,
        type: Optional[type[T]] = object,
    ) -> Union[T, Optional[T], Any]:
        """Get a plugin configuration value by key.

        Optionally validate the value as a specific type.
        """
        try:
            if default is not NotSet:
                attr = getattr(self, key, default)
            else:
                attr = getattr(self, key)
            if type is object:
                return attr
            adapter = _get_type_adapter(type)
            return adapter.validate_python(attr)
        except AttributeError:
            raise ConfigOptionNotFound(
                f"Plugin configuration key '{key}' not found"
            ) from None
        except ValidationError as e:
            raise PluginConfigTypeError(
                f"Plugin config key '{key}' failed to validate as type {type}: {e}"
            ) from e

    def set(self, key: str, value: Any) -> None:
        """Set a plugin configuration value by key."""
        setattr(self, key, value)


class PluginsConfig(RootModel[dict[str, PluginConfig]]):
    root: dict[str, PluginConfig] = Field(default_factory=dict)

    def get(self, key: str, *, strict: bool = False) -> Optional[PluginConfig]:
        """Get a plugin configuration by name."""
        conf = self.root.get(key)
        if conf is None and strict:
            raise ConfigError(f"Plugin {key} not found in configuration")
        return conf


class Config(BaseModel):
    """Configuration for the application."""

    api: APIConfig = Field(
        default_factory=APIConfig,
        # Changed in V3: zabbix_api -> api
        validation_alias=AliasChoices("api", "zabbix_api"),
    )
    app: AppConfig = Field(
        default_factory=AppConfig,
        # Changed in V3: zabbix_config -> app
        validation_alias=AliasChoices("app", "zabbix_config"),
    )
    logging: LoggingConfig = Field(default_factory=LoggingConfig)
    plugins: PluginsConfig = Field(default_factory=PluginsConfig)

    config_path: Optional[Path] = Field(default=None, exclude=True)

    _deprecated_fields_migrated: bool = PrivateAttr(default=False)

    @property
    def sample(self) -> bool:
        # No fields set means this is a sample config
        return not bool(self.model_fields_set)

    @model_validator(mode="after")
    def _set_deprecated_fields_in_new_location(self) -> Self:
        """Set values specified on deprecated fields in their new location
        and optionally update the config file on disk.

        I.e. `app.username` -> `api.username`.
             `app.output_format` -> `app.output.format`.

        Only updates new fields if the old field is set and the new field is not.
        """
        if self._deprecated_fields_migrated:
            return self

        # Guard against failure in case we have a config that cannot be updated
        # After all, this validator is added for _increased_ compatibility, not decreased
        try:
            replace_deprecated_fields(self)
            self.check_emit_upgrade_instructions()
            if self.app.config_auto_update.enabled:
                self.dump_updated_config()
        except Exception as e:
            logger.error("Failed to update deprecated fields in config: %s", e)

        # Mark as migrated even if we failed to avoid repeated attempts
        self._deprecated_fields_migrated = True
        return self

    @classmethod
    def sample_config(cls) -> Config:
        """Get a sample configuration."""
        return cls()

    @classmethod
    def from_file(
        cls, filename: Optional[Path] = None, *, init: bool = False
    ) -> Config:
        """Load configuration from a file.

        Attempts to find a config file to load if none is specified.

        Prioritizes V3 .toml config files, but falls back
        to legacy V2 .conf config files if no .toml config file can be found.
        """
        if filename:
            fp = filename
        else:
            fp = find_config(filename)
            if (
                not fp
            ):  # We didn't find a .toml file, so try to find a legacy .conf file
                fp = find_config(filename, CONFIG_PRIORITY_LEGACY)

        # Failed to find both .toml and .conf files
        if not fp or not fp.exists():
            if init:
                from zabbix_cli.config.utils import init_config

                return init_config(config_file=filename)
            else:
                return cls.sample_config()

        if fp.suffix == ".conf":
            return cls.from_conf_file(fp)
        else:
            return cls.from_toml_file(fp)

    @classmethod
    def from_toml_file(cls, filename: Path) -> Config:
        """Load configuration from a TOML file."""
        conf = load_config_toml(filename)
        try:
            return cls(**conf, config_path=filename)
        except ValidationError as e:
            raise ConfigError(f"Invalid configuration file {filename}: {e}") from e
        except Exception as e:
            raise ConfigError(
                f"Failed to load configuration file {filename}: {e}"
            ) from e

    @classmethod
    def from_conf_file(cls, filename: Path) -> Config:
        """Load configuration from a legacy .conf file."""
        logging.info("Using legacy config file (%s)", filename)
        conf = load_config_conf(filename)
        # Use legacy JSON format if we load from a legacy .conf file
        # and mark the loaded config as stemming from a legacy config file
        conf.setdefault("zabbix_config", {}).setdefault("legacy_json_format", True)
        conf.setdefault("zabbix_config", {}).setdefault("is_legacy", True)
        try:
            return cls(**conf, config_path=filename)
        except ValidationError as e:
            raise ConfigError(
                f"Failed to validate legacy configuration file {filename}: {e}"
            ) from e
        except Exception as e:
            raise ConfigError(
                f"Failed to load legacy configuration file {filename}: {e}"
            ) from e

    def as_toml(self, secrets: SecretMode = SecretMode.MASK) -> str:
        """Dump the configuration to a TOML string."""
        import tomli_w

        try:
            return tomli_w.dumps(
                self.model_dump(
                    mode="json",
                    exclude_none=True,  # we shouldn't have any, but just in case
                    context={"secrets": secrets},
                )
            )
        except Exception as e:
            raise ConfigError(f"Failed to serialize configuration to TOML: {e}") from e

    def dump_to_file(
        self, filename: Path, secrets: SecretMode = SecretMode.HIDE
    ) -> None:
        """Dump the configuration to a TOML file."""
        try:
            mkdir_if_not_exists(filename.parent)
            filename.write_text(self.as_toml(secrets=secrets))
        except OSError as e:
            raise ConfigError(
                f"Failed to write configuration file {filename}: {e}"
            ) from e

    def check_emit_upgrade_instructions(self) -> None:
        from zabbix_cli.output.console import warning

        # TODO: Detmermine whether or not to prefix command with `zabbix-cli`
        #       based on whether or not we are in the REPL

        # Legacy configs provide different instructions
        # and we cannot use the same heuristics for determining deprecations
        if self.app.is_legacy:
            warning(
                "Your configuration file is from an older version of Zabbix-CLI.\n"
                "  To update your config file to the new format, run:\n"
                "  [command]zabbix-cli migrate_config[/]\n"
                "  For more information, see the documentation."
            )
            return

        # Auto-updates do not require user intervention
        if self.app.config_auto_update.enabled:
            return

        deprecated_fields = get_deprecated_fields_set(self)
        if not deprecated_fields:
            return

        # Deprecated fields have no replacements – nothing to inform about
        # NOTE: unless we want to provide a way to remove deprecated fields?
        if all(not field.replacement for field in deprecated_fields):
            return

        warning(
            "Your configuration file contains deprecated options.\n"
            "  To update your config file with the new options, run:\n"
            "  [command]zabbix-cli update_config[/]\n"
            "  For more information, see the documentation."
        )

    def dump_updated_config(self, config_file: Optional[Path] = None) -> None:
        """Update deprecated fields in the configuration to their new location.

        Uses the current config values to update the config file on disk.
        """
        from zabbix_cli.output.console import info
        from zabbix_cli.output.console import success
        from zabbix_cli.output.formatting.path import path_link

        deprecated_fields = get_deprecated_fields_set(self)
        if not deprecated_fields:
            return  # no deprecated fields
        elif not any(field.replacement for field in deprecated_fields):
            return  # no replacements for deprecated fields

        config_file = config_file or self.config_path
        if not config_file:
            logger.warning("Cannot update configuration file: no config file path set.")
            return

        if self.app.config_auto_update.backup:
            backup_file = config_file.with_suffix(config_file.suffix + ".bak")
            try:
                backup_file.write_text(config_file.read_text())
            except OSError as e:
                raise ConfigError(
                    f"Failed to create backup of config file {config_file} "
                    f"before updating it: {e}. "
                    "Disable backups with [option]app.config_auto_update.backup=false[/] "
                    "to proceed without a backup."
                ) from e
            logger.info("Created backup of config file at %s", backup_file)

        try:
            self.dump_to_file(config_file, secrets=SecretMode.PLAIN)
        except ConfigError as e:
            raise ConfigError(
                f"Failed to update config file {config_file} with new fields: {e}. "
                "Disable automatic config updates with [option]app.config_auto_update.enabled=false[/] "
                "to proceed without automatic updates."
            ) from e

        success(f"Updated config file {path_link(config_file)}.")
        info(f"Deprecated fields updated:\n{fmt_deprecated_fields(deprecated_fields)}")