Debian Codegraph @

ansible_collections/community/proxysql/plugins/modules/proxysql_scheduler.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Copyright: (c) 2017, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9 DOCUMENTATION = '''
10 ---
11 module: proxysql_scheduler
12 author: "Ben Mildren (@bmildren)"
13 short_description: Adds or removes schedules from proxysql admin interface
14 description:
15 - The M(community.proxysql.proxysql_scheduler) module adds or removes schedules using the
16 proxysql admin interface.
17 options:
18 active:
19 description:
20 - A schedule with I(active) set to C(False) will be tracked in the
21 database, but will be never loaded in the in-memory data structures.
22 type: bool
23 default: true
24 interval_ms:
25 description:
26 - How often (in millisecond) the job will be started. The minimum value
27 for I(interval_ms) is 100 milliseconds.
28 type: int
29 default: 10000
30 filename:
31 description:
32 - Full path of the executable to be executed.
33 type: str
34 required: true
35 arg1:
36 description:
37 - Argument that can be passed to the job.
38 type: str
39 arg2:
40 description:
41 - Argument that can be passed to the job.
42 type: str
43 arg3:
44 description:
45 - Argument that can be passed to the job.
46 type: str
47 arg4:
48 description:
49 - Argument that can be passed to the job.
50 type: str
51 arg5:
52 description:
53 - Argument that can be passed to the job.
54 type: str
55 comment:
56 description:
57 - Text field that can be used for any purposed defined by the user.
58 type: str
59 state:
60 description:
61 - When C(present) - adds the schedule, when C(absent) - removes the
62 schedule.
63 type: str
64 choices: [ "present", "absent" ]
65 default: present
66 force_delete:
67 description:
68 - By default we avoid deleting more than one schedule in a single batch,
69 however if you need this behaviour and you are not concerned about the
70 schedules deleted, you can set I(force_delete) to C(True).
71 type: bool
72 default: false
73 extends_documentation_fragment:
74 - community.proxysql.proxysql.managing_config
75 - community.proxysql.proxysql.connectivity
76 notes:
77 - Supports C(check_mode).
78 '''
79
80 EXAMPLES = '''
81 ---
82 # This example adds a schedule, it saves the scheduler config to disk, but
83 # avoids loading the scheduler config to runtime (this might be because
84 # several servers are being added and the user wants to push the config to
85 # runtime in a single batch using the community.general.proxysql_manage_config
86 # module). It uses supplied credentials to connect to the proxysql admin
87 # interface.
88
89 - name: Add a schedule
90 community.proxysql.proxysql_scheduler:
91 login_user: 'admin'
92 login_password: 'admin'
93 interval_ms: 1000
94 filename: "/opt/maintenance.py"
95 state: present
96 load_to_runtime: false
97
98 # This example removes a schedule, saves the scheduler config to disk, and
99 # dynamically loads the scheduler config to runtime. It uses credentials
100 # in a supplied config file to connect to the proxysql admin interface.
101
102 - name: Remove a schedule
103 community.proxysql.proxysql_scheduler:
104 config_file: '~/proxysql.cnf'
105 filename: "/opt/old_script.py"
106 state: absent
107 '''
108
109 RETURN = '''
110 stdout:
111 description: The schedule modified or removed from proxysql.
112 returned: On create/update will return the newly modified schedule, on
113 delete it will return the deleted record.
114 type: dict
115 "sample": {
116 "changed": true,
117 "filename": "/opt/test.py",
118 "msg": "Added schedule to scheduler",
119 "schedules": [
120 {
121 "active": "1",
122 "arg1": null,
123 "arg2": null,
124 "arg3": null,
125 "arg4": null,
126 "arg5": null,
127 "comment": "",
128 "filename": "/opt/test.py",
129 "id": "1",
130 "interval_ms": "10000"
131 }
132 ],
133 "state": "present"
134 }
135 '''
136
137 from ansible.module_utils.basic import AnsibleModule
138 from ansible_collections.community.proxysql.plugins.module_utils.mysql import (
139 mysql_connect,
140 mysql_driver,
141 proxysql_common_argument_spec,
142 save_config_to_disk,
143 load_config_to_runtime,
144 )
145 from ansible.module_utils._text import to_native
146
147 # ===========================================
148 # proxysql module specific support methods.
149 #
150
151
152 def perform_checks(module):
153 if module.params["interval_ms"] < 100 \
154 or module.params["interval_ms"] > 100000000:
155 module.fail_json(
156 msg="interval_ms must between 100ms & 100000000ms"
157 )
158
159
160 class ProxySQLSchedule(object):
161
162 def __init__(self, module):
163 self.state = module.params["state"]
164 self.force_delete = module.params["force_delete"]
165 self.save_to_disk = module.params["save_to_disk"]
166 self.load_to_runtime = module.params["load_to_runtime"]
167 self.active = module.params["active"]
168 self.interval_ms = module.params["interval_ms"]
169 self.filename = module.params["filename"]
170
171 config_data_keys = ["arg1",
172 "arg2",
173 "arg3",
174 "arg4",
175 "arg5",
176 "comment"]
177
178 self.config_data = dict((k, module.params[k])
179 for k in config_data_keys)
180
181 def check_schedule_config(self, cursor):
182 query_string = \
183 """SELECT count(*) AS `schedule_count`
184 FROM scheduler
185 WHERE active = %s
186 AND interval_ms = %s
187 AND filename = %s"""
188
189 query_data = \
190 [self.active,
191 self.interval_ms,
192 self.filename]
193
194 for col, val in self.config_data.items():
195 if val is not None:
196 query_data.append(val)
197 query_string += "\n AND " + col + " = %s"
198
199 cursor.execute(query_string, query_data)
200 check_count = cursor.fetchone()
201 return int(check_count['schedule_count'])
202
203 def get_schedule_config(self, cursor):
204 query_string = \
205 """SELECT *
206 FROM scheduler
207 WHERE active = %s
208 AND interval_ms = %s
209 AND filename = %s"""
210
211 query_data = \
212 [self.active,
213 self.interval_ms,
214 self.filename]
215
216 for col, val in self.config_data.items():
217 if val is not None:
218 query_data.append(val)
219 query_string += "\n AND " + col + " = %s"
220
221 cursor.execute(query_string, query_data)
222 schedule = cursor.fetchall()
223 return schedule
224
225 def create_schedule_config(self, cursor):
226 query_string = \
227 """INSERT INTO scheduler (
228 active,
229 interval_ms,
230 filename"""
231
232 cols = 0
233 query_data = \
234 [self.active,
235 self.interval_ms,
236 self.filename]
237
238 for col, val in self.config_data.items():
239 if val is not None:
240 cols += 1
241 query_data.append(val)
242 query_string += ",\n" + col
243
244 query_string += \
245 (")\n" +
246 "VALUES (%s, %s, %s" +
247 ", %s" * cols +
248 ")")
249
250 cursor.execute(query_string, query_data)
251 return True
252
253 def delete_schedule_config(self, cursor):
254 query_string = \
255 """DELETE FROM scheduler
256 WHERE active = %s
257 AND interval_ms = %s
258 AND filename = %s"""
259
260 query_data = \
261 [self.active,
262 self.interval_ms,
263 self.filename]
264
265 for col, val in self.config_data.items():
266 if val is not None:
267 query_data.append(val)
268 query_string += "\n AND " + col + " = %s"
269
270 cursor.execute(query_string, query_data)
271 check_count = cursor.rowcount
272 return True, int(check_count)
273
274 def manage_config(self, cursor, state):
275 if state:
276 if self.save_to_disk:
277 save_config_to_disk(cursor, "SCHEDULER")
278 if self.load_to_runtime:
279 load_config_to_runtime(cursor, "SCHEDULER")
280
281 def create_schedule(self, check_mode, result, cursor):
282 if not check_mode:
283 result['changed'] = \
284 self.create_schedule_config(cursor)
285 result['msg'] = "Added schedule to scheduler"
286 result['schedules'] = \
287 self.get_schedule_config(cursor)
288 self.manage_config(cursor,
289 result['changed'])
290 else:
291 result['changed'] = True
292 result['msg'] = ("Schedule would have been added to" +
293 " scheduler, however check_mode" +
294 " is enabled.")
295
296 def delete_schedule(self, check_mode, result, cursor):
297 if not check_mode:
298 result['schedules'] = \
299 self.get_schedule_config(cursor)
300 result['changed'] = \
301 self.delete_schedule_config(cursor)
302 result['msg'] = "Deleted schedule from scheduler"
303 self.manage_config(cursor,
304 result['changed'])
305 else:
306 result['changed'] = True
307 result['msg'] = ("Schedule would have been deleted from" +
308 " scheduler, however check_mode is" +
309 " enabled.")
310
311 # ===========================================
312 # Module execution.
313 #
314
315
316 def main():
317 argument_spec = proxysql_common_argument_spec()
318 argument_spec.update(
319 active=dict(default=True, type='bool'),
320 interval_ms=dict(default=10000, type='int'),
321 filename=dict(required=True, type='str'),
322 arg1=dict(type='str'),
323 arg2=dict(type='str'),
324 arg3=dict(type='str'),
325 arg4=dict(type='str'),
326 arg5=dict(type='str'),
327 comment=dict(type='str'),
328 state=dict(default='present', choices=['present',
329 'absent']),
330 force_delete=dict(default=False, type='bool'),
331 save_to_disk=dict(default=True, type='bool'),
332 load_to_runtime=dict(default=True, type='bool')
333 )
334
335 module = AnsibleModule(
336 supports_check_mode=True,
337 argument_spec=argument_spec
338 )
339
340 perform_checks(module)
341
342 login_user = module.params["login_user"]
343 login_password = module.params["login_password"]
344 config_file = module.params["config_file"]
345
346 cursor = None
347 try:
348 cursor, db_conn, version = mysql_connect(module,
349 login_user,
350 login_password,
351 config_file,
352 cursor_class='DictCursor')
353 except mysql_driver.Error as e:
354 module.fail_json(
355 msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e)
356 )
357
358 proxysql_schedule = ProxySQLSchedule(module)
359 result = {}
360
361 result['state'] = proxysql_schedule.state
362 result['filename'] = proxysql_schedule.filename
363
364 if proxysql_schedule.state == "present":
365 try:
366 if proxysql_schedule.check_schedule_config(cursor) <= 0:
367 proxysql_schedule.create_schedule(module.check_mode,
368 result,
369 cursor)
370 else:
371 result['changed'] = False
372 result['msg'] = ("The schedule already exists and doesn't" +
373 " need to be updated.")
374 result['schedules'] = \
375 proxysql_schedule.get_schedule_config(cursor)
376 except mysql_driver.Error as e:
377 module.fail_json(
378 msg="unable to modify schedule.. %s" % to_native(e)
379 )
380
381 elif proxysql_schedule.state == "absent":
382 try:
383 existing_schedules = \
384 proxysql_schedule.check_schedule_config(cursor)
385 if existing_schedules > 0:
386 if existing_schedules == 1 or proxysql_schedule.force_delete:
387 proxysql_schedule.delete_schedule(module.check_mode,
388 result,
389 cursor)
390 else:
391 module.fail_json(
392 msg=("Operation would delete multiple records" +
393 " use force_delete to override this")
394 )
395 else:
396 result['changed'] = False
397 result['msg'] = ("The schedule is already absent from the" +
398 " memory configuration")
399 except mysql_driver.Error as e:
400 module.fail_json(
401 msg="unable to remove schedule.. %s" % to_native(e)
402 )
403
404 module.exit_json(**result)
405
406
407 if __name__ == '__main__':
408 main()