-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
master.py
1281 lines (1092 loc) · 57.7 KB
/
master.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2015, Wazuh Inc.
# Created by Wazuh, Inc. <info@wazuh.com>.
# This program is free software; you can redistribute it and/or modify it under the terms of GPLv2
import asyncio
import functools
import json
import operator
import os
import shutil
import time
from calendar import timegm
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor
from datetime import datetime
from time import perf_counter
from typing import Tuple, Dict, Callable
from uuid import uuid4
import wazuh.core.cluster.cluster
from wazuh.core import cluster as metadata, common, exception, utils
from wazuh.core.agent import Agent
from wazuh.core.cluster import server, cluster, common as c_common
from wazuh.core.cluster.dapi import dapi
from wazuh.core.cluster.utils import context_tag
from wazuh.core.common import DECIMALS_DATE_FORMAT
from wazuh.core.utils import get_utc_now
from wazuh.core.wdb import WazuhDBConnection
class ReceiveIntegrityTask(c_common.ReceiveFileTask):
"""
Define the process and variables necessary to receive and process integrity information from the master.
This task is created by the master when the worker starts sending its integrity file metadata and it's destroyed
by the master once the necessary files to update have been sent.
"""
def __init__(self, *args, **kwargs):
"""Class constructor.
Parameters
----------
args
Positional arguments for parent constructor class.
kwargs
Keyword arguments for parent constructor class.
"""
super().__init__(*args, **kwargs)
def set_up_coro(self) -> Callable:
"""Set up the function to be called when the worker sends its integrity information."""
return self.wazuh_common.sync_integrity
def done_callback(self, future=None):
"""Check whether the synchronization process was correct and free its lock.
Parameters
----------
future : asyncio.Future object
Synchronization process result.
"""
super().done_callback(future)
# Integrity task is only freed if master is not waiting for Extra valid files.
# if not self.wazuh_common.extra_valid_requested:
# self.wazuh_common.sync_integrity_free[0] = True
self.wazuh_common.sync_integrity_free[0] = True
class ReceiveExtraValidTask(c_common.ReceiveFileTask):
"""
Define the process and variables necessary to receive and process extra valid files from the worker.
This task is created when the worker starts sending extra valid files and its destroyed once the master has updated
all the required information.
"""
def __init__(self, *args, **kwargs):
"""Class constructor.
Parameters
----------
args
Positional arguments for parent constructor class.
kwargs
Keyword arguments for parent constructor class.
"""
super().__init__(*args, **kwargs)
def set_up_coro(self) -> Callable:
"""Set up the function to be called when the worker sends the previously required extra valid files."""
return self.wazuh_common.sync_extra_valid
def done_callback(self, future=None):
"""Check whether the synchronization process was correct and free its lock.
Parameters
----------
future : asyncio.Future object
Synchronization process result.
"""
super().done_callback(future)
self.wazuh_common.extra_valid_requested = False
self.wazuh_common.sync_integrity_free[0] = True
class ReceiveAgentInfoTask(c_common.ReceiveStringTask):
"""
Define the process and variables necessary to receive and process Agent info from the worker.
This task is created when the worker finishes sending Agent info chunks and its destroyed once the master has
updated all the received information.
"""
def __init__(self, *args, **kwargs):
"""Class constructor.
Parameters
----------
args
Positional arguments for parent constructor class.
kwargs
Keyword arguments for parent constructor class.
"""
super().__init__(*args, **kwargs, info_type='agent-info')
def set_up_coro(self) -> Callable:
"""Set up the function to be called when the worker sends its Agent info."""
return self.wazuh_common.setup_sync_wazuh_db_information
def done_callback(self, future=None):
"""Check whether the synchronization process was correct and free its lock.
Parameters
----------
future : asyncio.Future object
Synchronization process result.
"""
super().done_callback(future)
self.wazuh_common.sync_agent_info_free = True
class ReceiveAgentGroupsTask(c_common.ReceiveStringTask):
"""
Define the process and variables necessary to receive and process agent-groups from the worker.
This task is created when the worker finishes sending agent-groups chunks and its destroyed once the master has
updated all the received information.
"""
def __init__(self, *args, **kwargs):
"""Class constructor.
Parameters
----------
args
Positional arguments for parent constructor class.
kwargs
Keyword arguments for parent constructor class.
"""
super().__init__(*args, **kwargs, info_type='agent-groups')
def set_up_coro(self) -> Callable:
"""Set up the function to be called when the worker sends its agent-groups."""
return self.wazuh_common.setup_sync_wazuh_db_information
def done_callback(self, future=None):
"""Check whether the synchronization process was correct and free its lock.
Parameters
----------
future : asyncio.Future object
Synchronization process result.
"""
super().done_callback(future)
self.wazuh_common.sync_agent_groups_free = True
class SendEntireAgentGroupsTask(c_common.SendStringTask):
"""
Define the process and variables necessary to send the entire agent-groups from the master to the worker.
This task is created when the worker needs the entire agent-groups information.
"""
def __init__(self, *args, **kwargs):
"""Class constructor.
Parameters
----------
args
Positional arguments for parent constructor class.
kwargs
Keyword arguments for parent constructor class.
"""
super().__init__(*args, **kwargs)
def set_up_coro(self) -> Callable:
"""Set up the function to be called when the worker needs the entire agent-groups information."""
return self.wazuh_common.send_entire_agent_groups_information
class MasterHandler(server.AbstractServerHandler, c_common.WazuhCommon):
"""
Handle incoming requests and sync processes with a worker.
"""
def __init__(self, **kwargs):
"""Class constructor.
Parameters
----------
kwargs
Arguments for the parent class constructor.
"""
super().__init__(**kwargs, tag="Worker")
# Sync availability variables. Used to prevent sync process from overlapping.
self.sync_agent_info_free = True
self.sync_agent_groups_free = True
self.sync_integrity_free = [True, utils.get_utc_now()]
# Variable used to check whether integrity sync process includes extra_valid files.
self.extra_valid_requested = False
# Sync status variables. Used in cluster_control -i and GET/cluster/healthcheck.
default_date = utils.get_date_from_timestamp(0)
self.integrity_check_status = {'date_start_master': default_date, 'date_end_master': default_date}
self.integrity_sync_status = {'date_start_master': default_date, 'tmp_date_start_master': default_date,
'date_end_master': default_date, 'total_extra_valid': 0,
'total_files': {'missing': 0, 'shared': 0, 'extra': 0, 'extra_valid': 0}}
self.sync_agent_info_status = {'date_start_master': default_date, 'date_end_master': default_date,
'n_synced_chunks': 0}
self.sync_agent_groups_status = {'date_start_master': default_date, 'date_end_master': default_date,
'n_synced_chunks': 0}
self.send_agent_groups_status = {'date_start': 0.0}
# Variables which will be filled when the worker sends the hello request.
self.version = ""
self.cluster_name = ""
self.node_type = ""
self.agent_group_task = None
# Dictionary to save loggers for each sync task.
self.task_loggers = {}
context_tag.set(self.tag)
self.current_zip_limit = self.cluster_items['intervals']['communication']['max_zip_size']
def to_dict(self):
"""Get worker healthcheck information.
Returns
-------
dict
Healthcheck information for each process.
"""
return {'info': {'name': self.name, 'type': self.node_type, 'version': self.version, 'ip': self.ip},
'status': {'sync_integrity_free': self.sync_integrity_free[0],
'last_check_integrity': {key: value for key, value in self.integrity_check_status.items() if
not key.startswith('tmp')},
'last_sync_integrity': {key: value for key, value in self.integrity_sync_status.items() if
not key.startswith('tmp')},
'sync_agent_info_free': self.sync_agent_info_free,
'sync_agent_groups_free': self.sync_agent_groups_free,
'last_sync_agentinfo': self.sync_agent_info_status,
'last_sync_agentgroups': self.sync_agent_groups_status,
'last_keep_alive': self.last_keepalive}
}
def process_request(self, command: bytes, data: bytes) -> Tuple[bytes, bytes]:
"""Define all available commands that can be received from a worker node.
Parameters
----------
command : bytes
Received command.
data : bytes
Received payload.
Returns
-------
bytes
Result.
bytes
Response message.
"""
self.logger.debug(f"Command received: {command}")
if command == b'syn_i_w_m_p' or command == b'syn_a_w_m_p' or command == b'syn_g_w_m_p':
return self.get_permission(command)
elif command == b'syn_i_w_m' or command == b'syn_e_w_m' or command == b'syn_a_w_m' or command == b'syn_g_w_m':
return self.setup_sync_integrity(command, data)
elif command == b'syn_w_g_c':
return self.setup_send_info(command)
elif command == b'syn_i_w_m_e' or command == b'syn_e_w_m_e':
return self.end_receiving_integrity_checksums(data.decode())
elif command == b'syn_i_w_m_r':
return self.process_sync_error_from_worker(data)
elif command == b'syn_w_g_e':
logger = self.task_loggers['Agent-groups send']
start_time = self.send_agent_groups_status['date_start']
return c_common.end_sending_agent_information(logger, start_time, data.decode())
elif command == b'syn_wgc_e':
logger = self.task_loggers['Agent-groups send full']
start_time = self.send_agent_groups_status['date_start']
return c_common.end_sending_agent_information(logger, start_time, data.decode())
elif command == b'syn_w_g_err':
logger = self.task_loggers['Agent-groups send']
return c_common.error_receiving_agent_information(logger, data.decode(), info_type='agent-groups')
elif command == b'syn_wgc_err':
logger = self.task_loggers['Agent-groups send full']
return c_common.error_receiving_agent_information(logger, data.decode(), info_type='agent-groups')
elif command == b'dapi':
self.server.dapi.add_request(self.name.encode() + b'*' + data)
return b'ok', b'Added request to API requests queue'
elif command == b'dapi_res':
return self.process_dapi_res(data)
elif command == b'dapi_err':
dapi_client, error_msg = data.split(b' ', 1)
asyncio.create_task(
self.server.local_server.clients[dapi_client.decode()].send_request(command, error_msg))
return b'ok', b'DAPI error forwarded to worker'
elif command == b'get_nodes':
cmd, res = self.get_nodes(json.loads(data))
return cmd, json.dumps(res).encode()
elif command == b'get_health':
cmd, res = self.get_health(json.loads(data))
return cmd, json.dumps(
res, default=lambda o: "n/a" if isinstance(o, datetime) and o == utils.get_date_from_timestamp(0) else
(o.__str__() if isinstance(o, datetime) else None)).encode()
elif command == b'sendsync':
self.server.sendsync.add_request(self.name.encode() + b'*' + data)
return b'ok', b'Added request to SendSync requests queue'
else:
return super().process_request(command, data)
async def execute(self, command: bytes, data: bytes, wait_for_complete: bool) -> Dict:
"""Send DAPI request and wait for response.
Send a distributed API request and wait for a response in command dapi_res. Methods here are the same
as the ones defined in LocalServerHandlerMaster.
Parameters
----------
command : bytes
Command to execute.
data : bytes
Data to send.
wait_for_complete : bool
Whether to raise a timeout exception or not.
Returns
-------
request_result : dict
API response.
"""
request_id = str(uuid4())
# Create an event to wait for the response.
self.server.pending_api_requests[request_id] = {'Event': asyncio.Event(), 'Response': ''}
# If forward request to other worker, get destination client and request.
if command == b'dapi_fwd':
client, request = data.split(b' ', 1)
client = client.decode()
if client in self.server.clients:
result = (await self.server.clients[client].send_request(b'dapi',
request_id.encode() + b' ' + request)).decode()
else:
raise exception.WazuhClusterError(3022, extra_message=client)
# Add request to local API requests queue.
elif command == b'dapi':
result = (await self.send_request(b'dapi', request_id.encode() + b' ' + data)).decode()
# If not dapi related command, run it now.
else:
result = self.process_request(command=command, data=data)
# If command was dapi or dapi_fwd, wait for response.
if command == b'dapi' or command == b'dapi_fwd':
try:
timeout = None if wait_for_complete \
else self.cluster_items['intervals']['communication']['timeout_dapi_request']
await asyncio.wait_for(self.server.pending_api_requests[request_id]['Event'].wait(), timeout=timeout)
request_result = self.server.pending_api_requests[request_id]['Response']
except asyncio.TimeoutError:
raise exception.WazuhClusterError(3021)
# Otherwise, immediately return the result obtained before.
else:
status, request_result = result
if status != b'ok':
raise exception.WazuhClusterError(3022, extra_message=request_result.decode())
request_result = request_result.decode()
return request_result
def hello(self, data: bytes) -> Tuple[bytes, bytes]:
"""Process 'hello' command from worker.
Process 'hello' command sent by a worker right after it connects to the server. It also initializes
the task loggers.
Parameters
----------
data : bytes
Node name, cluster name, node type and wazuh version all separated by spaces.
Returns
-------
cmd : bytes
Result.
payload : bytes
Response message.
"""
name, cluster_name, node_type, version = data.split(b' ')
# Add client to global clients dictionary.
cmd, payload = super().hello(name)
self.task_loggers = {'Integrity check': self.setup_task_logger('Integrity check'),
'Integrity sync': self.setup_task_logger('Integrity sync'),
'Agent-info sync': self.setup_task_logger('Agent-info sync'),
'Agent-groups sync': self.setup_task_logger('Agent-groups sync'),
'Agent-groups send': self.setup_task_logger('Agent-groups send'),
'Agent-groups send full': self.setup_task_logger('Agent-groups send full')}
# Fill more information and check both name and version are correct.
self.version, self.cluster_name, self.node_type = version.decode(), cluster_name.decode(), node_type.decode()
if self.cluster_name != self.server.configuration['name']:
raise exception.WazuhClusterError(3030)
elif self.version != metadata.__version__:
raise exception.WazuhClusterError(3031)
# Create directory where zips and other files coming from or going to the worker will be managed.
worker_dir = os.path.join(common.WAZUH_PATH, 'queue', 'cluster', self.name)
if cmd == b'ok' and not os.path.exists(worker_dir):
utils.mkdir_with_mode(worker_dir)
# Initialize agent-groups sending task
self.agent_group_task = asyncio.ensure_future(self.send_agent_groups_information())
return cmd, payload
def get_manager(self) -> server.AbstractServer:
"""Get the Master object that created this MasterHandler. Used in the class WazuhCommon.
Returns
-------
AbstractServer
Master object.
"""
return self.server
def process_dapi_res(self, data: bytes) -> Tuple[bytes, bytes]:
"""Process a DAPI response coming from a worker node.
This function is called when the master received a "dapi_res" command. The response
has been previously sent using a send_string so this method only receives the string ID.
If the request ID is within the pending api requests, the response is assigned to the request ID and
the server is notified. Else, if the request ID is within the local_server clients, it is forwarded.
Parameters
----------
data : bytes
Request ID and response ID separated by a space (' ').
Returns
-------
bytes
Result.
bytes
Response message.
"""
req_id, string_id = data.split(b' ', 1)
req_id = req_id.decode()
if req_id in self.server.pending_api_requests:
self.server.pending_api_requests[req_id]['Response'] = self.in_str[string_id].payload.decode()
self.server.pending_api_requests[req_id]['Event'].set()
# Remove the string after using it
self.in_str.pop(string_id, None)
return b'ok', b'Forwarded response'
elif req_id in self.server.local_server.clients:
asyncio.create_task(self.forward_dapi_response(data))
return b'ok', b'Response forwarded to worker'
else:
raise exception.WazuhClusterError(3032, extra_message=req_id)
def get_nodes(self, arguments: Dict) -> Tuple[bytes, Dict]:
"""Process 'get_nodes' request.
Parameters
----------
arguments : dict
Arguments to use in get_connected_nodes function (filter, sort, etc).
Returns
-------
bytes
Result.
dict
Dict object containing nodes information.
"""
return b'ok', self.server.get_connected_nodes(**arguments)
def get_health(self, filter_nodes: Dict) -> Tuple[bytes, Dict]:
"""Process 'get_health' request.
Parameters
----------
filter_nodes : dict
Whether to filter by a node or return all health information.
Returns
-------
bytes
Result.
dict
Dict object containing nodes information.
"""
return b'ok', self.server.get_health(filter_nodes)
def get_permission(self, sync_type: bytes) -> Tuple[bytes, bytes]:
"""Get whether a sync process is in progress or not.
Parameters
----------
sync_type : bytes
Sync process to check.
Returns
-------
bytes
Result.
bytes
Response message.
"""
# Check if an integrity_check has already been performed
# for the worker in the current iteration of local_integrity
if sync_type == b'syn_i_w_m_p' and self.name not in self.server.integrity_already_executed:
# Add the variable self.name to keep track of the number of integrity_checks per cycle
self.server.integrity_already_executed.append(self.name)
# Reset integrity permissions if False for more than "max_locked_integrity_time" seconds
if not self.sync_integrity_free[0] and (utils.get_utc_now() - self.sync_integrity_free[1]).total_seconds() > \
self.cluster_items['intervals']['master']['max_locked_integrity_time']:
self.logger.warning(f'Automatically releasing Integrity check permissions flag ({sync_type}) after '
f'being locked out for more than '
f'{self.cluster_items["intervals"]["master"]["max_locked_integrity_time"]}s.')
self.sync_integrity_free[0] = True
permission = self.sync_integrity_free[0]
elif sync_type == b'syn_a_w_m_p':
permission = self.sync_agent_info_free
elif sync_type == b'syn_g_w_m_p':
permission = self.sync_agent_groups_free
else:
permission = False
return b'ok', str(permission).encode()
def setup_sync_integrity(self, sync_type: bytes, data: bytes = None) -> Tuple[bytes, bytes]:
"""Start synchronization process.
Parameters
----------
sync_type : bytes
Sync process to start.
data : bytes
Data to be sent.
Returns
-------
bytes
Result.
bytes
Response message.
"""
if sync_type == b'syn_i_w_m':
self.sync_integrity_free, sync_function = [False, utils.get_utc_now()], ReceiveIntegrityTask
elif sync_type == b'syn_e_w_m':
sync_function = ReceiveExtraValidTask
elif sync_type == b'syn_a_w_m':
self.sync_agent_info_free, sync_function = False, ReceiveAgentInfoTask
elif sync_type == b'syn_g_w_m':
self.sync_agent_groups_free, sync_function = False, ReceiveAgentGroupsTask
else:
sync_function = None
return super().setup_receive_file(sync_function, data)
def setup_send_info(self, sync_type: bytes) -> Tuple[bytes, bytes]:
"""Start synchronization process.
Parameters
----------
sync_type : bytes
Sync process to start.
Returns
-------
bytes
Result.
bytes
Response message.
"""
if sync_type == b'syn_w_g_c':
sync_function = SendEntireAgentGroupsTask
else:
sync_function = None
return super().setup_send_info(sync_function)
def process_sync_error_from_worker(self, error_msg: bytes) -> Tuple[bytes, bytes]:
"""Manage error during synchronization process reported by a worker.
Mark the process as free so a new one can start.
Parameters
----------
error_msg : bytes
Error information.
Returns
-------
bytes
Result.
bytes
Response message.
"""
self.sync_integrity_free[0] = True
return super().error_receiving_file(error_msg.decode())
def end_receiving_integrity_checksums(self, task_and_file_names: str) -> Tuple[bytes, bytes]:
"""Finish receiving a file and start the function to process it.
Parameters
----------
task_and_file_names : str
Task ID awaiting the file and the filename separated by a space (' ').
Returns
-------
bytes
Result.
bytes
Response message.
"""
return super().end_receiving_file(task_and_file_names)
async def setup_sync_wazuh_db_information(self, task_id: bytes, info_type: str):
"""Create a process to send to the local wazuh-db the chunks of data received from a worker.
Parameters
----------
task_id : bytes
ID of the string where the JSON chunks are stored.
info_type : str
Information type handled.
Returns
-------
result : bytes
Worker's response after finishing the synchronization.
"""
logger = ''
command = ''
error_command = ''
timeout = 0
sync_dict = {}
if info_type == 'agent-info':
logger = self.task_loggers['Agent-info sync']
command = b'syn_m_a_e'
error_command = b'syn_m_a_err'
sync_dict = self.sync_agent_info_status
timeout = self.cluster_items['intervals']['master']['timeout_agent_info']
elif info_type == 'agent-groups':
logger = self.task_loggers['Agent-groups sync']
command = b'syn_m_g_e'
error_command = b'syn_m_g_err'
sync_dict = self.sync_agent_groups_status
timeout = self.cluster_items['intervals']['master']['timeout_agent_groups']
return await super().sync_wazuh_db_information(
task_id=task_id, info_type=info_type, error_command=error_command,
logger=logger, command=command, sync_dict=sync_dict, timeout=timeout)
async def send_entire_agent_groups_information(self):
"""Method in charge of sending all the information related to
agent-groups from the master node database to the worker node database.
This method is activated when the worker node requests this information to the master node.
"""
logger = self.task_loggers['Agent-groups send full']
sync_object = c_common.SyncWazuhdb(manager=self, logger=logger,
data_retriever=WazuhDBConnection().run_wdb_command,
get_data_command='global sync-agent-groups-get ',
get_payload={"condition": "all", "set_synced": False,
"get_global_hash": False, "last_id": 0}, pivot_key='last_id')
local_agent_groups_information = await sync_object.retrieve_information()
sync_object = c_common.SyncWazuhdb(manager=self, logger=logger, cmd=b'syn_g_m_w_c',
data_retriever=WazuhDBConnection().run_wdb_command,
set_data_command='global set-agent-groups',
set_payload={'mode': 'override', 'sync_status': 'synced'})
logger.info("Requested entire agent-groups information by the worker node. Starting.")
start_time = get_utc_now().timestamp()
logger.info("Sending all agent-groups information from the master node database.")
await sync_object.sync(start_time=start_time, chunks=local_agent_groups_information)
return b'ok', b'Sent'
async def send_agent_groups_information(self):
"""Function in charge of sending the group information to the worker node.
Each time we get data it will be sent.
A worker node cannot send two consecutive times the same group information.
"""
logger = self.task_loggers['Agent-groups send']
wdb_conn = WazuhDBConnection()
sync_object = c_common.SyncWazuhdb(manager=self, logger=logger, cmd=b'syn_g_m_w',
data_retriever=wdb_conn.run_wdb_command,
set_data_command='global set-agent-groups',
set_payload={'mode': 'override', 'sync_status': 'synced'})
while True:
info = self.server.get_agent_groups_info(self.name)
if info != {}:
try:
logger.info("Starting.")
self.send_agent_groups_status['date_start'] = get_utc_now().timestamp()
await sync_object.sync(start_time=self.send_agent_groups_status['date_start'], chunks=info)
except Exception as e:
logger.error(f'Error sending agent-groups information to {self.name}: {e}')
await asyncio.sleep(1)
async def sync_integrity(self, task_id: str, received_file: asyncio.Event):
"""Perform the integrity synchronization process by comparing local and received files.
It waits until the worker sends its integrity metadata. Once received, they are unzipped.
The information inside the unzipped files_metadata.json file (integrity metadata) is compared with the
local one (updated every self.cluster_items['intervals']['master']['recalculate_integrity'] seconds).
All files that are different (new, deleted, with a different MD5, etc) are classified into four groups:
shared, missing, and extra.
Finally, a zip containing this classification (files_metadata.json) and the files that are missing
or that must be updated are sent to the worker.
Parameters
----------
task_id : str
ID of the asyncio task in charge of doing the sync process.
received_file : asyncio.Event
Asyncio event that is holding a lock while the files are not received.
"""
logger = self.task_loggers['Integrity check']
date_start_master = utils.get_utc_now()
logger.info(f"Starting.")
logger.debug("Waiting to receive zip file from worker.")
try:
await asyncio.wait_for(received_file.wait(),
timeout=self.cluster_items['intervals']['communication']['timeout_receiving_file'])
except Exception:
# Notify the sending node to stop its task.
await self.send_request(
command=b'cancel_task',
data=task_id.encode() + b' ' + json.dumps(timeout_exc := exception.WazuhClusterError(3039),
cls=c_common.WazuhJSONEncoder).encode())
raise timeout_exc
# Full path where the zip sent by the worker is located.
received_filename = self.sync_tasks[task_id].filename
if isinstance(received_filename, Exception):
raise received_filename
logger.debug(f"Received file from worker: '{received_filename}'")
# Path to metadata file (files_metadata.json) and to zipdir (directory with decompressed files).
files_metadata, decompressed_files_path = await wazuh.core.cluster.cluster.async_decompress_files(
received_filename)
# There are no files inside decompressed_files_path, only files_metadata.json which has already been loaded.
shutil.rmtree(decompressed_files_path)
# Classify files in shared, missing, extra and extra valid.
worker_files_ko, counts = wazuh.core.cluster.cluster.compare_files(self.server.integrity_control,
files_metadata, self.name)
total_time = (utils.get_utc_now() - date_start_master).total_seconds()
# The 'TYPE' placeholder is replacing the type of files that we could need the worker to forwards to the master.
# This file used to the 'extra-valid', which is currently deprecated.
# self.extra_valid_requested = bool(worker_files_ko['TYPE'])
self.extra_valid_requested = False
self.integrity_check_status.update({'date_start_master': date_start_master.strftime(DECIMALS_DATE_FORMAT),
'date_end_master': utils.get_utc_now().strftime(DECIMALS_DATE_FORMAT)})
# Get the total number of files that require some change.
if not functools.reduce(operator.add, map(len, worker_files_ko.values())):
logger.info(f"Finished in {total_time:.3f}s. Received metadata of {len(files_metadata)} files. "
f"Sync not required.")
await self.send_request(command=b'syn_m_c_ok', data=b'')
else:
logger.info(f"Finished in {total_time:.3f}s. Received metadata of {len(files_metadata)} files. "
f"Sync required.")
logger = self.task_loggers['Integrity sync']
logger.info("Starting.")
self.integrity_sync_status.update({'tmp_date_start_master': utils.get_utc_now(), 'total_files': counts,
'total_extra_valid': 0})
logger.info(f"Files to create in worker: {len(worker_files_ko['missing'])} | Files to update in worker: "
f"{len(worker_files_ko['shared'])} | Files to delete in worker: "
f"{len(worker_files_ko['extra'])}")
# Compress data: master files (only KO shared and missing).
logger.debug("Compressing files to be synced in worker.")
master_files_paths = worker_files_ko['shared'].keys() | worker_files_ko['missing'].keys()
compressed_data = await cluster.run_in_pool(self.loop, self.server.task_pool,
wazuh.core.cluster.cluster.compress_files, self.name,
master_files_paths, worker_files_ko, self.current_zip_limit)
time_to_send = 0
sent_size = 0
try:
# Start the synchronization process with the worker and get a taskID.
task_id = await self.send_request(command=b'syn_m_c', data=b'')
if isinstance(task_id, Exception) or task_id.startswith(b'Error'):
exc_info = task_id if isinstance(task_id, Exception) else \
exception.WazuhClusterError(3016, extra_message=str(task_id))
task_id = b'None'
raise exc_info
# Send zip file to the worker into chunks.
time_to_send = time.perf_counter()
sent_size = await self.send_file(compressed_data, task_id)
time_to_send = time.perf_counter() - time_to_send
logger.debug("Zip with files to be synced sent to worker.")
# Notify what is the zip path for the current taskID.
result = await self.send_request(command=b'syn_m_c_e', data=task_id + b' ' + os.path.relpath(
compressed_data, common.WAZUH_PATH).encode())
if isinstance(result, Exception):
raise result
elif result.startswith(b'Error'):
raise exception.WazuhClusterError(3016, extra_message=result.decode())
except exception.WazuhException as e:
# Notify error to worker and delete its received file.
self.logger.error(f"Error sending files information: {e}")
await self.send_request(
command=b'syn_m_c_r', data=task_id + b' ' + json.dumps(e, cls=c_common.WazuhJSONEncoder).encode())
except Exception as e:
# Notify error to worker and delete its received file.
self.logger.error(f"Error sending files information: {e}")
exc_info = json.dumps(exception.WazuhClusterError(1000, extra_message=str(e)),
cls=c_common.WazuhJSONEncoder).encode()
await self.send_request(command=b'syn_m_c_r', data=task_id + b' ' + exc_info)
finally:
try:
# Decrease max zip size if task was interrupted (otherwise, KeyError exception raised).
self.interrupted_tasks.remove(task_id)
self.current_zip_limit = max(
self.cluster_items['intervals']['communication']['min_zip_size'],
sent_size * (1 - self.cluster_items['intervals']['communication']['zip_limit_tolerance'])
)
self.logger.debug(f"Decreasing sync size limit to {self.current_zip_limit / (1024 ** 2):.2f} MB.")
except KeyError:
# Increase max zip size if two conditions are met:
# 1. Current zip limit is lower than default.
# 2. Time to send zip was far under timeout_receiving_file.
if (self.current_zip_limit < self.cluster_items['intervals']['communication']['max_zip_size'] and
time_to_send < self.cluster_items['intervals']['communication']['timeout_receiving_file'] *
(1 - self.cluster_items['intervals']['communication']['zip_limit_tolerance'])):
self.current_zip_limit = min(
self.cluster_items['intervals']['communication']['max_zip_size'],
self.current_zip_limit * (
1 / (1 - self.cluster_items['intervals']['communication']['zip_limit_tolerance'])
))
self.logger.debug(
f"Increasing sync size limit to {self.current_zip_limit / (1024 ** 2):.2f} MB.")
# Remove local file.
os.unlink(compressed_data)
logger.debug("Finished sending files to worker.")
# Log 'Finished in' message only if there are no extra_valid files to sync.
if not self.extra_valid_requested:
self.integrity_sync_status['date_end_master'] = utils.get_utc_now()
logger.info("Finished in {:.3f}s.".format((self.integrity_sync_status['date_end_master'] -
self.integrity_sync_status['tmp_date_start_master'])
.total_seconds()))
self.integrity_sync_status['date_start_master'] = self.integrity_sync_status[
'tmp_date_start_master'].strftime(DECIMALS_DATE_FORMAT)
self.integrity_sync_status['date_end_master'] = \
self.integrity_sync_status['date_end_master'].strftime(DECIMALS_DATE_FORMAT)
async def sync_extra_valid(self, task_id: str, received_file: asyncio.Event):
"""Run extra valid sync process and set up necessary parameters.
Parameters
----------
task_id : str
ID of the asyncio task in charge of doing the sync process.
received_file : asyncio.Event
Asyncio event that is holding a lock while the files are not received.
"""
logger = self.task_loggers['Integrity sync']
await self.sync_worker_files(task_id, received_file, logger)
self.integrity_sync_status['date_end_master'] = utils.get_utc_now()
logger.info("Finished in {:.3f}s.".format(
(self.integrity_sync_status['date_end_master'] -
self.integrity_sync_status['tmp_date_start_master']).total_seconds()))
self.integrity_sync_status['date_start_master'] = \
self.integrity_sync_status['tmp_date_start_master'].strftime(DECIMALS_DATE_FORMAT)
self.integrity_sync_status['date_end_master'] = \
self.integrity_sync_status['date_end_master'].strftime(DECIMALS_DATE_FORMAT)
self.extra_valid_requested = False
self.sync_integrity_free[0] = True
async def sync_worker_files(self, task_id: str, received_file: asyncio.Event, logger):
"""Wait until extra valid files are received from the worker and create a child process for them.
Parameters
----------
task_id : str
Task ID to which the file was sent.
received_file : asyncio.Event
Asyncio event that is holding a lock while the files are not received.
logger : Logger object
Logger to use (can't use self since one of the task loggers will be used).
"""
logger.debug("Waiting to receive zip file from worker.")
try:
await asyncio.wait_for(received_file.wait(),
timeout=self.cluster_items['intervals']['communication']['timeout_receiving_file'])
except Exception:
# Notify the sending node to stop its task.
await self.send_request(
command=b'cancel_task',
data=task_id.encode() + b' ' + json.dumps(timeout_exc := exception.WazuhClusterError(3039),
cls=c_common.WazuhJSONEncoder).encode())
raise timeout_exc
# Full path where the zip sent by the worker is located.
received_filename = self.sync_tasks[task_id].filename
if isinstance(received_filename, Exception):
raise received_filename
logger.debug(f"Received extra-valid file from worker: '{received_filename}'")
# Path to metadata file (files_metadata.json) and to zipdir (directory with decompressed files).
files_metadata, decompressed_files_path = await wazuh.core.cluster.cluster.async_decompress_files(
received_filename)
# Create a child process to run the task.
try:
result = await cluster.run_in_pool(self.loop, self.server.task_pool, self.process_files_from_worker,
files_metadata, decompressed_files_path, self.cluster_items, self.name,
self.cluster_items['intervals']['master']['timeout_extra_valid'])
except Exception as e:
raise exception.WazuhClusterError(3038, extra_message=str(e))
finally:
shutil.rmtree(decompressed_files_path)
# Log any possible error found in the process.
self.integrity_sync_status['total_extra_valid'] = result['total_updated']
if result['errors_per_folder']:
logger.error(f"Errors updating worker files: {dict(result['errors_per_folder'])}", exc_info=False)
for error in result['generic_errors']:
logger.error(error, exc_info=False)
@staticmethod
def process_files_from_worker(files_metadata: Dict, decompressed_files_path: str, cluster_items: dict,
worker_name: str, timeout: int):
"""Iterate over received files from worker and updates the local ones.
Parameters
----------
files_metadata : dict
Dictionary containing file metadata (each key is a filepath and each value its metadata).
decompressed_files_path : str
Filepath of the decompressed received zipfile.
cluster_items : dict
Object containing cluster internal variables from the cluster.json file.
worker_name : str
Name of the worker instance. Used to access the correct worker folder.
timeout : int
Seconds to wait before stopping the task.
Returns
-------
result : dict
Dict containing number of updated chunks and any error found in the process.
"""
result = {'total_updated': 0, 'errors_per_folder': defaultdict(list), 'generic_errors': []}
try:
with utils.Timeout(timeout):
for file_path, data in files_metadata.items():
full_path = os.path.join(common.WAZUH_PATH, file_path)
item_key = data['cluster_item_key']
# Only valid client.keys is the local one (master).
if os.path.basename(file_path) == 'client.keys':