Debian Codegraph @

ansible_collections/community/general/plugins/modules/pubnub_blocks.py

raw
1 #!/usr/bin/python
2 #
3 # PubNub Real-time Cloud-Hosted Push API and Push Notification Client
4 # Frameworks
5 # Copyright (C) 2016 PubNub Inc.
6 # http://www.pubnub.com/
7 # http://www.pubnub.com/terms
8 #
9 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
10 # SPDX-License-Identifier: GPL-3.0-or-later
11
12 from __future__ import annotations
13
14 DOCUMENTATION = r"""
15 module: pubnub_blocks
16 short_description: PubNub blocks management module
17 description:
18 - 'This module allows Ansible to interface with the PubNub BLOCKS infrastructure by providing the following operations:
19 create / remove, start / stop and rename for blocks and create / modify / remove for event handlers.'
20 author:
21 - PubNub <[email protected]> (@pubnub)
22 - Sergey Mamontov <[email protected]> (@parfeon)
23 requirements:
24 - "pubnub_blocks_client >= 1.0"
25 extends_documentation_fragment:
26 - community.general._attributes
27 attributes:
28 check_mode:
29 support: full
30 diff_mode:
31 support: none
32 options:
33 email:
34 description:
35 - Email from account for which new session should be started.
36 - Not required if O(cache) contains result of previous module call (in same play).
37 type: str
38 default: ''
39 password:
40 description:
41 - Password which match to account to which specified O(email) belong.
42 - Not required if O(cache) contains result of previous module call (in same play).
43 type: str
44 default: ''
45 cache:
46 description: >-
47 In case if single play use blocks management module few times it is preferred to enabled 'caching' by making previous
48 module to share gathered artifacts and pass them to this parameter.
49 type: dict
50 default: {}
51 account:
52 description:
53 - Name of PubNub account for from which O(application) is used to manage blocks.
54 - User's account is used if value not set or empty.
55 type: str
56 default: ''
57 application:
58 description:
59 - Name of target PubNub application for which blocks configuration on specific O(keyset) is done.
60 type: str
61 required: true
62 keyset:
63 description:
64 - Name of application's keys set which is bound to managed blocks.
65 type: str
66 required: true
67 state:
68 description:
69 - Intended block state after event handlers creation / update process is completed.
70 default: 'present'
71 choices: ['started', 'stopped', 'present', 'absent']
72 type: str
73 name:
74 description:
75 - Name of managed block which is later visible on admin.pubnub.com.
76 required: true
77 type: str
78 description:
79 description:
80 - Short block description which is later visible on U(https://admin.pubnub.com).
81 - Used only if block does not exists and does not change description for existing block.
82 type: str
83 event_handlers:
84 description:
85 - List of event handlers which should be updated for specified block O(name).
86 - 'Each entry for new event handler should contain: V(name), V(src), V(channels), V(event). V(name) used as event handler
87 name which can be used later to make changes to it.'
88 - C(src) is full path to file with event handler code.
89 - V(channels) is name of channel from which event handler is waiting for events.
90 - 'V(event) is type of event which is able to trigger event handler: V(js-before-publish), V(js-after-publish), V(js-after-presence).'
91 - Each entry for existing handlers should contain C(name) (so target handler can be identified). Rest parameters (C(src),
92 C(channels) and C(event)) can be added if changes required for them.
93 - It is possible to rename event handler by adding C(changes) key to event handler payload and pass dictionary, which
94 contains single key C(name), where new name should be passed.
95 - To remove particular event handler it is possible to set C(state) for it to C(absent) and it is removed.
96 default: []
97 type: list
98 elements: dict
99 changes:
100 description:
101 - List of fields which should be changed by block itself (does not affect any event handlers).
102 - 'Possible options for change is: O(name).'
103 default: {}
104 type: dict
105 validate_certs:
106 description:
107 - This key allow to try skip certificates check when performing REST API calls. Sometimes host may have issues with
108 certificates on it and this causes problems to call PubNub REST API.
109 - If check should be ignored V(false) should be passed to this parameter.
110 default: true
111 type: bool
112 """
113
114 EXAMPLES = r"""
115 # Event handler create example.
116 - name: Create single event handler
117 community.general.pubnub_blocks:
118 email: '{{ email }}'
119 password: '{{ password }}'
120 application: '{{ app_name }}'
121 keyset: '{{ keyset_name }}'
122 name: '{{ block_name }}'
123 event_handlers:
124 - src: '{{ path_to_handler_source }}'
125 name: '{{ handler_name }}'
126 event: 'js-before-publish'
127 channels: '{{ handler_channel }}'
128
129 # Change event handler trigger event type.
130 - name: Change event handler 'event'
131 community.general.pubnub_blocks:
132 email: '{{ email }}'
133 password: '{{ password }}'
134 application: '{{ app_name }}'
135 keyset: '{{ keyset_name }}'
136 name: '{{ block_name }}'
137 event_handlers:
138 - name: '{{ handler_name }}'
139 event: 'js-after-publish'
140
141 # Stop block and event handlers.
142 - name: Stopping block
143 community.general.pubnub_blocks:
144 email: '{{ email }}'
145 password: '{{ password }}'
146 application: '{{ app_name }}'
147 keyset: '{{ keyset_name }}'
148 name: '{{ block_name }}'
149 state: stop
150
151 # Multiple module calls with cached result passing
152 - name: Create '{{ block_name }}' block
153 register: module_cache
154 community.general.pubnub_blocks:
155 email: '{{ email }}'
156 password: '{{ password }}'
157 application: '{{ app_name }}'
158 keyset: '{{ keyset_name }}'
159 name: '{{ block_name }}'
160 state: present
161 - name: Add '{{ event_handler_1_name }}' handler to '{{ block_name }}'
162 register: module_cache
163 community.general.pubnub_blocks:
164 cache: '{{ module_cache }}'
165 application: '{{ app_name }}'
166 keyset: '{{ keyset_name }}'
167 name: '{{ block_name }}'
168 state: present
169 event_handlers:
170 - src: '{{ path_to_handler_1_source }}'
171 name: '{{ event_handler_1_name }}'
172 channels: '{{ event_handler_1_channel }}'
173 event: 'js-before-publish'
174 - name: Add '{{ event_handler_2_name }}' handler to '{{ block_name }}'
175 register: module_cache
176 community.general.pubnub_blocks:
177 cache: '{{ module_cache }}'
178 application: '{{ app_name }}'
179 keyset: '{{ keyset_name }}'
180 name: '{{ block_name }}'
181 state: present
182 event_handlers:
183 - src: '{{ path_to_handler_2_source }}'
184 name: '{{ event_handler_2_name }}'
185 channels: '{{ event_handler_2_channel }}'
186 event: 'js-before-publish'
187 - name: Start '{{ block_name }}' block
188 register: module_cache
189 community.general.pubnub_blocks:
190 cache: '{{ module_cache }}'
191 application: '{{ app_name }}'
192 keyset: '{{ keyset_name }}'
193 name: '{{ block_name }}'
194 state: started
195 """
196
197 RETURN = r"""
198 module_cache:
199 description:
200 - Cached account information. In case if with single play module used few times it is better to pass cached data to next
201 module calls to speed up process.
202 type: dict
203 returned: always
204 """
205 import copy
206 import os
207
208 try:
209 # Import PubNub BLOCKS client.
210 from pubnub_blocks_client import Block, EventHandler, User, exceptions
211
212 HAS_PUBNUB_BLOCKS_CLIENT = True
213 except ImportError:
214 HAS_PUBNUB_BLOCKS_CLIENT = False
215 User = None
216 Account = None
217 Owner = None
218 Application = None
219 Keyset = None
220 Block = None
221 EventHandler = None
222 exceptions = None
223
224 from ansible.module_utils.basic import AnsibleModule
225 from ansible.module_utils.common.text.converters import to_text
226
227
228 def pubnub_user(module):
229 """Create and configure user model if it possible.
230
231 :type module: AnsibleModule
232 :param module: Reference on module which contain module launch
233 information and status report methods.
234
235 :rtype: User
236 :return: Reference on initialized and ready to use user or 'None' in
237 case if not all required information has been passed to block.
238 """
239 user = None
240 params = module.params
241
242 if params.get("cache") and params["cache"].get("module_cache"):
243 cache = params["cache"]["module_cache"]
244 user = User()
245 user.restore(cache=copy.deepcopy(cache["pnm_user"]))
246 elif params.get("email") and params.get("password"):
247 user = User(email=params.get("email"), password=params.get("password"))
248 else:
249 err_msg = (
250 "It looks like not account credentials has been passed or "
251 "'cache' field doesn't have result of previous module "
252 "call."
253 )
254 module.fail_json(msg="Missing account credentials.", description=err_msg, changed=False)
255
256 return user
257
258
259 def pubnub_account(module, user):
260 """Create and configure account if it is possible.
261
262 :type module: AnsibleModule
263 :param module: Reference on module which contain module launch
264 information and status report methods.
265 :type user: User
266 :param user: Reference on authorized user for which one of accounts
267 should be used during manipulations with block.
268
269 :rtype: Account
270 :return: Reference on initialized and ready to use account or 'None' in
271 case if not all required information has been passed to block.
272 """
273 params = module.params
274 if params.get("account"):
275 account_name = params.get("account")
276 account = user.account(name=params.get("account"))
277 if account is None:
278 module.fail_json(
279 msg="Missing account.",
280 description=(
281 f"It looks like there is no '{account_name}' account for authorized user. "
282 "Please make sure what correct name has been passed during module configuration."
283 ),
284 changed=False,
285 )
286 else:
287 account = user.accounts()[0]
288
289 return account
290
291
292 def pubnub_application(module, account):
293 """Retrieve reference on target application from account model.
294
295 NOTE: In case if account authorization will fail or there is no
296 application with specified name, module will exit with error.
297 :type module: AnsibleModule
298 :param module: Reference on module which contain module launch
299 information and status report methods.
300 :type account: Account
301 :param account: Reference on PubNub account model from which reference
302 on application should be fetched.
303
304 :rtype: Application
305 :return: Reference on initialized and ready to use application model.
306 """
307 application = None
308 params = module.params
309 try:
310 application = account.application(params["application"])
311 except (exceptions.AccountError, exceptions.GeneralPubNubError) as exc:
312 exc_msg = _failure_title_from_exception(exc)
313 exc_descr = exc.message if hasattr(exc, "message") else exc.args[0]
314 module.fail_json(msg=exc_msg, description=exc_descr, changed=account.changed, module_cache=dict(account))
315
316 if application is None:
317 email = account.owner.email
318 module.fail_json(
319 msg=(
320 f"There is no '{params['application']}' application for {email}. "
321 "Make sure what correct application name has been passed. "
322 "If application doesn't exist you can create it on admin.pubnub.com."
323 ),
324 changed=account.changed,
325 module_cache=dict(account),
326 )
327
328 return application
329
330
331 def pubnub_keyset(module, account, application):
332 """Retrieve reference on target keyset from application model.
333
334 NOTE: In case if there is no keyset with specified name, module will
335 exit with error.
336 :type module: AnsibleModule
337 :param module: Reference on module which contain module launch
338 information and status report methods.
339 :type account: Account
340 :param account: Reference on PubNub account model which will be
341 used in case of error to export cached data.
342 :type application: Application
343 :param application: Reference on PubNub application model from which
344 reference on keyset should be fetched.
345
346 :rtype: Keyset
347 :return: Reference on initialized and ready to use keyset model.
348 """
349 params = module.params
350 keyset = application.keyset(params["keyset"])
351 if keyset is None:
352 module.fail_json(
353 msg=(
354 f"There is no '{params['keyset']}' keyset for '{application.name}' application. "
355 "Make sure what correct keyset name has been passed. "
356 "If keyset doesn't exist you can create it on admin.pubnub.com."
357 ),
358 changed=account.changed,
359 module_cache=dict(account),
360 )
361
362 return keyset
363
364
365 def pubnub_block(module, account, keyset):
366 """Retrieve reference on target keyset from application model.
367
368 NOTE: In case if there is no block with specified name and module
369 configured to start/stop it, module will exit with error.
370 :type module: AnsibleModule
371 :param module: Reference on module which contain module launch
372 information and status report methods.
373 :type account: Account
374 :param account: Reference on PubNub account model which will be used in
375 case of error to export cached data.
376 :type keyset: Keyset
377 :param keyset: Reference on keyset model from which reference on block
378 should be fetched.
379
380 :rtype: Block
381 :return: Reference on initialized and ready to use keyset model.
382 """
383 block = None
384 params = module.params
385 try:
386 block = keyset.block(params["name"])
387 except (exceptions.KeysetError, exceptions.GeneralPubNubError) as exc:
388 exc_msg = _failure_title_from_exception(exc)
389 exc_descr = exc.message if hasattr(exc, "message") else exc.args[0]
390 module.fail_json(msg=exc_msg, description=exc_descr, changed=account.changed, module_cache=dict(account))
391
392 # Report error because block doesn't exists and at the same time
393 # requested to start/stop.
394 if block is None and params["state"] in ["started", "stopped"]:
395 block_name = params.get("name")
396 module.fail_json(
397 msg=f"'{block_name}' block doesn't exists.", changed=account.changed, module_cache=dict(account)
398 )
399
400 if block is None and params["state"] == "present":
401 block = Block(name=params.get("name"), description=params.get("description"))
402 keyset.add_block(block)
403
404 if block:
405 # Update block information if required.
406 if params.get("changes") and params["changes"].get("name"):
407 block.name = params["changes"]["name"]
408 if params.get("description"):
409 block.description = params.get("description")
410
411 return block
412
413
414 def pubnub_event_handler(block, data):
415 """Retrieve reference on target event handler from application model.
416
417 :type block: Block
418 :param block: Reference on block model from which reference on event
419 handlers should be fetched.
420 :type data: dict
421 :param data: Reference on dictionary which contain information about
422 event handler and whether it should be created or not.
423
424 :rtype: EventHandler
425 :return: Reference on initialized and ready to use event handler model.
426 'None' will be returned in case if there is no handler with
427 specified name and no request to create it.
428 """
429 event_handler = block.event_handler(data["name"])
430
431 # Prepare payload for event handler update.
432 changed_name = data.pop("changes").get("name") if "changes" in data else None
433 name = data.get("name") or changed_name
434 channels = data.get("channels")
435 event = data.get("event")
436 code = _content_of_file_at_path(data.get("src"))
437 state = data.get("state") or "present"
438
439 # Create event handler if required.
440 if event_handler is None and state == "present":
441 event_handler = EventHandler(name=name, channels=channels, event=event, code=code)
442 block.add_event_handler(event_handler)
443
444 # Update event handler if required.
445 if event_handler is not None and state == "present":
446 if name is not None:
447 event_handler.name = name
448 if channels is not None:
449 event_handler.channels = channels
450 if event is not None:
451 event_handler.event = event
452 if code is not None:
453 event_handler.code = code
454
455 return event_handler
456
457
458 def _failure_title_from_exception(exception):
459 """Compose human-readable title for module error title.
460
461 Title will be based on status codes if they has been provided.
462 :type exception: exceptions.GeneralPubNubError
463 :param exception: Reference on exception for which title should be
464 composed.
465
466 :rtype: str
467 :return: Reference on error tile which should be shown on module
468 failure.
469 """
470 title = "General REST API access error."
471 if exception.code == exceptions.PN_AUTHORIZATION_MISSING_CREDENTIALS:
472 title = "Authorization error: missing credentials."
473 elif exception.code == exceptions.PN_AUTHORIZATION_WRONG_CREDENTIALS:
474 title = "Authorization error: wrong credentials."
475 elif exception.code == exceptions.PN_USER_INSUFFICIENT_RIGHTS:
476 title = "API access error: insufficient access rights."
477 elif exception.code == exceptions.PN_API_ACCESS_TOKEN_EXPIRED:
478 title = "API access error: time token expired."
479 elif exception.code == exceptions.PN_KEYSET_BLOCK_EXISTS:
480 title = "Block create did fail: block with same name already exists)."
481 elif exception.code == exceptions.PN_KEYSET_BLOCKS_FETCH_DID_FAIL:
482 title = "Unable fetch list of blocks for keyset."
483 elif exception.code == exceptions.PN_BLOCK_CREATE_DID_FAIL:
484 title = "Block creation did fail."
485 elif exception.code == exceptions.PN_BLOCK_UPDATE_DID_FAIL:
486 title = "Block update did fail."
487 elif exception.code == exceptions.PN_BLOCK_REMOVE_DID_FAIL:
488 title = "Block removal did fail."
489 elif exception.code == exceptions.PN_BLOCK_START_STOP_DID_FAIL:
490 title = "Block start/stop did fail."
491 elif exception.code == exceptions.PN_EVENT_HANDLER_MISSING_FIELDS:
492 title = "Event handler creation did fail: missing fields."
493 elif exception.code == exceptions.PN_BLOCK_EVENT_HANDLER_EXISTS:
494 title = "Event handler creation did fail: missing fields."
495 elif exception.code == exceptions.PN_EVENT_HANDLER_CREATE_DID_FAIL:
496 title = "Event handler creation did fail."
497 elif exception.code == exceptions.PN_EVENT_HANDLER_UPDATE_DID_FAIL:
498 title = "Event handler update did fail."
499 elif exception.code == exceptions.PN_EVENT_HANDLER_REMOVE_DID_FAIL:
500 title = "Event handler removal did fail."
501
502 return title
503
504
505 def _content_of_file_at_path(path):
506 """Read file content.
507
508 Try read content of file at specified path.
509 :type path: str
510 :param path: Full path to location of file which should be read'ed.
511 :rtype: content
512 :return: File content or 'None'
513 """
514 content = None
515 if path and os.path.exists(path):
516 with open(path) as opened_file:
517 b_content = opened_file.read()
518 try:
519 content = to_text(b_content, errors="surrogate_or_strict")
520 except UnicodeError:
521 pass
522
523 return content
524
525
526 def main():
527 fields = dict(
528 email=dict(default="", type="str"),
529 password=dict(default="", type="str", no_log=True),
530 account=dict(default="", type="str"),
531 application=dict(required=True, type="str"),
532 keyset=dict(required=True, type="str", no_log=False),
533 state=dict(default="present", type="str", choices=["started", "stopped", "present", "absent"]),
534 name=dict(required=True, type="str"),
535 description=dict(type="str"),
536 event_handlers=dict(default=list(), type="list", elements="dict"),
537 changes=dict(default=dict(), type="dict"),
538 cache=dict(default=dict(), type="dict"),
539 validate_certs=dict(default=True, type="bool"),
540 )
541 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
542
543 if not HAS_PUBNUB_BLOCKS_CLIENT:
544 module.fail_json(msg="pubnub_blocks_client required for this module.")
545
546 params = module.params
547
548 # Authorize user.
549 user = pubnub_user(module)
550 # Initialize PubNub account instance.
551 account = pubnub_account(module, user=user)
552 # Try fetch application with which module should work.
553 application = pubnub_application(module, account=account)
554 # Try fetch keyset with which module should work.
555 keyset = pubnub_keyset(module, account=account, application=application)
556 # Try fetch block with which module should work.
557 block = pubnub_block(module, account=account, keyset=keyset)
558 is_new_block = block is not None and block.uid == -1
559
560 # Check whether block should be removed or not.
561 if block is not None and params["state"] == "absent":
562 keyset.remove_block(block)
563 block = None
564
565 if block is not None:
566 # Update block information if required.
567 if params.get("changes") and params["changes"].get("name"):
568 block.name = params["changes"]["name"]
569
570 # Process event changes to event handlers.
571 for event_handler_data in params.get("event_handlers") or list():
572 state = event_handler_data.get("state") or "present"
573 event_handler = pubnub_event_handler(data=event_handler_data, block=block)
574 if state == "absent" and event_handler:
575 block.delete_event_handler(event_handler)
576
577 # Update block operation state if required.
578 if block and not is_new_block:
579 if params["state"] == "started":
580 block.start()
581 elif params["state"] == "stopped":
582 block.stop()
583
584 # Save current account state.
585 if not module.check_mode:
586 try:
587 account.save()
588 except (
589 exceptions.APIAccessError,
590 exceptions.KeysetError,
591 exceptions.BlockError,
592 exceptions.EventHandlerError,
593 exceptions.GeneralPubNubError,
594 ) as exc:
595 module_cache = dict(account)
596 module_cache.update(dict(pnm_user=dict(user)))
597 exc_msg = _failure_title_from_exception(exc)
598 exc_descr = exc.message if hasattr(exc, "message") else exc.args[0]
599 module.fail_json(msg=exc_msg, description=exc_descr, changed=account.changed, module_cache=module_cache)
600
601 # Report module execution results.
602 module_cache = dict(account)
603 module_cache.update(dict(pnm_user=dict(user)))
604 changed_will_change = account.changed or account.will_change
605 module.exit_json(changed=changed_will_change, module_cache=module_cache)
606
607
608 if __name__ == "__main__":
609 main()