opensearch-api 0.1.0

High-performance REST API gateway for OpenSearch with security, observability and multi-tenant support
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
#!/usr/bin/env python3

import os
import sys
import json
import subprocess
import shutil
import requests
import tarfile
import tempfile
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Tuple, Optional
import argparse
import time

class OpenSearchManager:
    def __init__(self):
        self.installations = []
        self.es_installations = []
        self.os_installations = []
        self.default_target = "/opt/prod/opensearch"
        
    def run_command(self, cmd: List[str], capture_output: bool = True) -> Tuple[int, str, str]:
        """Executa comando e retorna código, stdout, stderr"""
        try:
            result = subprocess.run(cmd, capture_output=capture_output, text=True)
            return result.returncode, result.stdout, result.stderr
        except Exception as e:
            return 1, "", str(e)
    
    def check_root(self):
        """Verifica se está rodando como root"""
        if os.geteuid() != 0:
            print("Este script precisa ser executado como root")
            print("Use: sudo python3 opensearch-manager.py")
            sys.exit(1)
    
    def format_size(self, size_bytes: int) -> str:
        """Formata tamanho em bytes para formato legível"""
        for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
            if size_bytes < 1024.0:
                return f"{size_bytes:.2f}{unit}"
            size_bytes /= 1024.0
        return f"{size_bytes:.2f}TB"
    
    def get_service_info(self, port: int = 9200) -> Dict:
        """Obtém informações do serviço via API"""
        try:
            response = requests.get(f"http://localhost:{port}/", timeout=5)
            return response.json()
        except:
            return {}
    
    def get_cluster_health(self, port: int = 9200) -> Dict:
        """Obtém saúde do cluster"""
        try:
            response = requests.get(f"http://localhost:{port}/_cluster/health", timeout=5)
            return response.json()
        except:
            return {}
    
    def get_indices_info(self, port: int = 9200) -> List[Dict]:
        """Obtém informações dos índices"""
        try:
            response = requests.get(f"http://localhost:{port}/_cat/indices?format=json", timeout=5)
            return response.json()
        except:
            return []
    
    def find_installations(self):
        """Encontra todas as instalações de ES/OS no sistema"""
        print("\n=== Procurando instalações ===")
        
        # Locais comuns para procurar
        search_paths = [
            "/opt/opensearch",
            "/opt/elasticsearch", 
            "/usr/share/opensearch",
            "/usr/share/elasticsearch",
            "/var/lib/opensearch",
            "/var/lib/elasticsearch",
        ]
        
        # Adiciona diretórios em /opt
        for item in Path("/opt").iterdir():
            if item.is_dir():
                if "opensearch" in item.name.lower():
                    search_paths.append(str(item))
                elif "elasticsearch" in item.name.lower():
                    search_paths.append(str(item))
        
        for path in search_paths:
            if os.path.exists(path):
                info = self.analyze_installation(path)
                if info:
                    self.installations.append(info)
                    if info['type'] == 'elasticsearch':
                        self.es_installations.append(info)
                    else:
                        self.os_installations.append(info)
        
        # Verifica serviços ativos
        self.check_running_services()
        
        # Mostra resumo
        self.print_installations_summary()
    
    def analyze_installation(self, path: str) -> Dict:
        """Analisa uma instalação específica"""
        info = {
            'path': path,
            'type': 'opensearch' if 'opensearch' in path.lower() else 'elasticsearch',
            'version': 'unknown',
            'data_size': 0,
            'config_path': None,
            'data_path': None,
            'logs_path': None,
            'running': False,
            'port': 9200
        }
        
        # Procura por arquivos de configuração
        config_paths = [
            os.path.join(path, 'config'),
            '/etc/opensearch',
            '/etc/elasticsearch'
        ]
        
        for config_path in config_paths:
            yml_file = os.path.join(config_path, f"{info['type']}.yml")
            if os.path.exists(yml_file):
                info['config_path'] = yml_file
                # Tenta extrair porta da configuração
                try:
                    with open(yml_file, 'r') as f:
                        for line in f:
                            if 'http.port:' in line and not line.strip().startswith('#'):
                                port = line.split(':')[1].strip()
                                info['port'] = int(port)
                except:
                    pass
                break
        
        # Procura diretórios de dados
        data_paths = [
            os.path.join(path, 'data'),
            f"/var/lib/{info['type']}/data"
        ]
        
        for data_path in data_paths:
            if os.path.exists(data_path):
                info['data_path'] = data_path
                # Calcula tamanho dos dados
                try:
                    total_size = 0
                    for dirpath, dirnames, filenames in os.walk(data_path):
                        for filename in filenames:
                            filepath = os.path.join(dirpath, filename)
                            total_size += os.path.getsize(filepath)
                    info['data_size'] = total_size
                except:
                    pass
                break
        
        # Procura diretório de logs
        logs_paths = [
            os.path.join(path, 'logs'),
            f"/var/log/{info['type']}"
        ]
        
        for logs_path in logs_paths:
            if os.path.exists(logs_path):
                info['logs_path'] = logs_path
                break
        
        # Tenta obter versão de arquivos
        version_files = [
            os.path.join(path, 'VERSION'),
            os.path.join(path, 'version.txt'),
            os.path.join(path, 'lib', f'{info["type"]}-*.jar')
        ]
        
        for version_file in version_files:
            if '*' in version_file:
                import glob
                files = glob.glob(version_file)
                if files:
                    # Extrai versão do nome do arquivo
                    filename = os.path.basename(files[0])
                    parts = filename.split('-')
                    if len(parts) > 1:
                        info['version'] = parts[1].replace('.jar', '')
                        break
            elif os.path.exists(version_file):
                try:
                    with open(version_file, 'r') as f:
                        info['version'] = f.read().strip()
                        break
                except:
                    pass
        
        return info
    
    def check_running_services(self):
        """Verifica quais serviços estão rodando"""
        # Verifica via systemctl
        services = ['opensearch', 'elasticsearch']
        for service in services:
            code, stdout, _ = self.run_command(['systemctl', 'is-active', f'{service}.service'])
            if code == 0 and 'active' in stdout:
                # Encontra qual instalação corresponde a este serviço
                for inst in self.installations:
                    if inst['type'] == service:
                        inst['running'] = True
                        # Tenta obter versão via API
                        api_info = self.get_service_info(inst['port'])
                        if api_info and 'version' in api_info:
                            inst['version'] = api_info['version']['number']
                            inst['api_info'] = api_info
        
        # Verifica portas em uso
        ports_to_check = [9200, 9201, 9300, 9301]
        for port in ports_to_check:
            api_info = self.get_service_info(port)
            if api_info:
                # Encontra instalação correspondente ou cria nova entrada
                found = False
                for inst in self.installations:
                    if inst['port'] == port or (inst['running'] and 'version' in api_info and api_info['version']['number'] == inst['version']):
                        inst['running'] = True
                        inst['port'] = port
                        inst['api_info'] = api_info
                        if 'version' in api_info:
                            inst['version'] = api_info['version']['number']
                        found = True
                        break
                
                if not found:
                    # Serviço rodando mas instalação não encontrada (talvez em container)
                    new_inst = {
                        'path': 'unknown',
                        'type': 'opensearch' if 'opensearch' in api_info.get('name', '').lower() else 'elasticsearch',
                        'version': api_info['version']['number'] if 'version' in api_info else 'unknown',
                        'data_size': 0,
                        'config_path': None,
                        'data_path': None,
                        'logs_path': None,
                        'running': True,
                        'port': port,
                        'api_info': api_info
                    }
                    self.installations.append(new_inst)
    
    def print_installations_summary(self):
        """Mostra resumo das instalações encontradas"""
        if not self.installations:
            print("\nNenhuma instalação encontrada.")
            return
        
        print(f"\nEncontradas {len(self.installations)} instalação(ões):\n")
        
        for i, inst in enumerate(self.installations, 1):
            print(f"{i}. {inst['type'].upper()} v{inst['version']}")
            print(f"   Path: {inst['path']}")
            print(f"   Status: {'RODANDO' if inst['running'] else 'PARADO'}")
            if inst['running']:
                print(f"   Porta: {inst['port']}")
            if inst['data_size'] > 0:
                print(f"   Dados: {self.format_size(inst['data_size'])}")
            
            # Mostra saúde do cluster se estiver rodando
            if inst['running']:
                health = self.get_cluster_health(inst['port'])
                if health:
                    print(f"   Cluster: {health.get('cluster_name', 'unknown')} - Status: {health.get('status', 'unknown')}")
                    print(f"   Nodes: {health.get('number_of_nodes', 0)} - Índices: {health.get('active_primary_shards', 0)}")
            print()
    
    def show_menu(self):
        """Mostra menu de opções baseado no que foi encontrado"""
        print("\n=== MENU DE OPÇÕES ===\n")
        
        options = []
        
        # Opções baseadas no que foi encontrado
        if not self.installations:
            options.append(("1", "Instalar OpenSearch novo", self.install_new))
        else:
            option_num = 1
            
            # Opções para Elasticsearch
            for inst in self.es_installations:
                version = inst['version']
                if version != 'unknown':
                    try:
                        major_version = int(version.split('.')[0])
                        if major_version <= 7:
                            options.append((str(option_num), f"Migrar Elasticsearch {version} para OpenSearch", lambda i=inst: self.migrate_es_to_os(i)))
                            option_num += 1
                    except:
                        pass
            
            # Opções para OpenSearch
            for inst in self.os_installations:
                options.append((str(option_num), f"Mover OpenSearch de {inst['path']} para {self.default_target}", lambda i=inst: self.move_installation(i)))
                option_num += 1
                
                options.append((str(option_num), f"Atualizar OpenSearch {inst['version']} para versão mais recente", lambda i=inst: self.upgrade_opensearch(i)))
                option_num += 1
            
            # Opções gerais
            options.append((str(option_num), "Fazer backup de uma instalação", self.backup_installation))
            option_num += 1
            
            options.append((str(option_num), "Desinstalar uma instalação", self.uninstall))
            option_num += 1
            
            options.append((str(option_num), "Instalar OpenSearch novo", self.install_new))
            option_num += 1
        
        options.append(("0", "Sair", None))
        
        # Mostra opções
        for opt_num, desc, _ in options:
            print(f"{opt_num}. {desc}")
        
        # Obtém escolha do usuário
        while True:
            choice = input("\nEscolha uma opção: ").strip()
            for opt_num, desc, func in options:
                if choice == opt_num:
                    if func:
                        print(f"\n=== {desc} ===")
                        func()
                    return choice == "0"
            print("Opção inválida. Tente novamente.")
    
    def migrate_es_to_os(self, es_inst: Dict):
        """Migra Elasticsearch para OpenSearch"""
        print(f"\nMigrando Elasticsearch {es_inst['version']} para OpenSearch...")
        
        # 1. Instala OpenSearch em porta temporária (9201)
        print("\n1. Instalando OpenSearch em porta temporária (9201)...")
        temp_port = 9201
        os_path = self.default_target
        
        if not self.download_and_install_opensearch(os_path, temp_port):
            print("Erro na instalação do OpenSearch")
            return
        
        # 2. Inicia OpenSearch
        print("\n2. Iniciando OpenSearch...")
        self.start_opensearch(os_path, temp_port)
        time.sleep(10)  # Aguarda inicialização
        
        # 3. Verifica se ambos estão rodando
        es_health = self.get_cluster_health(es_inst['port'])
        os_health = self.get_cluster_health(temp_port)
        
        if not es_health or not os_health:
            print("Erro: Um dos serviços não está respondendo")
            return
        
        print(f"\nElasticsearch: {es_health['cluster_name']} - {es_health['status']}")
        print(f"OpenSearch: {os_health['cluster_name']} - {os_health['status']}")
        
        # 4. Migra dados
        print("\n3. Migrando dados...")
        migration_method = input("\nEscolha método de migração:\n1. Reindex (recomendado para dados pequenos)\n2. Snapshot/Restore (recomendado para dados grandes)\nEscolha (1/2): ")
        
        if migration_method == "1":
            self.migrate_via_reindex(es_inst['port'], temp_port)
        else:
            self.migrate_via_snapshot(es_inst, os_path, temp_port)
        
        # 5. Valida migração
        print("\n4. Validando migração...")
        es_indices = self.get_indices_info(es_inst['port'])
        os_indices = self.get_indices_info(temp_port)
        
        print(f"Índices no Elasticsearch: {len(es_indices)}")
        print(f"Índices no OpenSearch: {len(os_indices)}")
        
        if len(os_indices) < len(es_indices):
            print("\nAVISO: Nem todos os índices foram migrados!")
            if input("Continuar mesmo assim? (s/N): ").lower() != 's':
                return
        
        # 6. Para Elasticsearch
        print("\n5. Parando Elasticsearch...")
        self.stop_service('elasticsearch')
        
        # 7. Reconfigura OpenSearch para porta 9200
        print("\n6. Reconfigurando OpenSearch para porta padrão...")
        self.reconfigure_port(os_path, temp_port, 9200)
        
        print("\nMigração concluída!")
        print(f"OpenSearch instalado em: {os_path}")
        print("Elasticsearch foi parado mas não removido (use a opção de desinstalar se desejar)")
    
    def migrate_via_reindex(self, source_port: int, target_port: int):
        """Migra dados usando reindex API"""
        # Obtém lista de índices
        indices = self.get_indices_info(source_port)
        
        print(f"\nMigrando {len(indices)} índices...")
        
        for idx in indices:
            if idx['index'].startswith('.'):  # Pula índices de sistema
                continue
                
            print(f"Migrando índice: {idx['index']}...", end='', flush=True)
            
            # Configura reindex remoto
            reindex_body = {
                "source": {
                    "remote": {
                        "host": f"http://localhost:{source_port}"
                    },
                    "index": idx['index']
                },
                "dest": {
                    "index": idx['index']
                }
            }
            
            try:
                response = requests.post(
                    f"http://localhost:{target_port}/_reindex",
                    json=reindex_body,
                    timeout=300
                )
                if response.status_code == 200:
                    print(" OK")
                else:
                    print(f" ERRO: {response.text}")
            except Exception as e:
                print(f" ERRO: {e}")
    
    def migrate_via_snapshot(self, source_inst: Dict, target_path: str, target_port: int):
        """Migra dados usando snapshot/restore"""
        snapshot_path = "/tmp/migration-snapshot"
        repo_name = "migration-repo"
        snapshot_name = f"migration-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
        
        # Cria diretório para snapshot
        os.makedirs(snapshot_path, exist_ok=True)
        os.chmod(snapshot_path, 0o777)
        
        print(f"\nCriando snapshot repository...")
        
        # Configura repository no source
        repo_body = {
            "type": "fs",
            "settings": {
                "location": snapshot_path
            }
        }
        
        # Cria repository no Elasticsearch
        response = requests.put(
            f"http://localhost:{source_inst['port']}/_snapshot/{repo_name}",
            json=repo_body
        )
        
        if response.status_code != 200:
            print(f"Erro ao criar repository: {response.text}")
            return
        
        # Cria snapshot
        print(f"Criando snapshot...")
        response = requests.put(
            f"http://localhost:{source_inst['port']}/_snapshot/{repo_name}/{snapshot_name}?wait_for_completion=true"
        )
        
        if response.status_code != 200:
            print(f"Erro ao criar snapshot: {response.text}")
            return
        
        print("Snapshot criado com sucesso!")
        
        # Configura repository no target
        print("\nConfigurando repository no OpenSearch...")
        response = requests.put(
            f"http://localhost:{target_port}/_snapshot/{repo_name}",
            json=repo_body
        )
        
        # Restaura snapshot
        print("Restaurando snapshot...")
        response = requests.post(
            f"http://localhost:{target_port}/_snapshot/{repo_name}/{snapshot_name}/_restore"
        )
        
        if response.status_code == 200:
            print("Restore iniciado com sucesso!")
        else:
            print(f"Erro no restore: {response.text}")
    
    def move_installation(self, inst: Dict):
        """Move instalação para novo diretório"""
        print(f"\nMovendo {inst['type']} de {inst['path']} para {self.default_target}")
        
        if os.path.exists(self.default_target):
            print(f"ERRO: Destino {self.default_target} já existe!")
            return
        
        # Para o serviço se estiver rodando
        if inst['running']:
            print("Parando serviço...")
            self.stop_service(inst['type'])
        
        # Cria diretório pai se não existir
        os.makedirs(os.path.dirname(self.default_target), exist_ok=True)
        
        # Move instalação
        print(f"Movendo arquivos...")
        shutil.move(inst['path'], self.default_target)
        
        # Atualiza configurações
        self.update_paths_after_move(inst['type'], inst['path'], self.default_target)
        
        # Reinicia serviço
        print("Reiniciando serviço...")
        self.update_systemd_service(inst['type'], self.default_target)
        self.start_service(inst['type'])
        
        print(f"\nInstalação movida com sucesso para {self.default_target}")
    
    def update_paths_after_move(self, service_type: str, old_path: str, new_path: str):
        """Atualiza caminhos após mover instalação"""
        # Atualiza configuração YAML
        config_file = os.path.join(new_path, 'config', f'{service_type}.yml')
        if os.path.exists(config_file):
            with open(config_file, 'r') as f:
                content = f.read()
            
            content = content.replace(old_path, new_path)
            
            with open(config_file, 'w') as f:
                f.write(content)
        
        # Atualiza variáveis de ambiente
        env_file = os.path.join(new_path, 'bin', f'{service_type}-env')
        if os.path.exists(env_file):
            with open(env_file, 'r') as f:
                content = f.read()
            
            content = content.replace(old_path, new_path)
            
            with open(env_file, 'w') as f:
                f.write(content)
    
    def upgrade_opensearch(self, inst: Dict):
        """Atualiza OpenSearch para versão mais recente"""
        print(f"\nAtualizando OpenSearch {inst['version']}...")
        
        # Verifica versão mais recente disponível
        latest_version = self.get_latest_opensearch_version()
        print(f"Versão mais recente disponível: {latest_version}")
        
        if inst['version'] == latest_version:
            print("Já está na versão mais recente!")
            return
        
        # Faz backup primeiro
        print("\nFazendo backup antes da atualização...")
        backup_path = self.create_backup(inst)
        if not backup_path:
            print("Erro ao criar backup. Atualização cancelada.")
            return
        
        print(f"Backup salvo em: {backup_path}")
        
        # Processo de atualização in-place
        print("\nBaixando nova versão...")
        temp_dir = tempfile.mkdtemp()
        if not self.download_opensearch(latest_version, temp_dir):
            print("Erro ao baixar nova versão")
            return
        
        # Para o serviço
        if inst['running']:
            print("Parando serviço...")
            self.stop_service('opensearch')
        
        # Atualiza arquivos
        print("Atualizando arquivos...")
        self.update_opensearch_files(inst['path'], temp_dir, inst['version'], latest_version)
        
        # Reinicia serviço
        print("Reiniciando serviço...")
        self.start_service('opensearch')
        
        # Limpa arquivos temporários
        shutil.rmtree(temp_dir)
        
        print(f"\nAtualização concluída! OpenSearch atualizado para versão {latest_version}")
    
    def backup_installation(self):
        """Faz backup de uma instalação"""
        if not self.installations:
            print("Nenhuma instalação encontrada para backup")
            return
        
        print("\nEscolha a instalação para backup:")
        for i, inst in enumerate(self.installations, 1):
            print(f"{i}. {inst['type']} v{inst['version']} em {inst['path']}")
        
        choice = input("\nEscolha: ")
        try:
            inst = self.installations[int(choice) - 1]
        except:
            print("Escolha inválida")
            return
        
        backup_path = self.create_backup(inst)
        if backup_path:
            print(f"\nBackup criado com sucesso em: {backup_path}")
        else:
            print("\nErro ao criar backup")
    
    def create_backup(self, inst: Dict) -> Optional[str]:
        """Cria backup de uma instalação"""
        timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
        backup_name = f"{inst['type']}-backup-{timestamp}.tar.gz"
        backup_path = os.path.join("/tmp", backup_name)
        
        print(f"Criando backup em {backup_path}...")
        
        try:
            with tarfile.open(backup_path, "w:gz") as tar:
                # Backup de configurações
                if inst['config_path']:
                    config_dir = os.path.dirname(inst['config_path'])
                    tar.add(config_dir, arcname=f"config")
                
                # Backup de dados
                if inst['data_path'] and os.path.exists(inst['data_path']):
                    print("Incluindo dados no backup (pode demorar)...")
                    tar.add(inst['data_path'], arcname="data")
                
                # Informações da instalação
                info_file = os.path.join("/tmp", "backup_info.json")
                with open(info_file, 'w') as f:
                    json.dump(inst, f, indent=2)
                tar.add(info_file, arcname="backup_info.json")
                os.remove(info_file)
            
            return backup_path
        except Exception as e:
            print(f"Erro ao criar backup: {e}")
            return None
    
    def uninstall(self):
        """Desinstala uma instalação"""
        if not self.installations:
            print("Nenhuma instalação encontrada")
            return
        
        print("\nEscolha a instalação para desinstalar:")
        for i, inst in enumerate(self.installations, 1):
            status = "RODANDO" if inst['running'] else "PARADO"
            print(f"{i}. {inst['type']} v{inst['version']} em {inst['path']} ({status})")
        
        choice = input("\nEscolha: ")
        try:
            inst = self.installations[int(choice) - 1]
        except:
            print("Escolha inválida")
            return
        
        # Confirmação
        print(f"\nATENÇÃO: Isso irá remover completamente {inst['type']} incluindo:")
        print("- Todos os arquivos do programa")
        print("- Dados e índices")
        print("- Configurações")
        print("- Logs")
        
        if inst['data_size'] > 0:
            print(f"\nVolume de dados que será removido: {self.format_size(inst['data_size'])}")
        
        # Oferece backup
        if input("\nDeseja fazer backup antes de desinstalar? (s/N): ").lower() == 's':
            backup_path = self.create_backup(inst)
            if backup_path:
                print(f"Backup salvo em: {backup_path}")
            else:
                if input("Backup falhou. Continuar mesmo assim? (s/N): ").lower() != 's':
                    return
        
        if input("\nConfirma a desinstalação? (s/N): ").lower() != 's':
            return
        
        # Para o serviço
        if inst['running']:
            print("Parando serviço...")
            self.stop_service(inst['type'])
        
        # Remove arquivos
        print("Removendo arquivos...")
        paths_to_remove = [inst['path']]
        
        if inst['config_path'] and '/etc/' in inst['config_path']:
            paths_to_remove.append(os.path.dirname(inst['config_path']))
        
        if inst['data_path'] and inst['data_path'] not in paths_to_remove:
            paths_to_remove.append(inst['data_path'])
        
        if inst['logs_path'] and inst['logs_path'] not in paths_to_remove:
            paths_to_remove.append(inst['logs_path'])
        
        for path in paths_to_remove:
            if path and path != 'unknown' and os.path.exists(path):
                print(f"Removendo: {path}")
                shutil.rmtree(path)
        
        # Remove serviço do systemd
        service_file = f"/etc/systemd/system/{inst['type']}.service"
        if os.path.exists(service_file):
            os.remove(service_file)
            self.run_command(['systemctl', 'daemon-reload'])
        
        # Remove usuário se existir
        self.run_command(['userdel', inst['type']])
        
        print(f"\n{inst['type']} desinstalado com sucesso!")
    
    def install_new(self):
        """Instala nova versão do OpenSearch"""
        print("\nInstalando nova versão do OpenSearch...")
        
        # Verifica se já existe instalação no destino
        if os.path.exists(self.default_target):
            print(f"ERRO: Já existe uma instalação em {self.default_target}")
            return
        
        # Obtém versão mais recente
        latest_version = self.get_latest_opensearch_version()
        version = input(f"\nQual versão instalar? (Enter para {latest_version}): ").strip()
        if not version:
            version = latest_version
        
        # Baixa e instala
        if self.download_and_install_opensearch(self.default_target, 9200, version):
            print(f"\nOpenSearch {version} instalado com sucesso em {self.default_target}")
            print("Para iniciar o serviço, execute: systemctl start opensearch")
        else:
            print("\nErro na instalação")
    
    def get_latest_opensearch_version(self) -> str:
        """Obtém a versão mais recente do OpenSearch"""
        # Por enquanto retorna uma versão fixa, mas poderia consultar API do GitHub
        return "2.11.0"
    
    def download_opensearch(self, version: str, dest_dir: str) -> bool:
        """Baixa OpenSearch da versão especificada"""
        url = f"https://artifacts.opensearch.org/releases/bundle/opensearch/{version}/opensearch-{version}-linux-x64.tar.gz"
        
        print(f"Baixando OpenSearch {version}...")
        
        try:
            response = requests.get(url, stream=True)
            response.raise_for_status()
            
            tar_path = os.path.join(dest_dir, f"opensearch-{version}.tar.gz")
            
            total_size = int(response.headers.get('content-length', 0))
            block_size = 8192
            downloaded = 0
            
            with open(tar_path, 'wb') as f:
                for chunk in response.iter_content(block_size):
                    downloaded += len(chunk)
                    f.write(chunk)
                    if total_size > 0:
                        percent = (downloaded / total_size) * 100
                        print(f"\rProgresso: {percent:.1f}%", end='', flush=True)
            
            print("\nExtraindo arquivos...")
            with tarfile.open(tar_path, 'r:gz') as tar:
                tar.extractall(dest_dir)
            
            os.remove(tar_path)
            return True
            
        except Exception as e:
            print(f"\nErro ao baixar: {e}")
            return False
    
    def download_and_install_opensearch(self, install_path: str, port: int = 9200, version: str = None) -> bool:
        """Baixa e instala OpenSearch"""
        if not version:
            version = self.get_latest_opensearch_version()
        
        # Cria diretório temporário
        temp_dir = tempfile.mkdtemp()
        
        try:
            # Baixa OpenSearch
            if not self.download_opensearch(version, temp_dir):
                return False
            
            # Move para destino final
            extracted_dir = os.path.join(temp_dir, f"opensearch-{version}")
            if os.path.exists(extracted_dir):
                os.makedirs(os.path.dirname(install_path), exist_ok=True)
                shutil.move(extracted_dir, install_path)
            else:
                print("Erro: diretório extraído não encontrado")
                return False
            
            # Configura OpenSearch
            self.configure_opensearch(install_path, port)
            
            # Cria usuário opensearch
            self.run_command(['useradd', '-r', '-s', '/bin/false', 'opensearch'])
            
            # Ajusta permissões
            self.run_command(['chown', '-R', 'opensearch:opensearch', install_path])
            
            # Cria serviço systemd
            self.create_systemd_service('opensearch', install_path)
            
            return True
            
        finally:
            # Limpa diretório temporário
            if os.path.exists(temp_dir):
                shutil.rmtree(temp_dir)
    
    def configure_opensearch(self, install_path: str, port: int):
        """Configura OpenSearch após instalação"""
        config_file = os.path.join(install_path, 'config', 'opensearch.yml')
        
        # Configuração básica
        config = f"""
cluster.name: opensearch-cluster
node.name: node-1
path.data: {install_path}/data
path.logs: {install_path}/logs
network.host: 0.0.0.0
http.port: {port}
discovery.type: single-node
plugins.security.disabled: true
"""
        
        with open(config_file, 'w') as f:
            f.write(config)
        
        # Cria diretórios necessários
        os.makedirs(os.path.join(install_path, 'data'), exist_ok=True)
        os.makedirs(os.path.join(install_path, 'logs'), exist_ok=True)
    
    def create_systemd_service(self, service_type: str, install_path: str):
        """Cria arquivo de serviço systemd"""
        service_content = f"""[Unit]
Description=OpenSearch
Documentation=https://opensearch.org/docs
Wants=network-online.target
After=network-online.target

[Service]
Type=notify
RuntimeDirectory={service_type}
PrivateTmp=true
Environment=OPENSEARCH_HOME={install_path}
Environment=OPENSEARCH_PATH_CONF={install_path}/config

WorkingDirectory={install_path}

User=opensearch
Group=opensearch

ExecStart={install_path}/bin/opensearch

StandardOutput=journal
StandardError=inherit

LimitNOFILE=65535
LimitNPROC=4096
LimitAS=infinity
LimitFSIZE=infinity
TimeoutStopSec=0
KillSignal=SIGTERM
KillMode=process
SendSIGKILL=no
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target
"""
        
        service_file = f"/etc/systemd/system/{service_type}.service"
        with open(service_file, 'w') as f:
            f.write(service_content)
        
        self.run_command(['systemctl', 'daemon-reload'])
    
    def update_systemd_service(self, service_type: str, new_path: str):
        """Atualiza arquivo de serviço systemd com novo caminho"""
        service_file = f"/etc/systemd/system/{service_type}.service"
        
        if os.path.exists(service_file):
            with open(service_file, 'r') as f:
                content = f.read()
            
            # Atualiza caminhos
            lines = content.split('\n')
            for i, line in enumerate(lines):
                if 'Environment=OPENSEARCH_HOME=' in line or 'Environment=ELASTICSEARCH_HOME=' in line:
                    lines[i] = f"Environment=OPENSEARCH_HOME={new_path}"
                elif 'Environment=OPENSEARCH_PATH_CONF=' in line or 'Environment=ELASTICSEARCH_PATH_CONF=' in line:
                    lines[i] = f"Environment=OPENSEARCH_PATH_CONF={new_path}/config"
                elif 'WorkingDirectory=' in line:
                    lines[i] = f"WorkingDirectory={new_path}"
                elif 'ExecStart=' in line:
                    lines[i] = f"ExecStart={new_path}/bin/{service_type}"
            
            with open(service_file, 'w') as f:
                f.write('\n'.join(lines))
            
            self.run_command(['systemctl', 'daemon-reload'])
    
    def stop_service(self, service_type: str):
        """Para um serviço"""
        self.run_command(['systemctl', 'stop', f'{service_type}.service'])
    
    def start_service(self, service_type: str):
        """Inicia um serviço"""
        self.run_command(['systemctl', 'start', f'{service_type}.service'])
        self.run_command(['systemctl', 'enable', f'{service_type}.service'])
    
    def start_opensearch(self, install_path: str, port: int):
        """Inicia OpenSearch em uma porta específica"""
        # Temporariamente ajusta a porta na configuração
        config_file = os.path.join(install_path, 'config', 'opensearch.yml')
        self.reconfigure_port(install_path, 9200, port)
        
        self.start_service('opensearch')
    
    def reconfigure_port(self, install_path: str, old_port: int, new_port: int):
        """Reconfigura porta no arquivo de configuração"""
        config_file = os.path.join(install_path, 'config', 'opensearch.yml')
        
        if os.path.exists(config_file):
            with open(config_file, 'r') as f:
                content = f.read()
            
            content = content.replace(f'http.port: {old_port}', f'http.port: {new_port}')
            
            with open(config_file, 'w') as f:
                f.write(content)
    
    def update_opensearch_files(self, install_path: str, new_files_path: str, old_version: str, new_version: str):
        """Atualiza arquivos do OpenSearch preservando configurações e dados"""
        # Faz backup das configurações
        config_backup = os.path.join("/tmp", "opensearch-config-backup")
        shutil.copytree(os.path.join(install_path, 'config'), config_backup)
        
        # Lista de diretórios a preservar
        preserve_dirs = ['data', 'logs']
        
        # Remove arquivos antigos (exceto os que devem ser preservados)
        for item in os.listdir(install_path):
            item_path = os.path.join(install_path, item)
            if item not in preserve_dirs + ['config']:
                if os.path.isdir(item_path):
                    shutil.rmtree(item_path)
                else:
                    os.remove(item_path)
        
        # Copia novos arquivos
        new_opensearch_dir = os.path.join(new_files_path, f"opensearch-{new_version}")
        for item in os.listdir(new_opensearch_dir):
            if item not in preserve_dirs:
                src = os.path.join(new_opensearch_dir, item)
                dst = os.path.join(install_path, item)
                if os.path.isdir(src):
                    shutil.copytree(src, dst)
                else:
                    shutil.copy2(src, dst)
        
        # Mescla configurações
        self.merge_configs(config_backup, os.path.join(install_path, 'config'))
        
        # Remove backup temporário
        shutil.rmtree(config_backup)
        
        # Ajusta permissões
        self.run_command(['chown', '-R', 'opensearch:opensearch', install_path])
    
    def merge_configs(self, old_config_path: str, new_config_path: str):
        """Mescla configurações antigas com as novas"""
        # Por simplicidade, apenas copia o opensearch.yml antigo
        old_yml = os.path.join(old_config_path, 'opensearch.yml')
        new_yml = os.path.join(new_config_path, 'opensearch.yml')
        
        if os.path.exists(old_yml):
            shutil.copy2(old_yml, new_yml)
    
    def run(self):
        """Executa o gerenciador"""
        print("=== OpenSearch/Elasticsearch Manager ===")
        print("Analisando sistema...\n")
        
        self.check_root()
        self.find_installations()
        
        while True:
            if self.show_menu():
                break
        
        print("\nObrigado por usar o OpenSearch Manager!")


def main():
    parser = argparse.ArgumentParser(description='Gerenciador unificado para OpenSearch e Elasticsearch')
    parser.add_argument('--target', default='/opt/prod/opensearch', help='Diretório de destino para instalações')
    parser.add_argument('--auto', action='store_true', help='Modo automático (sem interação)')
    
    args = parser.parse_args()
    
    manager = OpenSearchManager()
    if args.target:
        manager.default_target = args.target
    
    try:
        manager.run()
    except KeyboardInterrupt:
        print("\n\nOperação cancelada pelo usuário")
        sys.exit(0)
    except Exception as e:
        print(f"\nErro: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()