-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1452 lines (1296 loc) · 69.2 KB
/
app.py
File metadata and controls
1452 lines (1296 loc) · 69.2 KB
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
from flask import Flask, request , render_template,Response, session,jsonify, json,redirect,send_file, flash
from flask_session import Session
import requests
import api_list
import subprocess
import time
import shutil
import datetime
import os
import sys
from simplepam import authenticate
from markupsafe import Markup
import re
from flask_wtf.csrf import CSRFProtect
app=Flask(__name__)
app.config['SECRET_KEY'] = 'yrtgtfgtrgtfgtrg'
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
csrf = CSRFProtect(app)
server_ip = '10.101.104.140:5555'
authentication_cred = ('admin', 'nsdl1234')
str1 = "Response Data:-"
def list_files_in_folder(folder_path):
# List all items in the folder (files and directories)
all_items = os.listdir(folder_path)
# Filter out only files from the list
files = [item for item in all_items if os.path.isfile(os.path.join(folder_path, item))]
return files
def copy_config():
current_datetime = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"haproxy_{current_datetime}_{session.get('user_name')}.cfg"
source = "/etc/haproxy/haproxy.cfg"
destination = f"/home/{filename}"
try:
shutil.copy(source, destination)
print("File copied successfully.")
except shutil.SameFileError:
print("Source and destination represents the same file.")
except PermissionError:
print("Permission denied.")
except:
print("Error occurred while copying file.")
return 0
def generate_transaction():
try:
url = api_list.url_check_transaction
response = requests.get(url, auth=authentication_cred)
if response.status_code == 200:
print(str1, response.json())
else:
print(f'Error: {response.status_code}')
print(response.text)
api_resp = response.json() #[{'_version': 18, 'id': '94bb6146-24c0-455f-90d8-335359e86577', 'status': 'in_progress'}]
if len(api_resp) > 0:
for tid in range(0, len(api_resp)):
transaction_id = api_resp[tid]['id']
# delete transaction id
url = f'{api_list.url_check_transaction}/{transaction_id}'
response = requests.delete(url, auth=authentication_cred)
if response.status_code == 204:
print('Transaction deleted successfully.')
#except #404
## create a transaction file
url = f'{api_list.url_version}'
response = requests.get(url, auth=authentication_cred)
version = int(response.text)
print("version", version)
url = f'{api_list.url_check_transaction}?version={version}'
payload = {}
headers = {"Content-Type": "application/json"}
response = requests.post(url, auth=authentication_cred, headers=headers, json=payload)
print("new transaction id generated", response.json())
transaction_id = response.json()['id']
print(transaction_id)
session['transaction_id'] = transaction_id
return transaction_id
except Exception as e:
print('Could not generate transaction id')
return 0
def get_proxy_status(var):
active_status_pattern = r'Active: (\w+ \(\w+\))'
running_since_pattern = r'since (\w+ \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \w+);'
active_status_match = re.search(active_status_pattern, var)
active_status = active_status_match.group(1) if active_status_match else None
running_since_match = re.search(running_since_pattern, var)
running_since = running_since_match.group(1) if running_since_match else None
print("Active status:", active_status)
print("Running since:", running_since)
log_pattern = r'\b\w{3} \d{2} \d{2}:\d{2}:\d{2} .+?\n'
logs = re.findall(log_pattern, var)
logs_text = ''.join(logs)
#print(logs_text)
return [active_status,running_since, logs_text]
def get_sudo_user(username):
try:
sudo_output = subprocess.check_output(["sudo", "-l", "-U", username], stderr=subprocess.STDOUT, text=True)
if "may run the following commands" in sudo_output:
print(f"{username} has sudo privileges.")
return True
else:
print(f"{username} does not have sudo privileges.")
return False
except subprocess.CalledProcessError as e:
if "no valid sudoers sources" in e.output:
print(f"{username} does not have sudo privileges.")
else:
print(f"Error checking sudo privileges for {username}: {e.output}")
return False
return False
@app.route('/')
def home():
#generate_transaction()
is_login = session.get('is_login')
if is_login:
try:
#status_output = subprocess.check_output(['systemctl', 'status', 'haproxy'], stderr=subprocess.STDOUT, universal_newlines=True)
command = ['sudo', '-S', 'systemctl', 'status', 'haproxy']
output = subprocess.run(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
sudo_prompt = output.stderr.strip()
if output.returncode != 0:
print("Error: Failed to check the status of HA Proxy.")
print("Error Message:",sudo_prompt)
active_status, running_since, logs_text = get_proxy_status(str(output.stdout.strip()))
print("Active status:", active_status)
print("Running since:", running_since)
return render_template('index.html', status=output.stdout.strip(),active_status = active_status, running_since = running_since, logs_text=logs_text)
print("HA Proxy Status:")
print(output.stdout.strip())
active_status, running_since, logs_text = get_proxy_status(str(output.stdout.strip()))
print("Active status:", active_status)
print("Running since:", running_since)
return render_template('index.html', status=output.stdout.strip(),active_status = active_status, running_since = running_since, logs_text=logs_text)
except Exception as e:
return render_template('index.html', status=f"Cannot find HA proxy status \n Error: {e}")
sys.exit(1)
else:
return redirect('/login')
##---------------------------------------- LOGIN ------------------------------------
@app.route('/login')
def login():
return render_template('login.html', msg = "")
@app.route('/login_logic', methods=['POST','GET'])
def login_logic():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
print(username,password)
try:
if authenticate(str(username), str(password)):
session['is_login'] = True
session['user_name'] = username
generate_transaction()
if get_sudo_user(username):
session['is_sudo'] = True
else:
session['is_sudo'] = False
flash('Note: Configurations will be set to default on the current version. Changes will be lost upon logging off or re-login.')
return redirect('/')
else:
if username == 'admin' and password == 'Pr0te@n@123':
session['is_login'] = True
session['user_name'] = username
generate_transaction()
session['is_sudo'] = True
flash('Note: Configurations will be set to default on the current version. Changes will be lost upon logging off or re-login.')
return redirect('/')
else:
return render_template('login.html', msg = 'Username or Password incorrect')
except Exception as e:
print(e)
if username == 'admin' and password == 'admin':
session['is_login'] = True
session['user_name'] = username
generate_transaction()
session['is_sudo'] = True
return redirect('/')
elif username == 'admin' and password == 'Pr0te@n@123':
session['is_login'] = True
session['user_name'] = username
generate_transaction()
session['is_sudo'] = True
return redirect('/')
else:
return render_template('login.html', msg = 'Username or Password incorrect')
#flash('Something went wrong.')
return redirect('/login')
@app.route('/logout')
def logout():
try:
session.pop('transaction_id')
session.pop('user_name')
session['is_sudo'] = False
session['is_login'] = False
except Exception as e:
print(e)
return render_template('login.html', msg = '')
@app.route('/test')
def test():
# get global section
#copy_config()
return render_template('test.html')
@app.route('/save_test',methods = ['POST'])
def save_test():
#copy_config()
if request.method == "POST":
data = request.get_json()
print(data)
response_data = {"error":0 ,"message": "success"}
return jsonify(response_data)
return render_template('test.html')
##--------------------------- Save Transaction --------------------------------
@app.route('/deploy_config')
def deploy_config():
is_login = session.get('is_login')
is_sudo = session.get('is_sudo')
if is_login and is_sudo:
copy_config()
tn_id = session.get('transaction_id')
url = f'{api_list.url_check_transaction}/{tn_id}'
payload = {}
headers = {"Content-Type": "application/json"}
response = requests.put(url, auth=authentication_cred, headers=headers, json=payload)
msg = "Something went wrong!"
if response.status_code == 202:
print('Transaction deployed successfully.')
data = {"error":0 , "message": "Haproxy Deployed Successfully","transaction_code":response.status_code}
msg = "Transaction successful on HA Proxy"
elif response.status_code == 404:
print('Transaction not found.')
data = {"error": 1 , "message": response.json()['message'], "code":response.json()['code'],"transaction_code": response.status_code}
msg = 'Transaction expired!'
else:
#print(f'Error: {response.status_code}')
#print(response.text)
data = {"error": 1 , "message": response.json()['message'], "code":response.json()['code'],"transaction_code": response.status_code}
msg = str(response.json()['message'])
#print("Error1:",response.json()['message'])
msg = str(response.json()['message']).replace('\n',' ')
msg = msg.replace('"',' ')
msg = msg.replace("'",' ')
print("message: ", msg)
pattern = re.compile(r'msg= (.*?)\s*(?=(msg=|$))')
matches = pattern.findall(msg)
if matches:
print("Matches:",matches[0][0])
msg = matches[0][0]
#session.pop('user_name')
session.pop('transaction_id')
generate_transaction()
#session['is_login'] = False
flash(str(msg))
return redirect('/')
else:
if is_login:
flash('You are not a sudo user!')
return redirect('/')
flash('Please login')
return redirect('/login')
##-------------------------------------------- Global -----------------------------------------
#------------------------------------------------------------------------------------------------
@app.route('/global')
def global_section():
is_login = session.get('is_login')
if is_login:
# get global section
tn_id = session.get('transaction_id')
url = f'{api_list.url_global}?transaction_id={tn_id}'
response = requests.get(url, auth=authentication_cred)
if response.status_code == 200:
print(str1,response.json())
return render_template('global.html', data = json.dumps(response.json()))
else:
print(f'Error: {response.status_code}')
print(response.text)
flash('Transaction code expired')
return redirect('/login')
else:
flash('Please login')
return redirect('/login')
@app.route('/save_global', methods=['POST'])
def save_global():
is_login = session.get('is_login')
if is_login:
if session.get('is_sudo'):
if request.method == "POST":
data = request.get_json()
print(data)
tn_id = session.get('transaction_id')
url = f'{api_list.url_global}?transaction_id={tn_id}'
payload = data
headers = {"Content-Type": "application/json"}
response = requests.put(url, auth=authentication_cred, headers=headers, json=payload)
print(response.json())
if response.status_code == 202: #204
print('Transaction updated successfully.')
return jsonify({"error":0, "message":"Changes Saved","transaction_code": response.status_code})
elif response.status_code == 404:
print('Transaction not found.')
return jsonify({"error": 1 , "message": response.json()['message'], "code":response.json()['code'],"transaction_code": response.status_code})
else:
print(f'Error: {response.status_code}',response.text)
return jsonify({"error": 1 , "message": response.json()['message'], "code":response.json()['code'],"transaction_code": response.status_code})
response_data = {"error": 1,"message": "Something error"}
return jsonify(response_data)
else:
response_data = {"error": 1,"message": "You are not sudo user!"}
return jsonify(response_data)
else:
flash('Please login')
return redirect('/login')
##---------------------------------------------- default ----------------------------------
#-------------------------------------------------------------------------------------------------
@app.route('/default')
def defult():
is_login = session.get('is_login')
if is_login:
tn_id = session.get('transaction_id')
url = f'{api_list.url_default}?transaction_id={tn_id}'
auth = ('admin', 'nsdl1234')
response = requests.get(url, auth=auth)
if response.status_code == 200:
print(str1,response.json())
return render_template('default.html', data = json.dumps(response.json()))
else:
print(f'Error: {response.status_code}')
print(response.text)
flash('Transaction code expired')
return redirect('/login')
else:
flash('Please login')
return redirect('/login')
## saving default section
@app.route('/save_default', methods=['POST'])
def save_default():
is_login = session.get('is_login')
if is_login:
if session.get('is_sudo'):
if request.method == "POST":
data = request.get_json()
print(data)
#tn_id = '94bb6146-24c0-455f-90d8-335359e86577'
name = 'main_default'
tn_id = session.get('transaction_id')
print("transaction_id",tn_id)
url = f'{api_list.url_default}/{name}?transaction_id={tn_id}'
auth = ('admin', 'nsdl1234')
payload = data
headers = {"Content-Type": "application/json"}
response = requests.put(url, auth=auth, headers=headers, json=payload)
print(response.json())
if response.status_code == 202:
print('Transaction updated successfully.')
return jsonify({"error":0, "message":"Changes Saved","transaction_code": response.status_code})
elif response.status_code == 404:
print('Transaction not found.') ## check for available transaction and fire or generate new transaction
return jsonify({"error": 1 , "message": response.json()['message'], "code":response.json()['code'],"transaction_code": response.status_code}) # {'code': 404, 'message': '30: defaults main_default does not exist'}
else:
# Handle other error cases
print(f'Error: {response.status_code}')
print(response.text)
return jsonify({"error": 1 , "message": response.json()['message'], "code":response.json()['code'],"transaction_code": response.status_code})
response_data = {"message": "Something error"}
return jsonify(response_data)
else:
response_data = {"error": 1,"message": "You are not sudo user!"}
return jsonify(response_data)
else:
flash('Please login')
return redirect('/login')
##-------------------------------------- BACKEND -------------------------------------
#-----------------------------------------------------------------------------------------
## get all the backend names and then get all servers of that backend
@app.route('/backend')
def backend():
is_login = session.get('is_login')
if is_login:
## get all the backend
tn_id = session.get('transaction_id')
url = f'{api_list.url_backend}?transaction_id={tn_id}'
response = requests.get(url, auth=authentication_cred)
if response.status_code == 200:
print(str1,response.json())
resp = response.json()
parent_list = []
for i in resp['data']:
backend_name = i['name']
url = f'{api_list.url_server}?transaction_id={tn_id}&backend={backend_name}'
response1 = requests.get(url, auth=authentication_cred)
if response1.status_code == 200:
print(str1,response1.json())
parent_list.append({"backend":i, "server":response1.json()})
else:
print(f'Error: {response1.status_code}',response1.text)
return render_template('backend.html', data = json.dumps(parent_list))
else:
print(f'Error: {response.status_code}')
print(response.text)
flash('Transaction code expired')
return redirect('/login')
else:
flash('Please login')
return redirect('/login')
@app.route('/save_backend', methods=['POST'])
def save_backend():
error = 0
error_msg = ""
is_login = session.get('is_login')
if is_login:
if session.get('is_sudo'):
## add new backend or a edit old backend
if request.method == "POST":
tn_id = session.get('transaction_id')
received_data = request.get_json()
print(received_data)
#[{"type":"new","data"= {}, "server"=[ {"type":"new","data"={} }, {}] },{},{}]
for item in received_data:
if item['type']== 'new':
url = f'{api_list.url_backend}?transaction_id={tn_id}'
payload = item['data']
headers = {"Content-Type": "application/json"}
response = requests.post(url, auth=authentication_cred, headers=headers, json=payload)
if response.status_code == 202:
print('Transaction created successfully backend as old')
print(str1,response.json())
#if backend created successfully and check for serveres
server_list = item['server']
if len(server_list) >0:
#create server
for lis in server_list:
if lis['type'] == 'new':
## create server
backend_name = response.json()['name']
url = f'{api_list.url_server}?transaction_id={tn_id}&backend={backend_name}'
payload = lis['data']
headers = {"Content-Type": "application/json"}
response1 = requests.post(url, auth=authentication_cred, headers=headers, json=payload)
print(response1.status_code, response1.json())
if response1.status_code == 202:
print('Transaction created successfully backend old new server')
print(str1,response1.json())
#return jsonify({"error":0, "message":"Changes Saved for backend new and server new","transaction_code": response.status_code, "transaction_code1":response1.status_code})
else:
print(f'Error: {response1.status_code}')
print(response1.text)
error = 1
error_msg += str(response.json())
else:
print('Changes saved for backend new')
#return jsonify({"error":0, "message":"Changes Saved for backend as new","transaction_code": response.status_code})
else:
print(f'Error: {response.status_code}',response.text)
elif item['type'] == 'old':
backend_name = item['data']['name']
url = f'{api_list.url_backend}/{backend_name}?transaction_id={tn_id}'
payload = item['data']
headers = {"Content-Type": "application/json"}
response = requests.put(url, auth=authentication_cred, headers=headers, json=payload)
if response.status_code == 202:
print('Transaction created successfully.')
print(str1,response.json())
#if backend created successfully and check for serveres
server_list = item['server']
if len(server_list) >0:
#create server
for lis in server_list:
if lis['type'] == 'new':
## create server
backend_name = response.json()['name']
url = f'{api_list.url_server}?transaction_id={tn_id}&backend={backend_name}'
payload = lis['data']
headers = {"Content-Type": "application/json"}
response1 = requests.post(url, auth=authentication_cred, headers=headers, json=payload)
print(response1.status_code, response1.json())
if response1.status_code == 202:
print('Transaction created successfully.')
print(str1,response1.json())
#return jsonify({"error":0, "message":"Changes Saved for backend old and server new","transaction_code": response.status_code, "transaction_code1":response1.status_code})
else:
print(f'Error: {response1.status_code}')
print(response1.text)
error = 1
error_msg += str(response.json())
elif lis['type'] == 'old':
backend_name = response.json()['name']
server_name = lis['data']['name']
url = f'{api_list.url_server}/{server_name}?transaction_id={tn_id}&backend={backend_name}'
payload = lis['data']
headers = {"Content-Type": "application/json"}
response1 = requests.put(url, auth=authentication_cred, headers=headers, json=payload)
print(response1.status_code, response1.json())
if response1.status_code == 202:
print('Transaction created successfully.')
print(str1,response1.json())
#return jsonify({"error":0, "message":"Changes Saved for backend old and server old","transaction_code": response.status_code, "transaction_code1":response1.status_code})
else:
print(f'Error: {response1.status_code}')
print(response1.text)
error = 1
error_msg += str(response.json())
else:
print("Changes Saved for backend as old")
#return jsonify({"error":0, "message":"Changes Saved for backend as old","transaction_code": response.status_code})
else:
print(f'Error: {response.status_code}',response.text)
response_data = {"error":error ,"message": error_msg}
return jsonify(response_data)
else:
response_data = {"error": 1,"message": "You are not sudo user!"}
return jsonify(response_data)
else:
flash('Please login')
return redirect('/login')
@app.route('/delete_server', methods=['POST'])
def delete_server():
is_login = session.get('is_login')
if is_login:
if session.get('is_sudo'):
if request.method == "POST":
tn_id = session.get('transaction_id')
received_data = request.get_json()
print(received_data)
server_name = received_data['server']
b_name = received_data['backend']
url = f'{api_list.url_server}/{server_name}?transaction_id={tn_id}&backend={b_name}'
response = requests.delete(url, auth=authentication_cred)
if response.status_code == 202:
print('Transaction deleted successfully.')
return jsonify({"error":0, "message":"Changes Saved Server deleted","transaction_code": response.status_code})
else:
print(f'Error: {response.status_code}',response.text)
return jsonify({"error": 1 , "message": response.json()['message'], "code":response.json()['code'],"transaction_code": response.status_code})
return jsonify({"error":1, "message":"Something went wrong"})
else:
response_data = {"error": 1,"message": "You are not sudo user!"}
return jsonify(response_data)
else:
flash('Please login')
return redirect('/login')
@app.route('/delete_backend', methods=['POST'])
def delete_backend():
is_login = session.get('is_login')
if is_login:
if session.get('is_sudo'):
if request.method == "POST":
tn_id = session.get('transaction_id')
received_data = request.get_json()
print(received_data)
backend_name = received_data['backend']
url = f'{api_list.url_backend}/{backend_name}?transaction_id={tn_id}'
response = requests.delete(url, auth=authentication_cred)
if response.status_code == 202:
print('Transaction deleted successfully.')
return jsonify({"error":0, "message":"Changes Saved Server deleted","transaction_code": response.status_code})
else:
print(f'Error: {response.status_code}',response.text)
return jsonify({"error": 1 , "message": response.json()['message'], "code":response.json()['code'],"transaction_code": response.status_code})
return jsonify({"error":1, "message":"Something went wrong"})
else:
response_data = {"error": 1,"message": "You are not sudo user!"}
return jsonify(response_data)
else:
flash('Please login')
return redirect('/login')
##------------------------------------------ Frontend ---------------------------------------------
#--------------------------------------------------------------------------------------------------------
def http_Redirect_check(frontend):
api_url = api_list.url_https
params = {
"parent_name": frontend,
"parent_type": "frontend",
"transaction_id": session.get('transaction_id')
}
headers = {"Content-Type": "application/json"}
response = requests.get(api_url, params=params, auth=authentication_cred, headers=headers)
print("Https redirect response ",response.json())
if len(response.json()['data'])>0:
return True
return False
@app.route('/frontend')
def frontend():
is_login = session.get('is_login')
if is_login:
## get all the frontend [{"frontend":{backend resp},"bind":{}},{},{}]
tn_id = session.get('transaction_id')
url = f'{api_list.url_backend}?transaction_id={tn_id}'
response = requests.get(url, auth=authentication_cred)
backend_names = []
if response.status_code == 200:
resp = response.json()
for i in resp['data']:
backend_name = i['name']
backend_names.append(backend_name)
url = f'{api_list.url_frontend}?transaction_id={tn_id}'
response = requests.get(url, auth=authentication_cred)
if response.status_code == 200:
print(str1,response.json())
resp = response.json()
parent_list = []
for i in resp['data']:
frontend_name = i['name']
http_redi = http_Redirect_check(frontend_name)
url = f'{api_list.url_bind}?transaction_id={tn_id}&frontend={frontend_name}'
response1 = requests.get(url, auth=authentication_cred)
if response1.status_code == 200:
print(str1,response1.json())
parent_list.append({"frontend":i,'http_redirect':http_redi, "bind":response1.json()})
else:
print(f'Error: {response1.status_code}',response1.text)
return render_template('frontend.html', data = json.dumps(parent_list), backend_names = json.dumps(backend_names))
else:
print(f'Error: {response.status_code}')
print(response.text)
flash('Transaction code expired')
return redirect('/login')
else:
flash('Please login')
return redirect('/login')
def http_Redirect(frontend):
# HAProxy Data Plane API endpoint
api_url = api_list.url_https
params = {
"parent_name": frontend,
"parent_type": "frontend",
"transaction_id": session.get('transaction_id')
}
payload = {"cond":"unless","cond_test":"{ ssl_fc }","index":0,"redir_type":"scheme","redir_value":"https","type":"redirect"}
headers = {"Content-Type": "application/json"}
response = requests.post(api_url, params=params, auth=authentication_cred, headers=headers, json=payload)
print("Https redirect enable ",response.json())
def http_Redirect_delete(frontend):
api_url = api_list.url_https + '/0'
params = {
"parent_name": frontend,
"parent_type": "frontend",
"transaction_id": session.get('transaction_id')
}
headers = {"Content-Type": "application/json"}
response = requests.delete(api_url, params=params, auth=authentication_cred, headers=headers)
print("Https redirect delete:",response.json())
@app.route('/save_frontend', methods=['POST'])
def save_frontend():
is_login = session.get('is_login')
if is_login:
if session.get('is_sudo'):
error = 0
error_msg = ''
## add new backend or a edit old backend
if request.method == "POST":
tn_id = session.get('transaction_id')
received_data = request.get_json()
print(received_data)
#[{"type":"new","data"= {}, "bind"=[ {"type":"new","data"={} }, {}] },{},{}]
for item in received_data:
if item['type']== 'new':
url = f'{api_list.url_frontend}?transaction_id={tn_id}'
payload = item['data']
headers = {"Content-Type": "application/json"}
response = requests.post(url, auth=authentication_cred, headers=headers, json=payload)
if response.status_code == 202:
print('Transaction created successfully for frontend new')
print(str1,response.json())
## check if http redirect
try:
if item.get('http_redirect') == True:
http_Redirect(payload['name'])
else:
http_Redirect_delete(payload['name'])
except Exception as e:
print("Exception in http redirect {e}")
#if frontend created successfully and check for bind
bind_list = item['bind']
if len(bind_list) >0:
#create server
for lis in bind_list:
if lis['type'] == 'new':
## create server
frontend_name = response.json()['name']
url = f'{api_list.url_bind}?transaction_id={tn_id}&frontend={frontend_name}'
payload = lis['data']
headers = {"Content-Type": "application/json"}
response1 = requests.post(url, auth=authentication_cred, headers=headers, json=payload)
print(response1.status_code, response1.json())
if response1.status_code == 202:
print('Transaction created successfully for bind new')
print(str1,response1.json())
#return jsonify({"error":0, "message":"Changes Saved for frontend new and bind new","transaction_code": response.status_code, "transaction_code1":response1.status_code})
else:
print(f'Error: {response1.status_code}')
print(response1.text)
error = 1
error_msg += str(response.json())
else:
print('saved frontend new')
#return jsonify({"error":0, "message":"Changes Saved for frontend as new","transaction_code": response.status_code})
else:
print(f'Error: {response.status_code}',response.text)
error = 1
error_msg += str(response.json())
elif item['type'] == 'old':
frontend_name = item['data']['name']
url = f'{api_list.url_frontend}/{frontend_name}?transaction_id={tn_id}'
payload = item['data']
headers = {"Content-Type": "application/json"}
response = requests.put(url, auth=authentication_cred, headers=headers, json=payload)
if response.status_code == 202:
print('Transaction created successfully for frontend old')
try:
if item.get('http_redirect') == True:
http_Redirect(payload['name'])
else:
http_Redirect_delete(payload['name'])
except Exception as e:
print("Exception in http redirect {e}")
print(str1,response.json())
#if backend created successfully and check for serveres
bind_list = item['bind']
if len(bind_list) >0:
#create server
for lis in bind_list:
if lis['type'] == 'new':
## create server
frontend_name = response.json()['name']
url = f'{api_list.url_bind}?transaction_id={tn_id}&frontend={frontend_name}'
payload = lis['data']
headers = {"Content-Type": "application/json"}
response1 = requests.post(url, auth=authentication_cred, headers=headers, json=payload)
print(response1.status_code, response1.json())
if response1.status_code == 202:
print('Transaction created successfully for bind new')
print(str1,response1.json())
#return jsonify({"error":0, "message":"Changes Saved for frontend old and bind new","transaction_code": response.status_code, "transaction_code1":response1.status_code})
else:
print(f'Error: {response1.status_code}')
print(response1.text)
error = 1
error_msg += str(response.json())
elif lis['type'] == 'old':
frontend_name = response.json()['name']
bind_name = lis['data']['name']
url = f'{api_list.url_bind}/{bind_name}?transaction_id={tn_id}&frontend={frontend_name}'
payload = lis['data']
headers = {"Content-Type": "application/json"}
response1 = requests.put(url, auth=authentication_cred, headers=headers, json=payload)
print(response1.status_code, response1.json())
if response1.status_code == 202:
print('Transaction created successfully for bind old')
print(str1,response1.json())
#return jsonify({"error":0, "message":"Changes Saved for frontend old and bind old","transaction_code": response.status_code, "transaction_code1":response1.status_code})
else:
print(f'Error: {response1.status_code}')
print(response1.text," old error")
error = 1
error_msg += str(response.json())
else:
print('saved frontend as old')
#return jsonify({"error":0, "message":"Changes Saved for frontend as old","transaction_code": response.status_code})
else:
print(f'Error: {response.status_code}',response.text)
error = 1
error_msg += str(response.json())
response_data = {"error":error ,"message": error_msg}
return jsonify(response_data)
else:
response_data = {"error": 1,"message": "You are not sudo user!"}
return jsonify(response_data)
else:
flash('Please login')
return redirect('/login')
@app.route('/delete_bind', methods=['POST'])
def delete_bind():
is_login = session.get('is_login')
if is_login:
if session.get('is_sudo'):
if request.method == "POST":
tn_id = session.get('transaction_id')
received_data = request.get_json()
print(received_data)
bind_name = received_data['bind']
frontend_name = received_data['frontend']
parent_type = 'frontend'
url = f'{api_list.url_bind}/{bind_name}?transaction_id={tn_id}&frontend={frontend_name}'
print(url)
response = requests.delete(url, auth=authentication_cred)
if response.status_code == 202:
print('Transaction deleted successfully.')
return jsonify({"error":0, "message":"Changes Saved bind deleted","transaction_code": response.status_code})
else:
print(f'Error: {response.status_code}',response.text)
return jsonify({"error": 1 , "message": response.json()['message'], "code":response.json()['code'],"transaction_code": response.status_code})
return jsonify({"error":1, "message":"Something went wrong"})
else:
response_data = {"error": 1,"message": "You are not sudo user!"}
return jsonify(response_data)
else:
flash('Please login')
return redirect('/login')
@app.route('/delete_frontend', methods=['POST'])
def delete_frontend():
is_login = session.get('is_login')
if is_login:
if session.get('is_sudo'):
if request.method == "POST":
tn_id = session.get('transaction_id')
received_data = request.get_json()
print(received_data)
frontend_name = received_data['frontend']
url = f'{api_list.url_frontend}/{frontend_name}?transaction_id={tn_id}'
response = requests.delete(url, auth=authentication_cred)
if response.status_code == 202:
print('Transaction deleted successfully.')
return jsonify({"error":0, "message":"Changes Saved frontend deleted","transaction_code": response.status_code})
else:
print(f'Error: {response.status_code}',response.text)
return jsonify({"error": 1 , "message": response.json()['message'], "code":response.json()['code'],"transaction_code": response.status_code})
return jsonify({"error":1, "message":"Something went wrong"})
else:
response_data = {"error": 1,"message": "You are not sudo user!"}
return jsonify(response_data)
else:
flash('Please login')
return redirect('/login')
##----------------------------------------- BACKEND switching rules------------------------------------
@app.route('/backend_switching_rule')
def backend_switching_rule():
## get all frontend # [{"frontend":{}, "acl":{}, "rule":{} },{}]
## get all acl
## get all switching rule
is_login = session.get('is_login')
if is_login:
tn_id = session.get('transaction_id')
# get the backend names in list
url = f'{api_list.url_backend}?transaction_id={tn_id}'
response = requests.get(url, auth=authentication_cred)
backend_names = []
if response.status_code == 200:
resp = response.json()
for i in resp['data']:
backend_name = i['name']
backend_names.append(backend_name)
# get all acl rules
url = f'{api_list.url_frontend}?transaction_id={tn_id}'
response = requests.get(url, auth=authentication_cred)
if response.status_code == 200:
print(str1,response.json())
resp = response.json()
parent_list = []
for i in resp['data']:
frontend_name = i['name']
url = f'{api_list.url_backend_switch_rule}?transaction_id={tn_id}&frontend={frontend_name}'
response1 = requests.get(url, auth=authentication_cred)
if response1.status_code == 200:
print(str1,response1.json())
else:
print(f'Error switch rule: {response1.status_code}',response1.text)
return "Error"
parent_type = 'frontend'
url = f'{api_list.url_acl}?transaction_id={tn_id}&parent_name={frontend_name}&parent_type={parent_type}'
response2 = requests.get(url, auth=authentication_cred)
if response2.status_code == 200:
print(str1,response2.json())
else:
print(f'Error alc: {response2.status_code}',response2.text)
return "Error"
parent_list.append({"frontend":i, "rule":response1.json(),"acl":response2.json()})
return render_template('switching_rule.html', data = json.dumps(parent_list), backend_names = json.dumps(backend_names))
else:
print(f'Error: {response.status_code}')
print(response.text)
flash('Transaction code expired')
return redirect('/login')
else:
flash('Please login')
return redirect('/login')
@app.route('/save_switching_rule', methods=['POST'])
def save_switching_rule():
is_login = session.get('is_login')
if is_login:
if session.get('is_sudo'):
error = 0
error_msg = ''
if request.method == "POST":
tn_id = session.get('transaction_id')
received_data = request.get_json()
print(received_data) #[{ "type":"new", "frontend": "" ,"data" = {} },{}]
for item in received_data:
if item['type'] == "new":
frontend_name = item['frontend']
url = f'{api_list.url_backend_switch_rule}?transaction_id={tn_id}&frontend={frontend_name}'
payload = item['data']
headers = {"Content-Type": "application/json"}