]> git.ipfire.org Git - thirdparty/knot-resolver.git/commitdiff
'cache-clear' remade to 'cache/clear'
authorAleš Mrázek <ales.mrazek@nic.cz>
Tue, 6 Feb 2024 13:00:06 +0000 (14:00 +0100)
committerAleš Mrázek <ales.mrazek@nic.cz>
Wed, 14 Feb 2024 12:34:15 +0000 (13:34 +0100)
doc/config-cache.rst
doc/manager-api.rst
doc/manager-client.rst
manager/knot_resolver_manager/cli/cmd/cache.py [moved from manager/knot_resolver_manager/cli/cmd/cache_clear.py with 54% similarity]
manager/knot_resolver_manager/server.py
manager/tests/packaging/interactive/cache-clear.sh [moved from manager/tests/packaging/interactive/cahe-clear.sh with 73% similarity]

index 6469b5ce615b189fd5569e3736f27ed2d46336ce..2a0273ff464774e48ad236a8aa7b82f9617e1613 100644 (file)
@@ -66,7 +66,7 @@ There are two specifics to purging cache records matching specified criteria:
 
    .. code-block:: none
 
-      $ kresctl cache-clear example.com.
+      $ kresctl cache clear example.com.
 
 .. [#] This is a consequence of DNSSEC negative cache which relies on proofs of non-existence on various owner nodes. It is impossible to efficiently flush part of DNS zones signed with NSEC3.
 
index bafa86df0d2ac523c029977b0f2a3c1d886f1e9c..80dcc4afaba946d14354e8943a6e651af586bc46 100644 (file)
@@ -88,7 +88,7 @@ List of API endpoints
 - ``GET /metrics`` provides Prometheus metrics
 - ``GET /`` static response that could be used to determine, whether the Manager is running
 - ``POST /stop`` gracefully stops the Manager, empty request body
-- ``POST /cache-clear`` purges cache records matching the specified criteria, see :ref:`cache clearing <config-cache-clear>`
+- ``POST /cache/clear`` purges cache records matching the specified criteria, see :ref:`cache clearing <config-cache-clear>`
 - ``{GET,PUT,DELETE,PATCH} /v1/config`` allows reading and modifying current configuration
 
 
index 2e50c882c684d701a339c801b6aabf81f3e8b2b0..c7f90346e792469f7bbaedd265de4cf59bc2bf7a 100644 (file)
@@ -158,7 +158,7 @@ Only one of these arguments can be selected during the execution of a single ``k
 
         $ kresctl metrics ./metrics/data.txt
 
-.. option:: cache-clear
+.. option:: cache clear
 
         Purge cache records matching the specified criteria.
 
@@ -187,9 +187,9 @@ Only one of these arguments can be selected during the execution of a single ``k
 
     .. code-block:: bash
 
-        $ kresctl cache-clear
-        $ kresctl cache-clear example.com.
-        $ kresctl cache-clear --exact-name example.com.
+        $ kresctl cache clear
+        $ kresctl cache clear example.com.
+        $ kresctl cache clear --exact-name example.com.
 
 
 .. option:: schema
similarity index 54%
rename from manager/knot_resolver_manager/cli/cmd/cache_clear.py
rename to manager/knot_resolver_manager/cli/cmd/cache.py
index de5546584d105272981396c120c6b8ce4449cc61..24757b3619e595e3d57ed0e980ab55b499e9169b 100644 (file)
@@ -1,6 +1,7 @@
 import argparse
 import sys
-from typing import Any, Dict, List, Tuple, Type
+from enum import Enum
+from typing import Any, Dict, List, Optional, Tuple, Type
 
 from knot_resolver_manager.cli.command import Command, CommandArgs, CompWords, register_command
 from knot_resolver_manager.datamodel.cache_schema import CacheClearRPCSchema
@@ -9,45 +10,51 @@ from knot_resolver_manager.utils.modeling.parsing import DataFormat
 from knot_resolver_manager.utils.requests import request
 
 
+class CacheOperations(Enum):
+    CLEAR = 0
+
+
 @register_command
-class CacheClearCommand(Command):
+class CacheCommand(Command):
     def __init__(self, namespace: argparse.Namespace) -> None:
         super().__init__(namespace)
+        self.operation: Optional[CacheOperations] = namespace.operation if hasattr(namespace, "operation") else None
 
-        config_dict: Dict[str, Any] = {"exact-name": namespace.exact_name}
-
+        # CLEAR operation
+        self.clear_dict: Dict[str, Any] = {}
+        if hasattr(namespace, "exact_name"):
+            self.clear_dict["exact-name"] = namespace.exact_name
         if hasattr(namespace, "name"):
-            config_dict["name"] = namespace.name
+            self.clear_dict["name"] = namespace.name
         if hasattr(namespace, "rr_type"):
-            config_dict["rr-type"] = namespace.rr_type
+            self.clear_dict["rr-type"] = namespace.rr_type
         if hasattr(namespace, "chunk_size"):
-            config_dict["chunk-size"] = namespace.chunk_size
-
-        try:
-            self.config = CacheClearRPCSchema(config_dict)
-        except (AggregateDataValidationError, DataValidationError) as e:
-            print(e, file=sys.stderr)
-            sys.exit(1)
+            self.clear_dict["chunk-size"] = namespace.chunk_size
 
     @staticmethod
     def register_args_subparser(
         subparser: "argparse._SubParsersAction[argparse.ArgumentParser]",
     ) -> Tuple[argparse.ArgumentParser, "Type[Command]"]:
-        cache_clear = subparser.add_parser("cache-clear", help="Purge cache records matching specified criteria.")
-        cache_clear.set_defaults(exact_name=False)
-        cache_clear.add_argument(
+        cache_parser = subparser.add_parser("cache", help="Performs operations on the running resolver's cache.")
+
+        config_subparsers = cache_parser.add_subparsers(help="operation type")
+
+        # CLEAR operation
+        clear_subparser = config_subparsers.add_parser("clear", help="Purge cache records matching specified criteria.")
+        clear_subparser.set_defaults(operation=CacheOperations.CLEAR, exact_name=False)
+        clear_subparser.add_argument(
             "--exact-name",
             help="If set, only records with the same name are removed.",
             action="store_true",
             dest="exact_name",
         )
-        cache_clear.add_argument(
+        clear_subparser.add_argument(
             "--rr-type",
             help="Optional, you may additionally specify the type to remove, but that is only supported with '--exact-name' flag set.",
             action="store",
             type=str,
         )
-        cache_clear.add_argument(
+        clear_subparser.add_argument(
             "--chunk-size",
             help="Optional, the number of records to remove in one round; default: 100."
             " The purpose is not to block the resolver for long. The resolver repeats the command after one millisecond until all matching data are cleared.",
@@ -55,7 +62,7 @@ class CacheClearCommand(Command):
             type=int,
             default=100,
         )
-        cache_clear.add_argument(
+        clear_subparser.add_argument(
             "name",
             type=str,
             nargs="?",
@@ -63,15 +70,26 @@ class CacheClearCommand(Command):
             default=None,
         )
 
-        return cache_clear, CacheClearCommand
+        return cache_parser, CacheCommand
 
     @staticmethod
     def completion(args: List[str], parser: argparse.ArgumentParser) -> CompWords:
         return {}
 
     def run(self, args: CommandArgs) -> None:
-        body: str = DataFormat.JSON.dict_dump(self.config.get_unparsed_data())
-        response = request(args.socket, "POST", "cache-clear", body)
+        if not self.operation:
+            args.subparser.print_help()
+            sys.exit()
+
+        if self.operation == CacheOperations.CLEAR:
+            try:
+                validated = CacheClearRPCSchema(self.clear_dict)
+            except (AggregateDataValidationError, DataValidationError) as e:
+                print(e, file=sys.stderr)
+                sys.exit(1)
+
+            body: str = DataFormat.JSON.dict_dump(validated.get_unparsed_data())
+            response = request(args.socket, "POST", "cache/clear", body)
 
         if response.status != 200:
             print(response, file=sys.stderr)
index 47a11d6d0d97e3b2e469deceb8e9bc31db857dd6..4b507b459124fa9897ca0b1e917543af12b62384 100644 (file)
@@ -25,10 +25,7 @@ from knot_resolver_manager.config_store import ConfigStore
 from knot_resolver_manager.constants import DEFAULT_MANAGER_CONFIG_FILE, PID_FILE_NAME, init_user_constants
 from knot_resolver_manager.datamodel.cache_schema import CacheClearRPCSchema
 from knot_resolver_manager.datamodel.config_schema import KresConfig, get_rundir_without_validation
-from knot_resolver_manager.datamodel.globals import (
-    Context,
-    set_global_validation_context,
-)
+from knot_resolver_manager.datamodel.globals import Context, set_global_validation_context
 from knot_resolver_manager.datamodel.management_schema import ManagementSchema
 from knot_resolver_manager.exceptions import CancelStartupExecInsteadException, KresManagerException
 from knot_resolver_manager.kresd_controller import get_best_controller_implementation
@@ -333,7 +330,7 @@ class Server:
                 web.get("/schema", self._handler_schema),
                 web.get("/schema/ui", self._handle_view_schema),
                 web.get("/metrics", self._handler_metrics),
-                web.post("/cache-clear", self._handler_cache_clear),
+                web.post("/cache/clear", self._handler_cache_clear),
             ]
         )
 
similarity index 73%
rename from manager/tests/packaging/interactive/cahe-clear.sh
rename to manager/tests/packaging/interactive/cache-clear.sh
index 4c08612d39f08d002f582f680142b1819ccf6489..f50cadab4081f9c6984d197042bc68ab2aefc2d3 100755 (executable)
@@ -1,14 +1,14 @@
 #!/bin/bash
 
 # clear full cache
-kresctl cache-clear
+kresctl cache clear
 if [ "$?" -ne "0" ]; then
        echo "Could not clear full cache"
        exit 1
 fi
 
 # clear just example.com. AAAA record
-kresctl cache-clear --exact-name --rr-type AAAA example.com.
+kresctl cache clear --exact-name --rr-type AAAA example.com.
 if [ "$?" -ne "0" ]; then
        echo "Could not clear example.com. AAAA record"
        exit 1