pandoraPlugintools-basic 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,249 @@
1
+ import sys
2
+ from queue import Queue
3
+ from threading import Thread
4
+ from multiprocessing import Pool, Manager
5
+
6
+ ####
7
+ # Define multi-processing internal global variables.
8
+ #########################################################################################
9
+
10
+ _MANAGER = Manager()
11
+ _SHARED_DICT = _MANAGER.dict()
12
+ _SHARED_DICT_LOCK = _MANAGER.Lock()
13
+
14
+ ####
15
+ # Internal: Alias for output.print_debug function
16
+ #########################################################################################
17
+
18
+ def _print_debug(
19
+ var = "",
20
+ print_errors: bool = False
21
+ ):
22
+ """
23
+ Prints the provided variable in a JSON-like format.
24
+
25
+ Args:
26
+ var: The variable (list, dict, string, float, integer) to be printed.
27
+ print_errors (bool): If True, prints any errors that occur during formatting.
28
+ """
29
+ from .output import print_debug
30
+ print_debug(var, print_errors)
31
+
32
+ ####
33
+ # Internal use only: Run a given function in a thread
34
+ #########################################################################################
35
+ def _single_thread(
36
+ q = None,
37
+ function: callable = None,
38
+ errors: list = []
39
+ ):
40
+ """
41
+ Internal use only: Runs a given function in a thread.
42
+
43
+ Args:
44
+ q: A queue from which to get parameters for the function.
45
+ function (callable): The function to be executed in the thread.
46
+ errors (list): A list to store any errors encountered during execution.
47
+ """
48
+ params=q.get()
49
+ q.task_done()
50
+ try:
51
+ function(params)
52
+ except Exception as e:
53
+ errors.append("Error while runing single thread: "+str(e))
54
+
55
+ ####
56
+ # Run a given function for given items list in a given number of threads
57
+ #########################################################################################
58
+ def run_threads(
59
+ max_threads: int = 1,
60
+ function: callable = None,
61
+ items: list = [],
62
+ print_errors: bool = False
63
+ ) -> bool:
64
+ """
65
+ Run a given function for a list of items in multiple threads.
66
+
67
+ Args:
68
+ max_threads (int): Maximum number of threads to use.
69
+ function (callable): The function to be executed in each thread.
70
+ items (list): List of items to process.
71
+ print_errors (bool): Whether to print errors encountered during execution.
72
+
73
+ Returns:
74
+ bool: True if all threads executed successfully, False otherwise.
75
+ """
76
+ from .output import print_stderr
77
+
78
+ # Assign threads
79
+ threads = max_threads
80
+
81
+ if threads > len(items):
82
+ threads = len(items)
83
+
84
+ if threads < 1:
85
+ threads = 1
86
+
87
+ # Distribute items per thread
88
+ items_per_thread = []
89
+ thread = 0
90
+ for item in items:
91
+ if not 0 <= thread < len(items_per_thread):
92
+ items_per_thread.append([])
93
+
94
+ items_per_thread[thread].append(item)
95
+
96
+ thread += 1
97
+ if thread >= threads:
98
+ thread=0
99
+
100
+ # Run threads
101
+ try:
102
+ q=Queue()
103
+ for n_thread in range(threads) :
104
+ q.put(items_per_thread[n_thread])
105
+
106
+ run_threads = []
107
+ errors = []
108
+
109
+ for n_thread in range(threads):
110
+ t = Thread(target=_single_thread, args=(q, function, errors))
111
+ t.daemon=True
112
+ t.start()
113
+ run_threads.append(t)
114
+
115
+ for t in run_threads:
116
+ t.join()
117
+
118
+ q.join()
119
+
120
+ if print_errors:
121
+ for error in errors:
122
+ print_stderr(str(error))
123
+
124
+ if len(errors) > 0:
125
+ return False
126
+ else:
127
+ return True
128
+
129
+ except Exception as e:
130
+ if print_errors:
131
+ print_stderr("Error while running threads: "+str(e))
132
+ return False
133
+
134
+ ####
135
+ # Set a given value to a key in the internal shared dict.
136
+ # Used by all parallel processes.
137
+ #########################################################################################
138
+ def set_shared_dict_value(
139
+ key: str = None,
140
+ value = None
141
+ )-> None:
142
+ """
143
+ Set a value for a key in the internal shared dictionary.
144
+ This function is used by all parallel processes.
145
+
146
+ Args:
147
+ key (str): The key in the shared dictionary.
148
+ value: The value to be assigned to the key.
149
+ """
150
+ global _SHARED_DICT
151
+
152
+ if key is not None:
153
+ with _SHARED_DICT_LOCK:
154
+ _SHARED_DICT[key] = value
155
+
156
+ ####
157
+ # Add a given value to a key in the internal shared dict.
158
+ # Used by all parallel processes.
159
+ #########################################################################################
160
+ def add_shared_dict_value(
161
+ key: str = None,
162
+ value = None
163
+ )-> None:
164
+ """
165
+ Add a value to a key in the internal shared dictionary.
166
+ This function is used by all parallel processes.
167
+
168
+ Args:
169
+ key (str): The key in the shared dictionary.
170
+ value: The value to be added to the key.
171
+ """
172
+ global _SHARED_DICT
173
+
174
+ if key is not None:
175
+ with _SHARED_DICT_LOCK:
176
+ if key in _SHARED_DICT:
177
+ _SHARED_DICT[key] += value
178
+ else:
179
+ set_shared_dict_value(key, value)
180
+
181
+ ####
182
+ # Get the value of a key in the internal shared dict.
183
+ # Used by all parallel processes.
184
+ #########################################################################################
185
+ def get_shared_dict_value(
186
+ key: str = None
187
+ ):
188
+ """
189
+ Get the value of a key in the internal shared dictionary.
190
+ This function is used by all parallel processes.
191
+
192
+ Args:
193
+ key (str): The key in the shared dictionary.
194
+
195
+ Returns:
196
+ The value associated with the key, or None if the key does not exist.
197
+ """
198
+ global _SHARED_DICT
199
+
200
+ with _SHARED_DICT_LOCK:
201
+ if key in _SHARED_DICT and key is not None:
202
+ return _SHARED_DICT[key]
203
+ else:
204
+ return None
205
+
206
+ ####
207
+ # Run a given function for given items list in a given number of processes
208
+ # Given function receives each item as first parameter
209
+ #########################################################################################
210
+ def run_processes(
211
+ max_processes: int = 1,
212
+ function: callable = None,
213
+ items: list = [],
214
+ print_errors: bool = False
215
+ ) -> bool:
216
+ """
217
+ Run a given function for given items list in a given number of processes
218
+
219
+ Args:
220
+ max_processes (int): The maximum number of processes to run in parallel.
221
+ function (callable): The function to be executed for each item.
222
+ items (list): List of items to be processed.
223
+ print_errors (bool): Whether to print errors.
224
+
225
+ Returns:
226
+ bool: True if all processes completed successfully, False otherwise.
227
+ """
228
+ from .output import print_stderr
229
+
230
+ # Assign processes
231
+ processes = max_processes
232
+
233
+ if processes > len(items):
234
+ processes = len(items)
235
+
236
+ if processes < 1:
237
+ processes = 1
238
+
239
+ # Run processes
240
+ with Pool(processes) as pool:
241
+ try:
242
+ pool.map(function, items)
243
+ result = True
244
+ except Exception as error:
245
+ if print_errors:
246
+ print_stderr(str(error))
247
+ result = False
248
+
249
+ return result
@@ -0,0 +1,258 @@
1
+ from datetime import datetime
2
+ from subprocess import *
3
+ import shutil
4
+ import subprocess
5
+ import os
6
+ import sys
7
+
8
+ ####
9
+ # Define global variables dict, used in functions as default values.
10
+ # Its values can be changed.
11
+ #########################################################################################
12
+
13
+ _GLOBAL_VARIABLES = {
14
+ 'transfer_mode' : 'tentacle',
15
+ 'temporal' : '/tmp',
16
+ 'data_dir' : '/var/spool/pandora/data_in/',
17
+ 'tentacle_client' : 'tentacle_client',
18
+ 'tentacle_ip' : '127.0.0.1',
19
+ 'tentacle_port' : 41121,
20
+ 'tentacle_extra_opts' : '',
21
+ 'tentacle_retries' : 1
22
+ }
23
+
24
+ ####
25
+ # Internal: Alias for output.print_debug function
26
+ #########################################################################################
27
+
28
+ def _print_debug(
29
+ var = "",
30
+ print_errors: bool = False
31
+ ):
32
+ """
33
+ Prints any list, dict, string, float or integer as a json
34
+
35
+ Args:
36
+ var: The variable to be printed.
37
+ print_errors (bool): Whether to print errors.
38
+ """
39
+ from .output import print_debug
40
+ print_debug(var, print_errors)
41
+
42
+ ####
43
+ # Set a global variable with the specified name and assigns a value to it.
44
+ #########################################################################################
45
+ def set_global_variable(
46
+ variable_name: str = "",
47
+ value = None
48
+ )-> None:
49
+ """
50
+ Sets the value of a global variable in the '_GLOBAL_VARIABLES' dictionary.
51
+
52
+ Args:
53
+ variable_name (str): Name of the variable to set.
54
+ value (any): Value to assign to the variable.
55
+
56
+ Returns:
57
+ None
58
+ """
59
+ from .general import set_dict_key_value
60
+
61
+ set_dict_key_value(_GLOBAL_VARIABLES, variable_name, value)
62
+
63
+ ####
64
+ # Get a global variable with the specified name.
65
+ #########################################################################################
66
+ def get_global_variable(
67
+ variable_name: str = ""
68
+ )-> None:
69
+ """
70
+ Gets the value of a global variable in the '_GLOBAL_VARIABLES' dictionary.
71
+
72
+ Args:
73
+ variable_name (str): Name of the variable to set.
74
+
75
+ Returns:
76
+ None
77
+ """
78
+ from .general import get_dict_key_value
79
+
80
+ get_dict_key_value(_GLOBAL_VARIABLES, variable_name)
81
+
82
+ ####
83
+ # Sends file using tentacle protocol
84
+ #########################################################################################
85
+ def tentacle_xml(
86
+ data_file: str = "",
87
+ tentacle_ops: dict = {},
88
+ tentacle_path: str = _GLOBAL_VARIABLES['tentacle_client'],
89
+ retry: bool = False,
90
+ debug: int = 0,
91
+ print_errors: bool = True
92
+ ) -> bool:
93
+ """
94
+ Sends file using tentacle protocol
95
+
96
+ Args:
97
+ data_file (str): Path to the data file to be sent.
98
+ tentacle_ops (dict): Tentacle options as a dictionary (address [password] [port]).
99
+ tentacle_path (str): Custom path for the tentacle client executable.
100
+ retry (bool): Whether to retry sending the file if it fails.
101
+ debug (int): Debug mode flag. If enabled (1), the data file will not be removed after sending.
102
+ print_errors (bool): Whether to print error messages.
103
+
104
+ Returns:
105
+ bool: True for success, False for errors.
106
+ """
107
+ from .output import print_stderr
108
+
109
+ if data_file is not None :
110
+
111
+ if not 'address' in tentacle_ops:
112
+ tentacle_ops['address'] = _GLOBAL_VARIABLES['tentacle_ip']
113
+ if not 'port' in tentacle_ops:
114
+ tentacle_ops['port'] = _GLOBAL_VARIABLES['tentacle_port']
115
+ if not 'extra_opts' in tentacle_ops:
116
+ tentacle_ops['extra_opts'] = _GLOBAL_VARIABLES['tentacle_extra_opts']
117
+
118
+ if tentacle_ops['address'] is None :
119
+ if print_errors:
120
+ print_stderr("Tentacle error: No address defined")
121
+ return False
122
+
123
+ try :
124
+ with open(data_file.strip(), 'r') as data:
125
+ data.read()
126
+ data.close()
127
+ except Exception as e :
128
+ if print_errors:
129
+ print_stderr(f"Tentacle error: {type(e).__name__} {e}")
130
+ return False
131
+
132
+ tentacle_cmd = f"{tentacle_path} -v -a {tentacle_ops['address']} -p {tentacle_ops['port']} {tentacle_ops['extra_opts']} {data_file.strip()}"
133
+ tentacle_exe=subprocess.Popen(tentacle_cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
134
+ rc=tentacle_exe.wait()
135
+
136
+ result = True
137
+
138
+ if rc != 0 :
139
+
140
+ if retry:
141
+
142
+ tentacle_retries = _GLOBAL_VARIABLES['tentacle_retries']
143
+
144
+ if tentacle_retries < 1:
145
+ tentacle_retries = 1
146
+
147
+ retry_count = 0
148
+
149
+ while retry_count < tentacle_retries :
150
+
151
+ tentacle_exe=subprocess.Popen(tentacle_cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
152
+ rc=tentacle_exe.wait()
153
+
154
+ if rc == 0:
155
+ break
156
+
157
+ if print_errors:
158
+ stderr = tentacle_exe.stderr.read().decode()
159
+ msg = f"Tentacle error (Retry {retry_count + 1}/{tentacle_retries}): {stderr}"
160
+ print_stderr(str(datetime.today().strftime('%Y-%m-%d %H:%M')) + msg)
161
+
162
+ retry_count += 1
163
+
164
+ if retry_count >= tentacle_retries:
165
+ result = False
166
+ else:
167
+
168
+ if print_errors:
169
+ stderr = tentacle_exe.stderr.read().decode()
170
+ msg="Tentacle error:" + str(stderr)
171
+ print_stderr(str(datetime.today().strftime('%Y-%m-%d %H:%M')) + msg)
172
+ result = False
173
+
174
+ if debug == 0 :
175
+ os.remove(data_file.strip())
176
+
177
+ return result
178
+
179
+ else:
180
+ if print_errors:
181
+ print_stderr("Tentacle error: file path is required.")
182
+ return False
183
+
184
+ ####
185
+ # Detect transfer mode and send XML.
186
+ #########################################################################################
187
+ def transfer_xml(
188
+ file: str = "",
189
+ transfer_mode: str = _GLOBAL_VARIABLES['transfer_mode'],
190
+ tentacle_ip: str = _GLOBAL_VARIABLES['tentacle_ip'],
191
+ tentacle_port: int = _GLOBAL_VARIABLES['tentacle_port'],
192
+ tentacle_extra_opts: str = _GLOBAL_VARIABLES['tentacle_extra_opts'],
193
+ data_dir: str = _GLOBAL_VARIABLES['data_dir']
194
+ )-> None:
195
+
196
+ """
197
+ Detects the transfer mode and calls the agentplugin() function to perform the transfer.
198
+
199
+ Args:
200
+ file (str): Path to file to send.
201
+ transfer_mode (str, optional): Transfer mode. Default is _GLOBAL_VARIABLES['transfer_mode'].
202
+ tentacle_ip (str, optional): IP address for Tentacle. Default is _GLOBAL_VARIABLES['tentacle_ip'].
203
+ tentacle_port (str, optional): Port for Tentacle. Default is _GLOBAL_VARIABLES['tentacle_port'].
204
+ data_dir (str, optional): Path to data dir with local transfer mode. Default is _GLOBAL_VARIABLES['data_dir'].
205
+
206
+ Returns:
207
+ None
208
+ """
209
+ if file is not None:
210
+ if transfer_mode != "local":
211
+ tentacle_conf = {
212
+ 'address' : tentacle_ip,
213
+ 'port' : tentacle_port,
214
+ 'extra_opts' : tentacle_extra_opts
215
+ }
216
+ tentacle_xml(file, tentacle_conf)
217
+ else:
218
+ shutil.move(file, data_dir)
219
+
220
+ ####
221
+ # Creates a agent .data file in the specified data_dir folder
222
+ #########################################################################################
223
+ def write_xml(
224
+ xml: str = "",
225
+ agent_name: str = "",
226
+ data_dir: str = _GLOBAL_VARIABLES['temporal'],
227
+ print_errors: bool = False
228
+ ) -> str:
229
+ """
230
+ Creates an agent .data file in the specified data_dir folder
231
+
232
+ Args:
233
+ xml (str): XML string to be written in the file.
234
+ agent_name (str): Agent name for the XML and file name.
235
+ data_dir (str): Folder in which the file will be created.
236
+ print_errors (bool): Whether to print error messages.
237
+
238
+ Returns:
239
+ str: Path to the created .data file.
240
+ """
241
+ from .general import generate_md5
242
+ from .output import print_stderr
243
+
244
+ Utime = datetime.now().strftime('%s')
245
+ agent_name_md5 = generate_md5(agent_name)
246
+ data_file = "%s/%s.%s.data" %(str(data_dir),agent_name_md5,str(Utime))
247
+
248
+ try:
249
+ with open(data_file, 'x') as data:
250
+ data.write(xml)
251
+ except OSError as o:
252
+ if print_errors:
253
+ print_stderr(f"ERROR - Could not write file: {o}, please check directory permissions")
254
+ except Exception as e:
255
+ if print_errors:
256
+ print_stderr(f"{type(e).__name__}: {e}")
257
+
258
+ return data_file
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.4
2
+ Name: pandoraPlugintools-basic
3
+ Version: 1.0.0
4
+ Summary: A plugin tool set of basic functions for pandorafms
5
+ Home-page: https://github.com/pandorafms/pandoraPlugintoolsBasic
6
+ Author: PandoraFMS projects department
7
+ Author-email: <info@pandorafms.com>
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: author
11
+ Dynamic: author-email
12
+ Dynamic: description
13
+ Dynamic: description-content-type
14
+ Dynamic: home-page
15
+ Dynamic: license-file
16
+ Dynamic: summary
17
+
18
+ # pandoraPlugintoolsBasic
19
+ Basic version of plugintools.
20
+
21
+ # Python: module plugintools-basic for PandoraFMS Developers
22
+
23
+ pandoraPluginToolsBasic is a library that aims to help the creation of scripts and their integration in Pandora FMS. This is a simplified and lighter version. If you want to use the plugin tools with SNMP or encryption functions, it is recommended to use the standard version.
24
+
25
+ [PluginTools Reference Documentation](https://pandorafms.com/guides/public/books/plugintools)
26
+
27
+ The package includes the following modules. Each one has different functions that facilitate and automate the data integration in Pandora FMS:
28
+
29
+ **general**
30
+
31
+ Module containing general purpose functions, useful in the creation of plugins for PandoraFMS.
32
+
33
+ **threads**
34
+
35
+ Module containing threading purpose functions, useful to run parallel functions.
36
+
37
+ **agents**
38
+
39
+ Module that contains functions oriented to the creation of Pandora FMS agents
40
+
41
+ **modules**
42
+
43
+ Module that contains functions oriented to the creation of Pandora FMS modules.
44
+
45
+ **transfer**
46
+
47
+ Module containing functions oriented to file transfer and data sending to Pandora FMS server.
48
+
49
+ **discovery**
50
+
51
+ Module containing functions oriented to the creation of Pandora FMS discovery plugins.
52
+
53
+ **output**
54
+
55
+ Module containing functions oriented to output and return data.
56
+
57
+ ## Example
58
+
59
+ ``` python
60
+ import pandoraPluginTools-basic as ppt
61
+
62
+ ## Define agent
63
+ server_name = "WIN-SERV"
64
+
65
+ agent=ppt.init_agent({
66
+ "agent_name" : ppt.generate_md5(server_name),
67
+ "agent_alias" : server_name,
68
+ "description" : "Default Windows server"
69
+ })
70
+
71
+ ## Define modules
72
+ modules=[]
73
+
74
+ data = 10
75
+ modules.append({
76
+ "name" : "CPU usage",
77
+ "type" : "generic_data",
78
+ "value": data,
79
+ "desc" : "Percentage of CPU utilization",
80
+ "unit" : "%"
81
+ })
82
+
83
+ ## Generate and transfer XML
84
+ xml_content = ppt.print_agent(agent, modules)
85
+ xml_file = ppt.write_xml(xml_content, agent["agent_name"])
86
+ ppt.transfer_xml(
87
+ xml_file,
88
+ transfer_mode="tentacle",
89
+ tentacle_ip="192.168.1.20",
90
+ tentacle_port="41121",
91
+ )
92
+ ```
93
+
@@ -0,0 +1,13 @@
1
+ pandoraPlugintools/__init__.py,sha256=lS0tmCLtljIwzK91V0y-z_Yl5VKTakT2oKRX-CuKBiI,161
2
+ pandoraPlugintools/agents.py,sha256=PbBTxdT-6NkNMo1rBwE7w3FQct2WE07r72y_ijxFQWs,10883
3
+ pandoraPlugintools/discovery.py,sha256=NNmpl8qFMf-8M55-EbHPrt7AsgHEsN-2MUqpUYy7aAg,5207
4
+ pandoraPlugintools/general.py,sha256=SvIjHO-RKjYPXujLFQJZxK0e8HLtTWhNZYD4m0-uKkQ,17499
5
+ pandoraPlugintools/modules.py,sha256=RGS6rOBdLlAhn87EjY3DtEuftx4U4UzBAnvhnA10WfM,15862
6
+ pandoraPlugintools/output.py,sha256=4zUm4WNx1zNbOri04SIzTUl51PMek1Hq2l8Hfu4RC-0,3724
7
+ pandoraPlugintools/threads.py,sha256=nvxVymUamVSs3VFVf6_ADkux87TqhLLm_uf_fG94Ksg,7086
8
+ pandoraPlugintools/transfer.py,sha256=qjWD0N6ybNI6a5CwWYm4h0VMobiFbkorRPq6Gvrv2L0,8770
9
+ pandoraplugintools_basic-1.0.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
10
+ pandoraplugintools_basic-1.0.0.dist-info/METADATA,sha256=AYhyLQGb4oCwK8enM72eDV0kb_ctNPRLhoRQqMZBJWQ,2520
11
+ pandoraplugintools_basic-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
12
+ pandoraplugintools_basic-1.0.0.dist-info/top_level.txt,sha256=7O0jTmQWh6ECIecH-PG2Fpf4WIDqVd6UCv7puuRupk0,19
13
+ pandoraplugintools_basic-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+