Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, Ivan Vanderbyl <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: logentries
11 author: "Ivan Vanderbyl (@ivanvanderbyl)"
12 short_description: Module for tracking logs using U(logentries.com)
13 description:
14 - Sends logs to LogEntries in realtime.
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: full
20 diff_mode:
21 support: none
22 options:
23 path:
24 type: str
25 description:
26 - Path to a log file.
27 required: true
28 state:
29 type: str
30 description:
31 - Following state of the log.
32 choices: ['present', 'absent', 'followed', 'unfollowed']
33 default: present
34 name:
35 type: str
36 description:
37 - Name of the log.
38 logtype:
39 type: str
40 description:
41 - Type of the log.
42 aliases: [type]
43
44 notes:
45 - Requires the LogEntries agent which can be installed following the instructions at U(logentries.com).
46 """
47
48 EXAMPLES = r"""
49 - name: Track nginx logs
50 community.general.logentries:
51 path: /var/log/nginx/access.log
52 state: present
53 name: nginx-access-log
54
55 - name: Stop tracking nginx logs
56 community.general.logentries:
57 path: /var/log/nginx/error.log
58 state: absent
59 """
60
61 from ansible.module_utils.basic import AnsibleModule
62
63
64 def query_log_status(module, le_path, path, state="present"):
65 """Returns whether a log is followed or not."""
66
67 if state == "present":
68 rc, out, err = module.run_command([le_path, "followed", path])
69 return rc == 0
70
71
72 def follow_log(module, le_path, logs, name=None, logtype=None):
73 """Follows one or more logs if not already followed."""
74
75 followed_count = 0
76
77 for log in logs:
78 if query_log_status(module, le_path, log):
79 continue
80
81 if module.check_mode:
82 module.exit_json(changed=True)
83
84 cmd = [le_path, "follow", log]
85 if name:
86 cmd.extend(["--name", name])
87 if logtype:
88 cmd.extend(["--type", logtype])
89 rc, out, err = module.run_command(cmd)
90
91 if not query_log_status(module, le_path, log):
92 module.fail_json(msg=f"failed to follow '{log}': {err.strip()}")
93
94 followed_count += 1
95
96 if followed_count > 0:
97 module.exit_json(changed=True, msg=f"followed {followed_count} log(s)")
98
99 module.exit_json(changed=False, msg="logs(s) already followed")
100
101
102 def unfollow_log(module, le_path, logs):
103 """Unfollows one or more logs if followed."""
104
105 removed_count = 0
106
107 # Using a for loop in case of error, we can report the package that failed
108 for log in logs:
109 # Query the log first, to see if we even need to remove.
110 if not query_log_status(module, le_path, log):
111 continue
112
113 if module.check_mode:
114 module.exit_json(changed=True)
115 rc, out, err = module.run_command([le_path, "rm", log])
116
117 if query_log_status(module, le_path, log):
118 module.fail_json(msg=f"failed to remove '{log}': {err.strip()}")
119
120 removed_count += 1
121
122 if removed_count > 0:
123 module.exit_json(changed=True, msg=f"removed {removed_count} package(s)")
124
125 module.exit_json(changed=False, msg="logs(s) already unfollowed")
126
127
128 def main():
129 module = AnsibleModule(
130 argument_spec=dict(
131 path=dict(required=True),
132 state=dict(default="present", choices=["present", "followed", "absent", "unfollowed"]),
133 name=dict(type="str"),
134 logtype=dict(type="str", aliases=["type"]),
135 ),
136 supports_check_mode=True,
137 )
138
139 le_path = module.get_bin_path("le", True, ["/usr/local/bin"])
140
141 p = module.params
142
143 # Handle multiple log files
144 logs = p["path"].split(",")
145 logs = [_f for _f in logs if _f]
146
147 if p["state"] in ["present", "followed"]:
148 follow_log(module, le_path, logs, name=p["name"], logtype=p["logtype"])
149
150 elif p["state"] in ["absent", "unfollowed"]:
151 unfollow_log(module, le_path, logs)
152
153
154 if __name__ == "__main__":
155 main()