Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2024, Andrew Klychkov (@Andersson007) <[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 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: clickhouse_info
13
14 short_description: Gather ClickHouse server information using the clickhouse-driver Client interface
15
16 description:
17 - Gather ClickHouse server information using the
18 L(clickhouse-driver,https://clickhouse-driver.readthedocs.io/en/latest) Client interface.
19 - Does not change server state.
20
21 attributes:
22 check_mode:
23 description: Supports check_mode.
24 support: full
25
26 version_added: '0.1.0'
27
28 author:
29 - Andrew Klychkov (@Andersson007)
30 - Aleksandr Vagachev (@aleksvagachev)
31
32 extends_documentation_fragment:
33 - community.clickhouse.client_inst_opts
34
35 options:
36 limit:
37 description:
38 - Limits a set of return values you want to get.
39 - See the Return section for acceptable values.
40 - If not specified, returns all supported return values.
41 type: list
42 elements: str
43 version_added: '0.2.0'
44 '''
45
46 EXAMPLES = r'''
47 - name: Get server information
48 register: result
49 community.clickhouse.clickhouse_info:
50 login_host: localhost
51 login_user: alice
52 login_db: foo
53 login_password: my_password
54
55 - name: Print returned data
56 ansible.builtin.debug:
57 var: result
58
59 - name: Limit return values with users and roles
60 register: result
61 community.clickhouse.clickhouse_info:
62 limit:
63 - users
64 - roles
65 '''
66
67 # When adding new ret values,
68 # please add it to the ret_val_func_mapping dictionary!
69 RETURN = r'''
70 driver:
71 description: Python driver information.
72 returned: success
73 type: dict
74 sample: { "version": "0.2.6" }
75 version:
76 description: Clickhouse server version.
77 returned: success
78 type: dict
79 sample: {"raw": "23.12.2.59", "year": 23, "feature": 12, "maintenance": 2, "build": 59, "type": null }
80 databases:
81 description:
82 - The content of the system.databases table with names as keys.
83 - Be sure your I(login_user) has permissions.
84 returned: success
85 type: dict
86 sample: { "system": "..." }
87 users:
88 description:
89 - The content of the system.users table with names as keys.
90 - Be sure your I(login_user) has permissions.
91 returned: success
92 type: dict
93 sample: { "default": "..." }
94 roles:
95 description:
96 - The content of the system.roles table with names as keys.
97 - Be sure your I(login_user) has permissions.
98 returned: success
99 type: dict
100 sample: { "accountant": "..." }
101 settings:
102 description:
103 - The content of the system.settings table with names as keys.
104 returned: success
105 type: dict
106 sample: { "zstd_window_log_max": "..." }
107 clusters:
108 description:
109 - The content of the system.clusters table with names as keys.
110 returned: success
111 type: dict
112 sample: { "test_cluster_two_shards": "..." }
113 tables:
114 description:
115 - The content of the system.tables table with the table names as keys.
116 returned: success
117 type: dict
118 sample: { "system": { "settings": "..." } }
119 version_added: '0.3.0'
120 merge_tree_settings:
121 description:
122 - The content of the system.merge_tree_settings table with names as keys.
123 returned: success
124 type: dict
125 sample: { "merge_max_block_size": "..." }
126 version_added: '0.3.0'
127 dictionaries:
128 description:
129 - The content of the system.dictionaries table with dictionary names as keys.
130 returned: success
131 type: dict
132 sample: { "database": { "dictionary": "..." } }
133 version_added: '0.3.0'
134 quotas:
135 description:
136 - The content of the system.quotas table with quota names as keys.
137 returned: success
138 type: dict
139 sample: { "default": "..." }
140 version_added: '0.4.0'
141 settings_profiles:
142 description:
143 - The content of the system.settings_profiles table with profile names as keys.
144 returned: success
145 type: dict
146 sample: { "readonly": "..." }
147 version_added: '0.4.0'
148 storage_policies:
149 description:
150 - The content of the system.storage_policies table with storage_policies names as keys.
151 returned: success
152 type: dict
153 sample: { "storage_policies": "..." }
154 version_added: '0.4.0'
155 grants:
156 description:
157 - The content of the system.grants table for users and roles as keys.
158 returned: success
159 type: dict
160 sample: { "roles": {"..."}, "users": {"..."} }
161 version_added: '0.7.0'
162 settings_profile_elements:
163 description:
164 - The content of the system.settings_profile_elements table for users, roles, profiles as keys.
165 returned: success
166 type: dict
167 sample: { "roles": {"..."}, "users": {"..."}, "profiles": {"..."} }
168 version_added: '0.7.0'
169 '''
170
171 from ansible.module_utils.basic import AnsibleModule
172
173 from ansible_collections.community.clickhouse.plugins.module_utils.clickhouse import (
174 check_clickhouse_driver,
175 client_common_argument_spec,
176 connect_to_db_via_client,
177 execute_query,
178 get_main_conn_kwargs,
179 get_server_version,
180 version_clickhouse_driver,
181 )
182
183
184 PRIV_ERR_CODE = 497
185
186
187 def get_databases(module, client):
188 """Get databases.
189
190 Returns a dictionary with database names as keys.
191 """
192 query = ("SELECT name, engine, data_path, metadata_path, uuid, "
193 "engine_full, comment FROM system.databases")
194 result = execute_query(module, client, query)
195
196 if result == PRIV_ERR_CODE:
197 return {str(PRIV_ERR_CODE): "Not enough privileges"}
198
199 db_info = {}
200 for row in result:
201 db_info[row[0]] = {
202 "engine": row[1],
203 "data_path": row[2],
204 "metadata_path": row[3],
205 "uuid": str(row[4]),
206 "engine_full": row[5],
207 "comment": row[6],
208 }
209
210 return db_info
211
212
213 def get_clusters(module, client):
214 """Get clusters.
215
216 Returns a list with clusters names as top level keys.
217 """
218 query = ("SELECT cluster, shard_num, shard_weight, replica_num, host_name, "
219 "host_address, port, is_local, user, default_database, errors_count, "
220 "slowdowns_count, estimated_recovery_time FROM system.clusters")
221 result = execute_query(module, client, query)
222
223 if result == PRIV_ERR_CODE:
224 return {str(PRIV_ERR_CODE): "Not enough privileges"}
225
226 cluster_info = {}
227
228 for row in result:
229 cluster = row[0]
230 shard_num = str(row[1])
231 shard_weight = row[2]
232 replica_num = str(row[3])
233 host_name = row[4]
234 host_address = row[5]
235 port = row[6]
236 is_local = row[7]
237 user = row[8]
238 default_database = row[9]
239 errors_count = row[10]
240 slowdowns_count = row[11]
241 estimated_recovery_time = row[12]
242
243 # Add cluster if not already there
244 if cluster not in cluster_info:
245 cluster_info[cluster] = {"shards": {}}
246
247 # Add shard if not already there
248 if shard_num not in cluster_info[cluster]["shards"]:
249 cluster_info[cluster]["shards"][shard_num] = {
250 "shard_weight": shard_weight,
251 "replicas": {},
252 }
253
254 # Add replica if not already there
255 if replica_num not in cluster_info[cluster]["shards"][shard_num]["replicas"]:
256 cluster_info[cluster]["shards"][shard_num]["replicas"][replica_num] = {
257 "host_name": host_name,
258 "host_address": host_address,
259 "port": port,
260 "is_local": is_local,
261 "user": user,
262 "default_database": default_database,
263 "errors_count": errors_count,
264 "slowdowns_count": slowdowns_count,
265 "estimated_recovery_time": estimated_recovery_time,
266 }
267
268 return cluster_info
269
270
271 def get_roles(module, client):
272 """Get roles.
273
274 Returns a dictionary with roles names as keys.
275 """
276 query = "SELECT name, id, storage FROM system.roles"
277 result = execute_query(module, client, query)
278
279 if result == PRIV_ERR_CODE:
280 return {str(PRIV_ERR_CODE): "Not enough privileges"}
281
282 roles_info = {}
283 for row in result:
284 role_name = row[0]
285 roles_info[role_name] = {
286 "id": str(row[1]),
287 "storage": row[2],
288 }
289 roles_info[role_name]["grants"] = get_grants(module, client, role_name)
290
291 return roles_info
292
293
294 def get_tables(module, client):
295 """Get tables.
296
297 Returns a dictionary with databases name as dictionary,
298 and the name of the table in this dictionary is the key.
299 """
300 query = ("SELECT database, name, uuid, engine, is_temporary, data_paths, "
301 "metadata_path, metadata_modification_time, dependencies_database, "
302 "dependencies_table, create_table_query, engine_full, as_select, partition_key, "
303 "sorting_key, primary_key, sampling_key, storage_policy, total_rows, total_bytes, "
304 "parts, active_parts, total_marks, lifetime_rows, lifetime_bytes, comment, "
305 "has_own_data, loading_dependencies_database, loading_dependencies_table, "
306 "loading_dependent_database, loading_dependent_table FROM system.tables")
307 result = execute_query(module, client, query)
308
309 if result == PRIV_ERR_CODE:
310 return {str(PRIV_ERR_CODE): "Not enough privileges"}
311
312 tables_info = {}
313 for row in result:
314 if row[0] not in tables_info:
315 tables_info[row[0]] = {}
316 tables_info[row[0]][row[1]] = {
317 "uuid": str(row[2]),
318 "engine": row[3],
319 "is_temporary": row[4],
320 "data_paths": row[5],
321 "metadata_path": row[6],
322 "metadata_modification_time": row[7],
323 "dependencies_database": row[8],
324 "dependencies_table": row[9],
325 "create_table_query": row[10],
326 "engine_full": row[11],
327 "as_select": row[12],
328 "partition_key": row[13],
329 "sorting_key": row[14],
330 "primary_key": row[15],
331 "sampling_key": row[16],
332 "storage_policy": row[17],
333 "total_rows": row[18],
334 "total_bytes": row[19],
335 "parts": row[20],
336 "active_parts": row[21],
337 "total_marks": row[22],
338 "lifetime_rows": row[23],
339 "lifetime_bytes": row[24],
340 "comment": row[25],
341 "has_own_data": row[26],
342 "loading_dependencies_database": row[27],
343 "loading_dependencies_table": row[28],
344 "loading_dependent_database": row[29],
345 "loading_dependent_table": row[30],
346 }
347
348 return tables_info
349
350
351 def get_dictionaries(module, client):
352 """Get dictionaries.
353
354 Returns a dictionary with databases name as dictionary,
355 and the name of the 'dictionary' in this dictionary is the key.
356 """
357 query = ("SELECT database, name, uuid, status, origin, key.names, key.types, "
358 "attribute.names, attribute.types, bytes_allocated, "
359 "hierarchical_index_bytes_allocated, query_count, hit_rate, found_rate, "
360 "element_count, load_factor, source, lifetime_min, "
361 "lifetime_max, loading_start_time, last_successful_update_time, "
362 "loading_duration, last_exception, comment FROM system.dictionaries")
363 result = execute_query(module, client, query)
364
365 if result == PRIV_ERR_CODE:
366 return {str(PRIV_ERR_CODE): "Not enough privileges"}
367
368 dictionaries_info = {}
369 for row in result:
370 dict_database = row[0] if row[0] else 'dict'
371 if dict_database not in dictionaries_info:
372 dictionaries_info[dict_database] = {}
373 dictionaries_info[dict_database][row[1]] = {
374 "uuid": str(row[2]),
375 "status": row[3],
376 "origin": row[4],
377 "key.names": row[5],
378 "key.types": row[6],
379 "attribute.names": row[7],
380 "attribute.types": row[8],
381 "bytes_allocated": row[9],
382 "hierarchical_index_bytes_allocated": row[10],
383 "query_count": row[11],
384 "hit_rate": row[12],
385 "found_rate": row[13],
386 "element_count": row[14],
387 "load_factor": row[15],
388 "source": row[16],
389 "lifetime_min": row[17],
390 "lifetime_max": row[18],
391 "loading_start_time": row[19],
392 "last_successful_update_time": row[20],
393 "loading_duration": row[21],
394 "last_exception": row[22],
395 }
396
397 return dictionaries_info
398
399
400 def get_settings(module, client):
401 """Get settings.
402
403 Returns a dictionary with settings names as keys.
404 """
405 query = ("SELECT name, value, changed, description, min, max, readonly, "
406 "type, default, alias_for FROM system.settings")
407 result = execute_query(module, client, query)
408
409 if result == PRIV_ERR_CODE:
410 return {str(PRIV_ERR_CODE): "Not enough privileges"}
411
412 settings_info = {}
413 for row in result:
414 settings_info[row[0]] = {
415 "value": row[1],
416 "changed": row[2],
417 "description": row[3],
418 "min": row[4],
419 "max": row[5],
420 "readonly": row[6],
421 "type": row[7],
422 "default": row[8],
423 "alias_for": row[9],
424 }
425
426 return settings_info
427
428
429 def get_merge_tree_settings(module, client):
430 """Get merge_tree_settings.
431
432 Returns a dictionary with merge_tree_settings names as keys.
433 """
434 query = ("SELECT name, value, changed, description, min, max, "
435 "readonly, type FROM system.merge_tree_settings")
436 result = execute_query(module, client, query)
437
438 if result == PRIV_ERR_CODE:
439 return {str(PRIV_ERR_CODE): "Not enough privileges"}
440
441 merge_tree_settings_info = {}
442 for row in result:
443 merge_tree_settings_info[row[0]] = {
444 "value": row[1],
445 "changed": row[2],
446 "description": row[3],
447 "min": row[4],
448 "max": row[5],
449 "readonly": row[6],
450 "type": row[7],
451 }
452
453 return merge_tree_settings_info
454
455
456 def get_users(module, client):
457 """Get users.
458
459 Returns a dictionary with users names as keys.
460 """
461 query = ("SELECT name, id, storage, auth_type, auth_params, host_ip, host_names, "
462 "host_names_regexp, host_names_like, default_roles_all, "
463 "default_roles_list, default_roles_except, grantees_any, "
464 "grantees_list, grantees_except, default_database FROM system.users")
465 result = execute_query(module, client, query)
466
467 if result == PRIV_ERR_CODE:
468 return {str(PRIV_ERR_CODE): "Not enough privileges"}
469
470 user_info = {}
471 for row in result:
472 user_name = row[0]
473 user_info[user_name] = {
474 "id": str(row[1]),
475 "storage": row[2],
476 "auth_type": row[3],
477 "auth_params": row[4],
478 "host_ip": row[5],
479 "host_names": row[6],
480 "host_names_regexp": row[7],
481 "host_names_like": row[8],
482 "default_roles_all": row[9],
483 "default_roles_list": row[10],
484 "default_roles_except": row[11],
485 "grantees_any": row[12],
486 "grantees_list": row[13],
487 "grantees_except": row[14],
488 "default_database": row[15],
489
490 }
491
492 user_info[user_name]["roles"] = get_user_roles(module, client, user_name)
493 user_info[user_name]["grants"] = get_grants(module, client, user_name)
494
495 return user_info
496
497
498 def get_grants(module, client, name):
499 """Get grants.
500
501 Return a list of grants.
502 """
503 query = ("SHOW GRANTS FOR '%s'" % name)
504 result = execute_query(module, client, query)
505 return [row[0] for row in result]
506
507
508 def get_user_roles(module, client, user_name):
509 """Get user roles.
510
511 Returns a list of roles.
512 """
513 query = ("SELECT granted_role_name FROM system.role_grants "
514 "WHERE user_name = '%s'" % user_name)
515 result = execute_query(module, client, query)
516 return [row[0] for row in result]
517
518
519 def get_settings_profiles(module, client):
520 """Get settings profiles.
521
522 Returns a dictionary with profile names as keys.
523 """
524 query = ("SELECT name, id, storage, num_elements, apply_to_all, apply_to_list, "
525 "apply_to_except FROM system.settings_profiles")
526 result = execute_query(module, client, query)
527
528 if result == PRIV_ERR_CODE:
529 return {str(PRIV_ERR_CODE): "Not enough privileges"}
530
531 profile_info = {}
532 for row in result:
533 profile_info[row[0]] = {
534 "id": str(row[1]),
535 "storage": row[2],
536 "num_elements": row[3],
537 "apply_to_all": row[4],
538 "apply_to_list": row[5],
539 "apply_to_except": row[6],
540 }
541
542 return profile_info
543
544
545 def get_quotas(module, client):
546 """Get quotas.
547
548 Returns a dictionary with quota names as keys.
549 """
550 query = ("SELECT name, id, storage, keys, durations, apply_to_all, "
551 "apply_to_list, apply_to_except FROM system.quotas")
552 result = execute_query(module, client, query)
553
554 if result == PRIV_ERR_CODE:
555 return {str(PRIV_ERR_CODE): "Not enough privileges"}
556
557 quota_info = {}
558 for row in result:
559 quota_info[row[0]] = {
560 "id": str(row[1]),
561 "storage": row[2],
562 "keys": row[3],
563 "durations": row[4],
564 "apply_to_all": row[5],
565 "apply_to_list": row[6],
566 "apply_to_except": row[7],
567 }
568
569 return quota_info
570
571
572 def get_all_grants(module, client):
573 """Get grants.
574
575 Returns a dictionary with users and roles names as keys.
576 """
577 query = ("SELECT user_name, role_name, access_type, database, "
578 "table, column, is_partial_revoke, grant_option FROM system.grants")
579
580 result = execute_query(module, client, query)
581
582 if result == PRIV_ERR_CODE:
583 return {str(PRIV_ERR_CODE): "Not enough privileges"}
584
585 grants_info = {
586 'users': {},
587 'roles': {},
588 }
589
590 for row in result:
591 if row[0] is not None:
592 dict_name = 'users'
593 name = row[0]
594 if row[0] not in grants_info[dict_name]:
595 grants_info[dict_name][name] = []
596 else:
597 dict_name = 'roles'
598 name = row[1]
599 if row[1] not in grants_info[dict_name]:
600 grants_info[dict_name][name] = []
601
602 grants_info[dict_name][name].append({
603 "access_type": row[2],
604 "database": row[3],
605 "table": row[4],
606 "column": row[5],
607 "is_partial_revoke": row[6],
608 "grant_option": row[7],
609 })
610
611 return grants_info
612
613
614 def get_settings_profile_elements(module, client):
615 """Get settings_profile_elements.
616
617 Returns a dictionary with roles, profiles and users names as keys.
618 """
619 query = ("SELECT profile_name, user_name, role_name, "
620 "index, setting_name, value, min, max, writability, "
621 "inherit_profile FROM system.settings_profile_elements")
622 result = execute_query(module, client, query)
623
624 if result == PRIV_ERR_CODE:
625 return {str(PRIV_ERR_CODE): "Not enough privileges"}
626
627 settings_profile_elements = {'profiles': {},
628 'users': {},
629 'roles': {},
630 }
631
632 for row in result:
633 if row[0] is not None:
634 dict_name = 'profiles'
635 name = row[0]
636 if row[0] not in settings_profile_elements[dict_name]:
637 settings_profile_elements[dict_name][name] = []
638 elif row[1] is not None:
639 dict_name = 'users'
640 name = row[1]
641 if row[1] not in settings_profile_elements[dict_name]:
642 settings_profile_elements[dict_name][name] = []
643 else:
644 dict_name = 'roles'
645 name = row[2]
646 if row[2] not in settings_profile_elements[dict_name]:
647 settings_profile_elements[dict_name][name] = []
648
649 settings_profile_elements[dict_name][name].append({
650 "index": row[3],
651 "setting_name": row[4],
652 "value": row[5],
653 "min": row[6],
654 "max": row[7],
655 "writability": row[8],
656 "inherit_profile": row[9],
657 })
658
659 return settings_profile_elements
660
661
662 def get_storage_policies(module, client):
663 """Get storage_policies.
664
665 Returns a dictionary with storage_policies names as keys.
666 """
667 query = ("SELECT policy_name, volume_name, volume_priority, "
668 "disks, volume_type, max_data_part_size, "
669 "move_factor, prefer_not_to_merge FROM system.storage_policies")
670 result = execute_query(module, client, query)
671
672 if result == PRIV_ERR_CODE:
673 return {str(PRIV_ERR_CODE): "Not enough privileges"}
674
675 storage_policies_info = {}
676 for row in result:
677 storage_policies_info[row[0]] = {
678 "volume_name": row[1],
679 "volume_priority": row[2],
680 "disks": row[3],
681 "volume_type": row[4],
682 "max_data_part_size": row[5],
683 "move_factor": row[6],
684 "prefer_not_to_merge": row[7],
685 }
686
687 return storage_policies_info
688
689
690 def get_driver(module, client):
691 """Gets driver information.
692
693 The module and client arguments are here
694 to provide a common interface and are ignored.
695
696 Returns its version for now.
697 """
698 return {"version": version_clickhouse_driver()}
699
700
701 def handle_limit_values(module, supported_ret_vals, limit):
702 """Checks if passed limit values match module return values.
703
704 Prints a warning if do not match. Returns a list of stripped vals.
705 """
706 stripped_vals = []
707 for wanted_val in limit:
708 wanted_val = wanted_val.strip()
709
710 if wanted_val not in supported_ret_vals:
711 msg = ("The passed %s value does not exist in module return values: "
712 "please check the spelling and supported values, and try again" % wanted_val)
713 module.warn(msg)
714 continue
715
716 stripped_vals.append(wanted_val)
717
718 return stripped_vals
719
720
721 def main():
722 # Set up arguments.
723 # If there are common arguments shared across several modules,
724 # create the common_argument_spec() function under plugins/module_utils/*
725 # and invoke here to return a dict with those arguments
726 argument_spec = client_common_argument_spec()
727 argument_spec.update(
728 limit=dict(type='list', elements='str'),
729 )
730
731 # Instantiate an object of module class
732 module = AnsibleModule(
733 argument_spec=argument_spec,
734 supports_check_mode=True,
735 )
736
737 # Assign passed options to variables
738 client_kwargs = module.params['client_kwargs']
739 # The reason why these arguments are separate from client_kwargs
740 # is that we need to protect some sensitive data like passwords passed
741 # to the module from logging (see the arguments above with no_log=True);
742 # Such data must be passed as module arguments (not nested deep in values).
743 main_conn_kwargs = get_main_conn_kwargs(module)
744
745 # Create a mapping between ret values and functions.
746 # When adding new values to return, add the value
747 # and a corresponding function in this dictionary
748 ret_val_func_mapping = {
749 'driver': get_driver,
750 'version': get_server_version,
751 'databases': get_databases,
752 'users': get_users,
753 'roles': get_roles,
754 'settings': get_settings,
755 'clusters': get_clusters,
756 'dictionaries': get_dictionaries,
757 'tables': get_tables,
758 'merge_tree_settings': get_merge_tree_settings,
759 'quotas': get_quotas,
760 'settings_profiles': get_settings_profiles,
761 'settings_profile_elements': get_settings_profile_elements,
762 'storage_policies': get_storage_policies,
763 'grants': get_all_grants,
764 }
765 # Check if the limit is provided, it contains correct values
766 limit = module.params['limit']
767 if limit:
768 limit = handle_limit_values(module, ret_val_func_mapping.keys(), limit)
769 else:
770 # If no limit, just gather all ret values
771 limit = ret_val_func_mapping.keys()
772
773 # Will fail if no driver informing the user
774 check_clickhouse_driver(module)
775
776 # Connect to DB
777 client = connect_to_db_via_client(module, main_conn_kwargs, client_kwargs)
778
779 # Get server information
780 srv_info = {}
781 for item in limit:
782 # This will invoke a proper function
783 srv_info[item] = ret_val_func_mapping[item](module, client)
784
785 # Close connection
786 client.disconnect_connection()
787
788 # Users will get this in JSON output after execution
789 module.exit_json(changed=False, **srv_info)
790
791
792 if __name__ == '__main__':
793 main()