Debian Codegraph @

ansible_collections/community/clickhouse/plugins/modules/clickhouse_quota.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2025, John Garland (@johnnyg) <[email protected]>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 DOCUMENTATION = r"""
12 ---
13 module: clickhouse_quota
14
15 short_description: Creates or removes a ClickHouse quota
16
17 description:
18 - Creates or removes a ClickHouse quota.
19
20 attributes:
21 check_mode:
22 description: Supports check_mode.
23 support: full
24
25 version_added: '1.1.0'
26
27 author:
28 - John Garland (@johnnyg)
29
30 extends_documentation_fragment:
31 - community.clickhouse.client_inst_opts
32
33 options:
34 state:
35 description:
36 - Quota state.
37 - V(present) creates the quota if it does not exist.
38 - V(absent) deletes the quota if it exists.
39 type: str
40 choices: ['present', 'absent']
41 default: 'present'
42 name:
43 description:
44 - Quota name to add or remove.
45 type: str
46 required: true
47 cluster:
48 description:
49 - Run the command on all cluster hosts.
50 - If the cluster is not configured, the command will crash with an error.
51 type: str
52 keyed_by:
53 description:
54 - Keys the quota by the specified key (default is to not key).
55 type: str
56 choices:
57 - user_name
58 - ip_address
59 - client_key
60 - client_key,user_name
61 - client_key,ip_address
62 limits:
63 description:
64 - The limits that this quota should enforce.
65 type: list
66 elements: dict
67 suboptions:
68 randomized_start:
69 description:
70 - Whether this interval's start should be randomized.
71 - Intervals always start at the same time if not randomized.
72 type: bool
73 default: false
74 interval:
75 description:
76 - The interval to apply the following quotas on.
77 - This is in the format C(<number> <unit>).
78 - Where unit is one of second, minute, hour, day, week, month, quarter or year.
79 type: str
80 required: true
81 max:
82 description:
83 - Maximum values to apply to this interval in this quota.
84 - At least one key must be specified.
85 - Mutually exclusive with O(limits.no_limits) and O(limits.tracking_only).
86 type: dict
87 suboptions:
88 queries:
89 description:
90 - Maximum number of queries to enforce in this interval.
91 type: int
92 query_selects:
93 description:
94 - Maximum number of query selects to enforce in this interval.
95 type: int
96 query_inserts:
97 description:
98 - Maximum number of query inserts to enforce in this interval.
99 type: int
100 errors:
101 description:
102 - Maximum number of errors to enforce in this interval.
103 type: int
104 result_rows:
105 description:
106 - Maximum number of result rows to enforce in this interval.
107 type: int
108 result_bytes:
109 description:
110 - Maximum number of result bytes to enforce in this interval.
111 type: int
112 read_rows:
113 description:
114 - Maximum number of rows read to enforce in this interval.
115 type: int
116 read_bytes:
117 description:
118 - Maximum number of bytes read to enforce in this interval.
119 type: int
120 written_bytes:
121 description:
122 - Maximum number of bytes written to enforce in this interval.
123 type: int
124 execution_time:
125 description:
126 - Maximum number of execution time to enforce in this interval.
127 type: float
128 failed_sequential_authentications:
129 description:
130 - Maximum number of failed sequential authentications to enforce in this interval.
131 type: int
132 no_limits:
133 description:
134 - Don't apply any limits.
135 - Mutually exclusive with O(limits.max) and O(limits.tracking_only).
136 type: bool
137 tracking_only:
138 description:
139 - Just track usage instead of enforcing.
140 - Mutually exclusive with O(limits.max) and O(limits.no_limits).
141 type: bool
142 apply_to:
143 description:
144 - Apply this quota to the following list of users/roles dependent on O(apply_to_mode).
145 - Can include special keywords of default and current_user or the name of an actual user or role.
146 - Is an error to specify this if O(apply_to_mode=all).
147 type: list
148 elements: str
149 apply_to_mode:
150 description:
151 - When V(listed_only) (default), the quota will only apply to the users/roles specified in O(apply_to).
152 - When V(all), the quota will only apply to B(all) users/roles.
153 - When V(all_except_listed), the quota will only apply to B(all) the users/roles except those specified in O(apply_to).
154 type: str
155 choices: ['listed_only', 'all', 'all_except_listed']
156 default: 'listed_only'
157 """
158
159 EXAMPLES = r"""
160 - name: Create quota
161 community.clickhouse.clickhouse_quota:
162 name: test_quota
163 state: present
164
165 - name: Create a quota with limits
166 community.clickhouse.clickhouse_quota:
167 name: test_quota
168 state: present
169 limits:
170 - interval: 5 minute
171 max:
172 queries: 100
173 execution_time: 100
174 apply_to:
175 - one_role
176 - another_role
177 cluster: test_cluster
178
179 - name: Remove quota
180 community.clickhouse.clickhouse_quota:
181 name: test_quota
182 state: absent
183 """
184
185 RETURN = r"""
186 executed_statements:
187 description:
188 - Data-modifying executed statements.
189 returned: on success
190 type: list
191 sample: ['CREATE QUOTA test_quota']
192 """
193
194 import copy
195 import re
196 from operator import itemgetter
197
198 from ansible.module_utils.basic import AnsibleModule
199 from ansible_collections.community.clickhouse.plugins.module_utils.clickhouse import (
200 check_clickhouse_driver,
201 client_common_argument_spec,
202 connect_to_db_via_client,
203 execute_query,
204 get_main_conn_kwargs,
205 )
206
207 _VALID_NAME_REGEX = re.compile(r"^[^'\"`;\0]+$")
208 _POSSIBLY_ESCAPED_NAME_REGEX = r"(?:`(?:[^`]+)`)|(?:\w+)"
209 _KEYED_BY_VALUES = [
210 "user_name",
211 "ip_address",
212 "client_key, ?user_name",
213 "client_key, ?ip_address",
214 "client_key", # needs to be after so it doesn't match first
215 ]
216 _CREATE_QUOTA_REGEX = re.compile(
217 rf"^CREATE QUOTA (?P<name>{_POSSIBLY_ESCAPED_NAME_REGEX})"
218 rf"(?: ON CLUSTER (?P<cluster>{_POSSIBLY_ESCAPED_NAME_REGEX}))?"
219 rf"(?: KEYED BY (?P<keyed_by>{'|'.join(_KEYED_BY_VALUES)}))?"
220 )
221
222 _NUMBER_REGEX = r"(?:-?\d+\.?\d*)"
223 _INTERVAL_UNITS = [
224 "second",
225 "minute",
226 "hour",
227 "day",
228 "week",
229 "month",
230 "quarter",
231 "year",
232 ]
233 _MAX_LIMIT_TYPES = [
234 "queries",
235 "query_selects",
236 "query_inserts",
237 "errors",
238 "result_rows",
239 "result_bytes",
240 "read_rows",
241 "read_bytes",
242 "written_bytes",
243 "execution_time",
244 "failed_sequential_authentications",
245 ]
246 _LIMIT_TYPES = [
247 rf"(?:MAX(?:,? (?:{'|'.join(_MAX_LIMIT_TYPES)}) = {_NUMBER_REGEX})+)",
248 "NO LIMITS",
249 "TRACKING ONLY",
250 ]
251 _LIMITS_REGEX = re.compile(
252 r"FOR (?:(?P<randomized>RANDOMIZED) )?"
253 rf"INTERVAL (?P<interval_number>{_NUMBER_REGEX}) (?P<interval_unit>{'|'.join(_INTERVAL_UNITS)}) "
254 rf"(?P<limit_type>{'|'.join(_LIMIT_TYPES)})"
255 )
256
257 _ROLES_REGEX = rf"(?:(?:{_POSSIBLY_ESCAPED_NAME_REGEX})(?:, )?)+"
258 _APPLY_TO_TYPES = [rf"(?:{_ROLES_REGEX})", "ALL", rf"ALL EXCEPT (?:{_ROLES_REGEX})"]
259 _APPLY_TO_REGEX = re.compile(rf" TO (?P<apply_to>{'|'.join(_APPLY_TO_TYPES)})$")
260 _USER_OR_ROLE_REGEX = re.compile(rf"(?P<name>{_POSSIBLY_ESCAPED_NAME_REGEX})(?:, ?)?")
261
262
263 _DEFAULT_LIMIT_PARAMS = {
264 "randomized_start": False,
265 "interval": None,
266 "max": {},
267 "no_limits": None,
268 "tracking_only": None,
269 }
270
271 _DEFAULT_MAX_PARAMS = {
272 "queries": None,
273 "query_selects": None,
274 "query_inserts": None,
275 "errors": None,
276 "result_rows": None,
277 "result_bytes": None,
278 "read_rows": None,
279 "read_bytes": None,
280 "written_bytes": None,
281 "execution_time": None,
282 "failed_sequential_authentications": None,
283 }
284
285 _DEFAULT_PARAMS = {
286 "cluster": None,
287 "keyed_by": None,
288 "limits": [],
289 "apply_to": [],
290 "apply_to_mode": "listed_only",
291 }
292
293
294 class ClickHouseQuota:
295 _type = "QUOTA"
296
297 def __init__(self, module, client, name):
298 if not _VALID_NAME_REGEX.match(name):
299 raise ValueError(f"'{name}' is not a valid quota name")
300 self.module = module
301 self.client = client
302 self.name = name
303 self.executed_statements = []
304 self.exists = self._check_exists()
305
306 def _check_exists(self):
307 query = f"SELECT 1 FROM system.{self._type.lower()}s WHERE name = '{self.name}' LIMIT 1"
308 result = execute_query(self.module, self.client, query)
309 return bool(result)
310
311 def _get_create_statement(self):
312 """Get current definition using SHOW CREATE X"""
313 if not self.exists:
314 return None
315
316 query = f"SHOW CREATE {self._type} '{self.name}'"
317 result = execute_query(self.module, self.client, query)
318 if result:
319 # SHOW CREATE X returns single row with CREATE statement
320 return result[0][0]
321 return None
322
323 def _needs_altering(self):
324 """Check if we need to alter to reach desired"""
325 create_statement = self._get_create_statement()
326 if create_statement is None:
327 return True
328 current_params = self._normalize(self._parse_create_statement(create_statement))
329 desired_params = self._normalize(self.module.params)
330
331 # For debugging version compatibility issues
332 if self.module._verbosity >= 3: # Only show at high verbosity
333 self.module.log(f"Current params (normalized): {current_params}")
334 self.module.log(f"Desired params (normalized): {desired_params}")
335
336 return current_params != desired_params
337
338 def _do(self, action):
339 if action not in ("CREATE", "ALTER"):
340 raise ValueError(
341 f"Expected action to be CREATE or ALTER but got '{action}'"
342 )
343
344 query = " ".join(self._create_sql_clauses(action))
345
346 self.executed_statements.append(query)
347
348 if not self.module.check_mode:
349 execute_query(self.module, self.client, query)
350
351 def create(self):
352 """
353 Create entity using CREATE X
354 Returns whether the entity was created or not
355 """
356 if self.exists:
357 return False
358
359 self._do("CREATE")
360 self.exists = True
361 return True
362
363 def alter(self):
364 """
365 Update entity using ALTER X if it needs it
366 Returns whether the entity was altered or not
367 """
368 if not self.exists or not self._needs_altering():
369 return False
370
371 self._do("ALTER")
372 return True
373
374 def drop(self):
375 """Drop entity using DROP X"""
376 if not self.exists:
377 return False
378
379 query = f"DROP {self._type} '{self.name}'"
380 self.executed_statements.append(query)
381
382 if not self.module.check_mode:
383 execute_query(self.module, self.client, query)
384
385 self.exists = False
386 return True
387
388 def ensure_state(self):
389 state = self.module.params["state"]
390 if state not in ("present", "absent"):
391 raise ValueError(f"Unexpected state '{state}'")
392
393 if state == "present":
394 # create or alter role
395 # will do nothing is nothing needs to be done
396 changed = self.create() or self.alter()
397 else:
398 # drop if exists
399 changed = self.drop()
400
401 return changed
402
403 @staticmethod
404 def _parse_create_statement(create_statement):
405 match = _CREATE_QUOTA_REGEX.match(create_statement)
406 if not match:
407 raise ValueError(f"Could not parse '{create_statement}'")
408 params = {} | match.groupdict()
409 params.pop("name")
410 cluster = params["cluster"]
411 if cluster is not None:
412 params["cluster"] = cluster.strip("`")
413 next_search_pos = match.end()
414 limits = []
415 for match in _LIMITS_REGEX.finditer(create_statement, pos=next_search_pos):
416 limit = {}
417 groups = match.groupdict()
418 limit["randomized_start"] = groups["randomized"] == "RANDOMIZED"
419 limit["interval"] = f"{groups['interval_number']} {groups['interval_unit']}"
420 limit_type = groups["limit_type"]
421 if limit_type == "NO LIMITS":
422 limit["no_limits"] = True
423 elif limit_type == "TRACKING ONLY":
424 limit["tracking_only"] = True
425 elif limit_type.startswith("MAX "):
426 max_limits = {}
427 for max_limit in limit_type[len("MAX ") :].split(", "):
428 key, _part, value = max_limit.partition(" = ")
429 type_fn = float if key == "execution_time" else int
430 max_limits[key] = type_fn(value)
431 limit["max"] = max_limits
432 else:
433 raise ValueError(f"Invalid limit type '{limit_type}'")
434 limits.append(limit)
435 next_search_pos = match.end()
436 params["limits"] = limits
437 match = _APPLY_TO_REGEX.match(create_statement, pos=next_search_pos)
438 if match:
439 groups = match.groupdict()
440 apply_to = groups["apply_to"]
441 if apply_to == "ALL":
442 params["apply_to_mode"] = "all"
443 apply_to = ""
444 elif apply_to.startswith("ALL EXCEPT "):
445 params["apply_to_mode"] = "all_except_listed"
446 apply_to = apply_to[len("ALL EXCEPT ") :]
447 else:
448 params["apply_to_mode"] = "listed_only"
449 params["apply_to"] = [
450 match.groupdict()["name"].strip("`")
451 for match in _USER_OR_ROLE_REGEX.finditer(apply_to)
452 ]
453 return params
454
455 @staticmethod
456 def _normalize(params):
457 normalized = _DEFAULT_PARAMS.copy()
458 for key in normalized.keys() & params.keys():
459 value = params[key]
460 if value is not None:
461 if key == "limits":
462 normalized_limits = []
463 for limit_params in value:
464 normalized_limit = _DEFAULT_LIMIT_PARAMS.copy()
465 for limit_key in normalized_limit.keys() & limit_params.keys():
466 limit_value = limit_params[limit_key]
467 if limit_value is not None:
468 normalized_limit[limit_key] = limit_value
469 normalized_limits.append(normalized_limit)
470 normalized[key] = normalized_limits
471 else:
472 normalized[key] = copy.deepcopy(value)
473 keyed_by = normalized["keyed_by"]
474 if keyed_by:
475 normalized["keyed_by"] = ",".join(
476 key.strip() for key in keyed_by.split(",")
477 )
478 if (
479 normalized["apply_to_mode"] == "all_except_listed"
480 and not normalized["apply_to"]
481 ):
482 normalized["apply_to_mode"] = "all"
483 # no limits is the default so they automatically get removed
484 normalized["limits"] = [
485 limit for limit in normalized["limits"] if not limit.get("no_limits")
486 ]
487 for limit in normalized["limits"]:
488 max_limit = limit["max"]
489 if max_limit:
490 limit["max"] = _DEFAULT_MAX_PARAMS | max_limit
491 normalized["limits"].sort(key=itemgetter("interval"))
492 normalized["apply_to"].sort()
493 return normalized
494
495 def _create_sql_clauses(self, action):
496 sql_clauses = [f"{action} {self._type} '{self.name}'"]
497
498 cluster = self.module.params["cluster"]
499 if cluster:
500 sql_clauses.append(f"ON CLUSTER '{cluster}'")
501
502 keyed_by = self.module.params.get("keyed_by")
503 if keyed_by:
504 sql_clauses.append(f"KEYED BY {keyed_by}")
505
506 limits_sql_clauses = []
507 for limit in self.module.params["limits"] or []:
508 sql_clause = ["FOR"]
509 if limit.get("randomized_start", False):
510 sql_clause.append("RANDOMIZED")
511 sql_clause.append(f"INTERVAL {limit['interval']}")
512 max_limits = {
513 key: value
514 for key, value in (limit.get("max") or {}).items()
515 if value is not None
516 }
517 if max_limits:
518 sql_clause.append("MAX")
519 sql_clause.append(
520 ", ".join(f"{key} = {value}" for key, value in max_limits.items())
521 )
522 elif limit.get("no_limits"):
523 sql_clause.append("NO LIMITS")
524 elif limit.get("tracking_only"):
525 sql_clause.append("TRACKING ONLY")
526 else:
527 raise ValueError(
528 "One of max or no_limits or tracking_only needs to specified"
529 )
530 limits_sql_clauses.append(" ".join(sql_clause))
531 if limits_sql_clauses:
532 sql_clauses.append(", ".join(limits_sql_clauses))
533
534 apply_to = self.module.params.get("apply_to", [])
535 apply_to_mode = self.module.params["apply_to_mode"]
536 if apply_to_mode == "all_except_listed" and not apply_to:
537 apply_to_mode = "all"
538 if apply_to and apply_to_mode == "all":
539 raise ValueError(
540 "Cannot specify list of user/roles to apply to when apply_to_mode == all"
541 )
542 if apply_to_mode == "all":
543 sql_clauses.append("TO ALL")
544 elif apply_to:
545 sql_clauses.append("TO")
546 if apply_to_mode == "all_except_listed":
547 sql_clauses.append("ALL EXCEPT")
548 sql_clauses.append(", ".join(apply_to))
549
550 return sql_clauses
551
552
553 def main():
554 # Set up arguments.
555 # If there are common arguments shared across several modules,
556 # create the common_argument_spec() function under plugins/module_utils/*
557 # and invoke here to return a dict with those arguments
558 argument_spec = client_common_argument_spec()
559 argument_spec.update(
560 state=dict(type="str", choices=["present", "absent"], default="present"),
561 name=dict(type="str", required=True),
562 cluster=dict(type="str", default=None),
563 keyed_by=dict(
564 type="str",
565 choices=[
566 "user_name",
567 "ip_address",
568 "client_key",
569 "client_key,user_name",
570 "client_key,ip_address",
571 ],
572 ),
573 limits=dict(
574 type="list",
575 elements="dict",
576 options=dict(
577 randomized_start=dict(type="bool", default=False),
578 interval=dict(type="str", required=True),
579 max=dict(
580 type="dict",
581 options=dict(
582 queries=dict(type="int"),
583 query_selects=dict(type="int"),
584 query_inserts=dict(type="int"),
585 errors=dict(type="int"),
586 result_rows=dict(type="int"),
587 result_bytes=dict(type="int"),
588 read_rows=dict(type="int"),
589 read_bytes=dict(type="int"),
590 written_bytes=dict(type="int"),
591 execution_time=dict(type="float"),
592 failed_sequential_authentications=dict(type="int"),
593 ),
594 required_one_of=[
595 (
596 "queries",
597 "query_selects",
598 "query_inserts",
599 "errors",
600 "result_rows",
601 "result_bytes",
602 "read_rows",
603 "read_bytes",
604 "written_bytes",
605 "execution_time",
606 "failed_sequential_authentications",
607 )
608 ],
609 ),
610 no_limits=dict(type="bool"),
611 tracking_only=dict(type="bool"),
612 ),
613 mutually_exclusive=[("max", "no_limits", "tracking_only")],
614 required_one_of=[("max", "no_limits", "tracking_only")],
615 ),
616 apply_to=dict(type="list", elements="str"),
617 apply_to_mode=dict(
618 type="str",
619 choices=["listed_only", "all", "all_except_listed"],
620 default="listed_only",
621 ),
622 )
623
624 # Instantiate an object of module class
625 module = AnsibleModule(
626 argument_spec=argument_spec,
627 supports_check_mode=True,
628 )
629
630 # Assign passed options to variables
631 client_kwargs = module.params["client_kwargs"]
632 # The reason why these arguments are separate from client_kwargs
633 # is that we need to protect some sensitive data like passwords passed
634 # to the module from logging (see the arguments above with no_log=True);
635 # Such data must be passed as module arguments (not nested deep in values).
636 main_conn_kwargs = get_main_conn_kwargs(module)
637 name = module.params["name"]
638
639 # Will fail if no driver informing the user
640 check_clickhouse_driver(module)
641
642 # Connect to DB
643 client = connect_to_db_via_client(module, main_conn_kwargs, client_kwargs)
644
645 # Do the job
646 quota = ClickHouseQuota(module, client, name)
647 changed = quota.ensure_state()
648
649 # Close connection
650 client.disconnect_connection()
651
652 # Users will get this in JSON output after execution
653 module.exit_json(changed=changed, executed_statements=quota.executed_statements)
654
655
656 if __name__ == "__main__":
657 main()