-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathappd-extractor.py
1697 lines (1360 loc) · 73.3 KB
/
appd-extractor.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
import streamlit as st
import pandas as pd
import yaml
import math
import datetime
import os
from io import StringIO
import xml.etree.ElementTree as ET
import requests
import json
import urllib.parse
import time
import sys
import subprocess
import gc
import pygame
#--- CONFIGURATION SECTION ---
snes = False
DEBUG = False
# add this back at some point maybe as use option
normalize = True
metric_rollup = "false"
# Verify SSL certificates - should only be set false for on-prem controllers. Use this if the script fails right off the bat and gives you errors to the point..
VERIFY_SSL = True
# used to keep the status window open if there are errors
keep_status_open = False
#manages token expiration - do not change these values
last_token_fetch_time = ""
token_expiration = 300
expiration_buffer = 30
def load_secrets():
"""Loads API credentials from secrets.yml if it exists."""
try:
with open("secrets.yml", "r") as file:
secrets_data = yaml.safe_load(file)
return secrets_data.get("secrets", []) # Default to empty list if not found
except FileNotFoundError:
return [] # Return an empty list if the file doesn't exist
def save_secrets(secrets_data):
"""Saves API credentials to secrets.yml."""
with open("secrets.yml", "w") as file:
yaml.dump({"secrets": secrets_data}, file, default_flow_style=False)
def authenticate(state):
"""get XCSRF token for use in this session"""
if state == "reauth":
print("Obtaining a freah authentication token.")
if state == "initial":
print("Begin login.")
connect(APPDYNAMICS_ACCOUNT_NAME, APPDYNAMICS_API_CLIENT, APPDYNAMICS_API_CLIENT_SECRET)
return
def is_token_valid():
"""Checks if the access token is valid and not expired."""
if DEBUG:
print(" --- Checking token validity...")
if __session__ is None or not __session__:
if DEBUG:
print(" --- __session__ not found or empty.")
return False
# Conservative buffer (e.g., 30 seconds before expiration)
if DEBUG:
print(f" --- __session__: {__session__}")
return time.time() < (token_expiration + last_token_fetch_time - expiration_buffer)
def connect(account, apiclient, secret):
"""Connects to the AppDynamics API and retrieves an OAuth token."""
global __session__, last_token_fetch_time, token_expiration
__session__ = requests.Session()
url = f"{BASE_URL}/controller/api/oauth/access_token?grant_type=client_credentials&client_id={apiclient}@{account}&client_secret={secret}"
payload = {}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
print(f"Logging into the controller at: {BASE_URL}")
@handle_rest_errors # Apply the error handling decorator
def make_auth_request():
response = __session__.request(
"POST",
url,
headers=headers,
data=payload,
verify=VERIFY_SSL
)
return response
auth_response, status = make_auth_request()
if DEBUG:
print(f"Authentication response:{auth_response} = {status}")
# Assuming auth_response isn't None if no errors occurred
if status == "valid":
if auth_response:
json_response = auth_response.json()
last_token_fetch_time = time.time()
token_expiration = json_response['expires_in']
else:
print(f"Unable to log in at: {BASE_URL}")
print("Please check your controller URL and try again.")
sys.exit(9)
__session__.headers['X-CSRF-TOKEN'] = json_response['access_token']
__session__.headers['Authorization'] = f'Bearer {json_response["access_token"]}'
print("Authenticated with controller.")
if DEBUG:
print(f"Last token fetch time: {last_token_fetch_time}")
print(f"Token expires in: {json_response['expires_in']}")
print(f"Session headers: {__session__.headers}")
return True
def handle_rest_errors(func):
"""for handling REST calls"""
def inner_function(*args, **kwargs):
error_map = {
400: "Bad Request - The request was invalid.",
401: "Unauthorized - Authentication failed.",
403: "Forbidden - You don't have permission to access this resource.",
404: "Not Found - The resource could not be found.",
500: "Internal Server Error - Something went wrong on the server.",
}
try:
response = func(*args, **kwargs)
response.raise_for_status()
return response, "valid"
except requests.exceptions.HTTPError as err:
error_code = err.response.status_code
error_explanation = error_map.get(error_code, "Unknown HTTP Error")
print(f"HTTP Error: {error_code} - {error_explanation}")
return error_explanation, "error"
except requests.exceptions.RequestException as err:
if isinstance(err, requests.exceptions.ConnectionError):
print("Connection Error: Failed to establish a new connection.")
return err, "error"
else:
print(f"Request Exception: {err}")
return err, "error"
except Exception:
error_type, error_value, _ = sys.exc_info()
print(f"Unexpected Error: {error_type.__name__}: {error_value}")
return error_value, "error"
return inner_function
def urlencode_string(text):
"""make app, tier or node names URL compatible for the REST call"""
#if the type is not string, make it one
if not isinstance(text, str):
print(f"converting {text} to a string.")
text = str(text)
encoded_text = urllib.parse.quote(text, safe='/', encoding=None, errors=None)
return encoded_text
@handle_rest_errors
def get_SIM_availability(hierarchy_list, hostId, type):
"""fetches last known server agent availability info. returns requests.Response object"""
if DEBUG:
print(f" --- Begin get_SIM_availability({hierarchy_list}, {hostId})")
#PHYSICAL server URL example
#https://customer1.saas.appdynamics.com/controller/rest/applications/Server%20%26%20Infrastructure%20Monitoring/metric-data?metric-path=Application%20Infrastructure%20Performance%7CRoot%5C%7CAppName%5C%7COwners%5C%7CEnvironment%7CIndividual%20Nodes%7C<hostId>%7CHardware%20Resources%7CMachine%7CAvailability&time-range-type=BEFORE_NOW&duration-in-mins=60
#CONTAINER server URL example - have to use CPU
#https://customer1.saas.appdynamics.com/controller/rest/applications/Server%20%26%20Infrastructure%20Monitoring/metric-data?metric-path=Application%20Infrastructure%20Performance%7CRoot%5C%7CContainers%7CIndividual%20Nodes%7C<hostId>%7CHardware%20Resources%7CCPU%7C%25Busy&time-range-type=BEFORE_NOW&duration-in-mins=60
#convert the hierarchy from the machine agent data into a URL encoded string
hierarchy = "%5C%7C".join(hierarchy_list)
#build the metric url using the hierarchy, hostId and metric duration
if type == "PHYSICAL": #use availability metric
metric_url = BASE_URL + "/controller/rest/applications/Server%20%26%20Infrastructure%20Monitoring/metric-data?metric-path=Application%20Infrastructure%20Performance%7CRoot%5C%7C" + hierarchy + "%7CIndividual%20Nodes%7C" + hostId + "%7CHardware%20Resources%7CMachine%7CAvailability&time-range-type=BEFORE_NOW&duration-in-mins=" + str(machine_metric_duration_mins) + "&output=json"
elif type == "CONTAINER": #use CPU busy since availability metric doesn't exist
metric_url = BASE_URL + "/controller/rest/applications/Server%20%26%20Infrastructure%20Monitoring/metric-data?metric-path=Application%20Infrastructure%20Performance%7CRoot%5C%7C" + hierarchy + "%7CIndividual%20Nodes%7C" + hostId + "%7CHardware%20Resources%7CCPU%7C%25Busy&time-range-type=BEFORE_NOW&duration-in-mins=" + str(machine_metric_duration_mins) + "&output=json"
if DEBUG:
print(f" --- SIM availability metric url: {metric_url}")
metric_response = requests.get(
metric_url,
headers = __session__.headers,
verify = VERIFY_SSL
)
return metric_response
@handle_rest_errors
def get_apm_availability(object_type, app, tier, agenttype, node):
"""fetches last known agent availability info from tier or node level. returns requests.Response object"""
if DEBUG:
print(f" --- Begin get_apm_availability({object_type},{app},{tier},{agenttype},{node})")
tier = urlencode_string(tier)
app = urlencode_string(app)
node = urlencode_string(node)
if object_type == "node":
print(" --- Querying node availability.")
if agenttype == "MACHINE_AGENT":
metric_path = "Application%20Infrastructure%20Performance%7C" + tier + "%7CIndividual%20Nodes%7C" + node + "%7CAgent%7CMachine%7CAvailability"
else:
metric_path = "Application%20Infrastructure%20Performance%7C" + tier + "%7CIndividual%20Nodes%7C" + node + "%7CAgent%7CApp%7CAvailability"
elif object_type == "tier":
print(" --- Querying tier availability.")
if agenttype == "MACHINE_AGENT":
metric_path = "Application%20Infrastructure%20Performance%7C" + tier + "%7CAgent%7CMachine%7CAvailability"
else:
metric_path = "Application%20Infrastructure%20Performance%7C" + tier + "%7CAgent%7CApp%7CAvailability"
metric_url = BASE_URL + "/controller/rest/applications/" + app + "/metric-data?metric-path=" + metric_path + "&time-range-type=BEFORE_NOW&duration-in-mins=" + str(apm_metric_duration_mins) + "&rollup=" + metric_rollup + "&output=json"
#get metric data
if DEBUG:
print(" --- metric url: " + metric_url)
metric_response = requests.get(
metric_url,
headers = __session__.headers,
verify = VERIFY_SSL
)
return metric_response
def return_apm_availability(metric_response):
'''validate the returned APM availability response, extracts the metric data and returns the last seen time and count'''
data, status = validate_json(metric_response)
if status != "valid":
if DEBUG:
print(f" --- Validation of APM availability data failed. Status: {status} Data: {data}")
return "", ""
if status == "valid":
# Check if any dictionary in the list has 'metricName' equal to 'METRIC DATA NOT FOUND' and jump out early if so
condition = any(d['metricName'] == 'METRIC DATA NOT FOUND' for d in data)
if condition:
print(" --- Metric data not found!")
return "", ""
try:
epoch, value = determine_availability(data, status)
return epoch, value
except Exception as e:
st.write(f"Unexpected error during validation: of APM availability data: {e}")
print(f" --- Unexpected error during validation: of APM availability data: {e}")
print(f" --- status: {status} data: {data}")
return "", ""
def validate_json(response):
"""validation function to parse into JSON and catch empty sets returned from our API requests"""
if not response:
if DEBUG:
print(" ---- No response was passed for validation.")
return None, "empty"
try:
if DEBUG:
if isinstance(response, requests.Response):
if response.headers.get('content-type') == 'application/json':
print(f" --- validate_json() - incoming response type:: {type(response)}, length: {len(response.json())}")
else:
print(f" --- validate_json() - incoming response type:: {type(response)}, length: {len(response.content)}")
else:
print(f" --- validate_json() - incoming response type:: {type(response)}, length: {len(response)}")
if isinstance(response, tuple):
#unpack response
data, data_status = response
#handle error and exceptions from the response
if data_status != "valid":
if DEBUG:
st.write(f"Response validation error! status = {data_status}, data = {data}")
print(f" --- response data is not valid. status = {data_status}, data = {data}")
return None, data_status
else:
if DEBUG:
print(f" --- response data is valid. status = {data_status}")
#convert response data to JSON
data = data.json()
elif isinstance(response, requests.Response):
data = response.json()
data_status = "valid"
elif isinstance(response, dict):
# Handle dictionaries directly
data = response
data_status = "valid"
# check for empty JSON object
if not data or data == [] or data == "":
if DEBUG:
print(f" --- The resulting JSON object is empty. data = {data}")
return None, "empty"
#if the data made it this far, then...
return data, data_status
except json.JSONDecodeError:
# The data is not valid JSON.
if DEBUG:
print(" --- The data is not valid JSON.")
print(response.text)
return None, "error"
def validate_and_parse_xml(response, xpath):
"""
Validates an XML response and converts it to a pandas DataFrame.
Args:
response: The requests.Response object containing the XML data.
xpath: The XPath expression to locate the parent of the repeating elements.
Returns:
A tuple containing:
- pandas.DataFrame: The DataFrame if successful, or an empty DataFrame if no data is found.
- str: Status string ("valid", "empty", or "error").
"""
try:
if not response.content.decode().strip(): # Check for empty XML (after decoding)
return pd.DataFrame(), "empty"
xml_content = StringIO(response.content.decode())
# Use pd.read_xml directly with the provided xpath
df = pd.read_xml(xml_content, xpath=xpath)
if df.empty:
return df, "empty"
else:
return df, "valid"
except Exception as e:
error_type, error_value, _ = sys.exc_info()
print(f"An exception occurred converting XML to DataFrame: {error_type.__name__}: {error_value}")
return pd.DataFrame(), "error" # Return an empty DataFrame on error
def determine_availability(metric_data, metric_data_status):
"""Processes returned metric JSON data"""
if DEBUG:
print(" --- handle_metric_response() - Handling metric data...")
print(f" --- handle_metric_response() - metric_data: {metric_data}")
print(f" --- handle_metric_response() - metric_data type: {type(metric_data)}")
print(f" --- handle_metric_response() - metric_data_status: {metric_data_status}")
if metric_data[-1]['metricName'] == "METRIC DATA NOT FOUND":
if DEBUG:
print("METRIC DATA NOT FOUND IN TIME RANGE")
return None, None
if metric_data[-1]['metricValues'][-1]['startTimeInMillis']:
last_start_time_millis = metric_data[-1]['metricValues'][-1]['startTimeInMillis']
value = metric_data[-1]['metricValues'][-1]['current']
if DEBUG:
print(f" --- startTimeInMillis: {last_start_time_millis} current: {value}")
return last_start_time_millis, value
elif metric_data == []:
if DEBUG:
print("METRIC DATA CAME BACK WITH EMPTY DICTIONARY")
return None, None
else:
return None, None
@handle_rest_errors
def get_applications():
"""Get a list of all applications"""
print("--- Fetching applications...")
if not is_token_valid():
authenticate("reauth")
if application_id:
#chosen when user supplied an app id in the config
applications_url = BASE_URL + "/controller/rest/applications/" + str(application_id) + "?output=json"
if DEBUG:
print(" --- from "+applications_url)
else:
applications_url = BASE_URL + "/controller/rest/applications?output=json"
if DEBUG:
print("--- from "+applications_url)
applications_response = requests.get(
applications_url,
headers = __session__.headers,
verify = VERIFY_SSL
)
return applications_response
def refresh_applications():
global APPDYNAMICS_ACCOUNT_NAME, APPDYNAMICS_API_CLIENT, APPDYNAMICS_API_CLIENT_SECRET, BASE_URL, application_id
APPDYNAMICS_ACCOUNT_NAME = account_name
APPDYNAMICS_API_CLIENT = api_client
APPDYNAMICS_API_CLIENT_SECRET = api_key
BASE_URL = "https://"+APPDYNAMICS_ACCOUNT_NAME+".saas.appdynamics.com"
application_id = None
authenticate("initial")
with st.spinner('Retrieving applications...'):
applications_response = get_applications()
applications, applications_status = validate_json(applications_response)
if applications_status == "valid":
applications_df = pd.DataFrame(applications)
applications_df = applications_df.rename(columns={
"id": "app_id",
"name": "app_name"
})
st.session_state['applications_df'] = applications_df # Store in session state
if DEBUG:
debug_df(applications_df, "applications_df")
st.rerun()
@handle_rest_errors
def get_tiers(application_id):
"""Gets the tiers in the application"""
tiers_url = BASE_URL + "/controller/rest/applications/" + str(application_id) + "/tiers?output=json"
if DEBUG:
print(" --- Fetching tiers from: "+ tiers_url)
else:
print(" --- Fetching tiers...")
if not is_token_valid():
authenticate("reauth")
tiers_response = requests.get(
tiers_url,
headers = __session__.headers,
verify = VERIFY_SSL
)
#if DEBUG:
# print(f" --- get_tiers response: {tiers_response.text}")
return tiers_response
@handle_rest_errors
def get_app_nodes(application_id):
"""Gets all nodes in an app"""
nodes_url = BASE_URL + "/controller/rest/applications/" + str(application_id) + "/nodes?output=json"
if DEBUG:
print(f" --- Fetching node data from {nodes_url}.")
else:
print(" --- Fetching nodes from app.")
if not is_token_valid():
authenticate("reauth")
nodes_response = requests.get(
nodes_url,
headers = __session__.headers,
verify = VERIFY_SSL
)
#if DEBUG:
# print(f" --- get_app_nodes response: {nodes_response.text}")
return nodes_response
@handle_rest_errors
def get_tier_nodes(application_id, tier_id):
"""Gets the nodes in a tier"""
nodes_url = BASE_URL + "/controller/rest/applications/" + str(application_id) + "/tiers/" + str(tier_id) + "/nodes?output=json"
if DEBUG:
print(f" --- Fetching node data from {nodes_url}.")
else:
print(" --- Fetching nodes from tier.")
if not is_token_valid():
authenticate("reauth")
nodes_response = requests.get(
nodes_url,
headers = __session__.headers,
verify = VERIFY_SSL
)
#if DEBUG:
# print(f" --- get_tier_nodes response: {nodes_response.text}")
return nodes_response
@handle_rest_errors
def get_app_backends(application_id):
"""Gets the backends in an app"""
backends_url = BASE_URL + "/controller/rest/applications/" + str(application_id) + "/backends?output=json"
if DEBUG:
print(f" --- Fetching backend data from {backends_url}.")
else:
print(f" --- Fetching backends from application: {application_id}.")
if not is_token_valid():
authenticate("reauth")
backends_response = requests.get(
backends_url,
headers = __session__.headers,
verify = VERIFY_SSL
)
#if DEBUG:
# print(f" --- get_backends response: {backends_response.text}")
return backends_response
@handle_rest_errors
def get_snapshots(application_id):
"""Gets snapshot data from an application"""
snapshots_url = BASE_URL + "/controller/rest/applications/" + str(application_id) + \
"/request-snapshots?time-range-type=BEFORE_NOW&duration-in-mins=" + str(snapshot_duration_mins) + \
"&first-in-chain=" + str(first_in_chain) + "&need-exit-calls=" + str(need_exit_calls) + \
"&need-props=" + str(need_props) + "&maximum-results=1000000"
if DEBUG:
print(" --- Fetching snapshots from: "+ snapshots_url)
else:
print(" --- Fetching snapshots...")
if not is_token_valid():
authenticate("reauth")
snapshots_response = requests.get(
snapshots_url,
headers = __session__.headers,
verify = VERIFY_SSL
)
#if DEBUG:
# print(f" --- get_snapshots response: {snapshots_response.text}")
return snapshots_response
@handle_rest_errors
def get_bts(application_id):
'''retrieves business transactions list from the application'''
bts_url = BASE_URL + "/controller/rest/applications/" + str(application_id) + "/business-transactions"
if DEBUG:
print(" --- Fetching bts from: "+ bts_url)
else:
print(" --- Fetching bts...")
if not is_token_valid():
authenticate("reauth")
bts_response = requests.get(
bts_url,
headers = __session__.headers,
verify = VERIFY_SSL
)
if DEBUG:
print(f" --- get_bts response: {bts_response.text}")
return bts_response
@handle_rest_errors
def get_healthRules(application_id):
'''retrieves health rules from application(s)'''
healthRules_url = BASE_URL + "/controller/alerting/rest/v1/applications/" + str(application_id) + "/health-rules"
if DEBUG:
print(f" --- Fetching health rules from: {healthRules_url}")
else:
print(" --- Fetching health rules...")
if not is_token_valid():
authenticate("reauth")
healthRules_response = requests.get(
healthRules_url,
headers = __session__.headers,
verify = VERIFY_SSL
)
#if DEBUG:
# print(f" --- get_healthRules response: {healthRules_response.text}")
return healthRules_response
@handle_rest_errors
def get_servers():
'''Get a list of all servers'''
servers_url = BASE_URL + "/controller/sim/v2/user/machines"
if DEBUG:
print(f"--- Retrieving Servers from {servers_url}")
else:
print(" --- Retrieving Servers...")
if not is_token_valid():
authenticate("reauth")
servers_response = requests.get(
servers_url,
headers = __session__.headers,
verify = VERIFY_SSL
)
return servers_response
def calculate_licenses(df):
license_data = []
for agent_type in ['APP_AGENT', 'DOT_NET_APP_AGENT', 'NODEJS_APP_AGENT', 'PYTHON_APP_AGENT',
'PHP_APP_AGENT', 'GOLANG_SDK', 'WMB_AGENT', 'MACHINE_AGENT', 'DOT_NET_MACHINE_AGENT',
'NATIVE_WEB_SERVER', 'NATIVE_SDK']:
if agent_type == 'NATIVE_SDK':
agent_df = df[df['Node - Agent Type'] == agent_type]
sap_abap_df = agent_df[agent_df['App Agent Version'].str.contains('with HTTP SDK', na=False)]
cpp_df = agent_df[~agent_df['App Agent Version'].str.contains('with HTTP SDK', na=False)]
sap_abap_licenses = sap_abap_df['hostId'].nunique()
cpp_licenses = cpp_df['hostId'].nunique() // 3
if cpp_df['hostId'].nunique() % 3 > 0:
cpp_licenses += 1
license_data.append({'Agent Type': 'SAP ABAP Agent', 'Licenses Required': sap_abap_licenses})
license_data.append({'Agent Type': 'C++ Agent', 'Licenses Required': cpp_licenses})
else:
agent_df = df[df['Node - Agent Type'] == agent_type]
container_df = agent_df[agent_df['Server Type'] == 'CONTAINER']
physical_df = agent_df[agent_df['Server Type'] == 'PHYSICAL']
if agent_type in ['DOT_NET_APP_AGENT', 'PYTHON_APP_AGENT', 'WMB_AGENT', 'NATIVE_SDK',
'MACHINE_AGENT', 'DOT_NET_MACHINE_AGENT', 'NATIVE_WEB_SERVER']:
container_licenses = container_df['hostId'].nunique()
physical_licenses = physical_df['hostId'].nunique()
elif agent_type in ['APP_AGENT', 'PHP_APP_AGENT']:
container_licenses = container_df['Node Name'].nunique()
physical_licenses = physical_df['Node Name'].nunique()
elif agent_type == 'NODEJS_APP_AGENT':
container_licenses = 0
physical_licenses = 0
for host_id in agent_df['hostId'].unique():
host_df = agent_df[agent_df['hostId'] == host_id]
container_host_df = host_df[host_df['Server Type'] == 'CONTAINER']
physical_host_df = host_df[host_df['Server Type'] == 'PHYSICAL']
container_licenses += (container_host_df['Node Name'].nunique() // 10)
if container_host_df['Node Name'].nunique() % 10 > 0:
container_licenses += 1
physical_licenses += (physical_host_df['Node Name'].nunique() // 10)
if physical_host_df['Node Name'].nunique() % 10 > 0:
physical_licenses += 1
elif agent_type == 'GOLANG_SDK':
container_licenses = (container_df['Node Name'].nunique() // 3)
if container_df['Node Name'].nunique() % 3 > 0:
container_licenses += 1
physical_licenses = (physical_df['Node Name'].nunique() // 3)
if physical_df['Node Name'].nunique() % 3 > 0:
physical_licenses += 1
microservices_licenses = math.ceil(container_licenses / 5)
standard_licenses = physical_licenses
#use the names everyone knows
if agent_type != "NATIVE_SDK":
if agent_type == 'APP_AGENT':
agent_type = 'Java Agent'
if agent_type == 'DOT_NET_APP_AGENT':
agent_type = '.NET Agent'
if agent_type == 'NODEJS_APP_AGENT':
agent_type = 'NodeJS Agent'
if agent_type == 'PYTHON_APP_AGENT':
agent_type = 'Python Agent'
if agent_type == 'PHP_APP_AGENT':
agent_type = "PHP Agent"
if agent_type == 'GOLANG_SDK':
agent_type = 'Go Agent'
if agent_type == 'WMB_AGENT':
agent_type = 'IIB Agent'
if agent_type == 'MACHINE_AGENT':
agent_type = 'Machine Agent'
if agent_type == 'DOT_NET_MACHINE_AGENT':
agent_type = '.NET Machine Agent'
if agent_type == 'NATIVE_WEB_SERVER':
agent_type = 'Apache Agent'
license_data.append({
'Agent Type': agent_type,
'Container Nodes': container_df.shape[0],
'Physical Nodes': physical_df.shape[0],
'Physical Licenses (Mixed)': physical_licenses,
'Microservices Licenses (Mixed)': microservices_licenses,
'Standard Licenses': standard_licenses
})
license_usage_df = pd.DataFrame(license_data)
return license_usage_df
def debug_df(df, df_name, num_lines=10):
"""Displays DataFrame information in a more readable way."""
if snes:
play_sound("sounds/smb_coin.wav")
st.subheader(f"Debug Info: {df_name}") # Use subheader instead of nested expander
st.write(f"Shape (rows, cols): {df.shape}")
#st.write(f"Columns: {df.columns.to_list()}")
st.write(f"First {num_lines} rows:")
st.write(df.head(num_lines).to_markdown(index=False, numalign='left', stralign='left'))
def play_sound(file_path):
'''file = realtive path and filename to wave file, wait (Boolean) wait for the file to finish playing or not'''
try:
pygame.mixer.init()
sound = pygame.mixer.Sound(file_path)
sound.play()
except Exception as e:
print(f"Error playing sound: {e}")
# --- MAIN (Streamlit UI) ---
st.title("AppDynamics Data Extractor")
st.markdown('<h2 text-align: center>not DEXTER</h2>', unsafe_allow_html=True)
# --- Load secrets and set initial values ---
secrets = load_secrets()
selected_account = ""
api_client_name = ""
api_key = ""
#load up accounts and creds if they exist
if secrets:
selected_account = secrets[0].get("account", "")
api_client_name = secrets[0].get("api-client-name", "")
api_key = secrets[0].get("api-key", "")
account_options = [secret["account"] for secret in secrets] + ["Enter Manually"]
selected_account = st.selectbox("Account Name", options=account_options, index=account_options.index(selected_account) if selected_account in account_options else 0)
# Input/select behavior
if selected_account == "Enter Manually":
account_name = st.text_input("Account Name", value="")
else:
account_name = selected_account # Use the selected value directly
# Populate fields dynamically based on account name
api_client_name = "" # Reset to empty
api_key = ""
for secret in secrets:
if secret["account"] == account_name:
api_client_name = secret.get("api-client-name", "")
api_key = secret.get("api-key", "")
break
connect_button = st.button("Connect")
#conditional multiselect populator
if 'applications_df' in st.session_state:
applications_df = st.session_state['applications_df']
# Create a list of tuples (app_id, app_name)
app_names = [(row['app_id'], row['app_name']) for _, row in applications_df.iterrows()]
# Insert "ALL APPS" at the beginning
app_names.insert(0, ("ALL", "ALL APPS"))
# Extract only the app_name for display in the multi-select
display_names = [name for _, name in app_names]
# Create the multi-select list
selected_apps = st.multiselect("Select applications:", display_names)
# Get the selected app_ids (including "ALL APPS" if selected)
selected_app_ids = [app_id for app_id, name in app_names if name in selected_apps]
if selected_app_ids:
application_id = ""
#st.write("You selected app_ids:", selected_app_ids)
"***Note: license usage analysis (BETA) requires APM and server data***"
retrieve_apm = st.checkbox("Retrieve APM (App, tiers, nodes, etc)?", value=True)
retrieve_servers = st.checkbox("Retrieve all machine agent data?", value=True)
if retrieve_apm:
pull_snapshots = st.checkbox("Retrieve transaction snapshots?", value=False)
else:
pull_snapshots = False
# --- User config form ---
with st.form("config_form"):
if not secrets:
account_name = st.text_input("Account Name", value="")
api_client = st.text_input("API client name", value=api_client_name)
api_key = st.text_input("API client secret", type="password", value=api_key)
# Save button
save_button = st.form_submit_button("Save Credentials")
if 'applications_df' not in st.session_state:
application_id = st.text_input("Application ID (optional)", value="")
if retrieve_apm:
"### APM options"
calc_apm_availability = st.checkbox("Analyze tier and node availability?", value=True)
apm_metric_duration_mins = st.text_input("How far to look back for APM availability? (mins)", value="60")
#add this back at some point maybe
#metric_rollup = st.checkbox("Rollup metrics?", value=False)
if pull_snapshots:
"### Snapshot options"
snapshot_duration_mins = st.text_input("How far to look back for snapshots? (mins)", value=60)
first_in_chain = st.checkbox("Capture only first in chain snapshots?", value=True)
need_exit_calls = st.checkbox("Return exit call data with snapshots?", value=False)
need_props = st.checkbox("Return data collector data with snapshots?", value=False)
if retrieve_servers:
"### Servers"
calc_machine_availability = st.checkbox("Analyze server availability?", value=True)
machine_metric_duration_mins = st.text_input("How far to look back for machine availability? (mins)", value="60")
#normalize = st.checkbox("Break out server properties into columns?", value=False)
#normalize = True
# Submit button
submitted = st.form_submit_button("Extract Data")
debug_output = st.checkbox("Debug output?", value=False)
if debug_output:
snes = st.checkbox("8-bit my debug!", value=False)
if connect_button:
global APPDYNAMICS_ACCOUNT_NAME, APPDYNAMICS_API_CLIENT, APPDYNAMICS_API_CLIENT_SECRET
# Update global variables with user input
APPDYNAMICS_ACCOUNT_NAME = account_name
APPDYNAMICS_API_CLIENT = api_client
APPDYNAMICS_API_CLIENT_SECRET = api_key
application_id = ""
st.write("Connecting to retrieve applications list...")
print("Connecting to retrieve applications list...")
refresh_applications()
if save_button:
# Update secrets.yml with user input
new_secrets = []
for secret in secrets:
if secret["account"] == account_name:
secret["api-client-name"] = api_client
secret["api_key"] = api_key
new_secrets.append(secret)
if account_name not in account_options: # Add only if it's a new account
new_secrets.append({
"account": account_name,
"api-client-name": api_client,
"api-key": api_key
})
save_secrets(new_secrets)
st.success("Credentials saved!")
# --- Main application code ---
if submitted and (retrieve_apm or retrieve_servers):
if snes:
play_sound("sounds/smb_jump-small.wav")
# Update global variables with user input
APPDYNAMICS_ACCOUNT_NAME = account_name
APPDYNAMICS_API_CLIENT = api_client
APPDYNAMICS_API_CLIENT_SECRET = api_key
if retrieve_apm:
if not selected_app_ids:
if not application_id:
application_id = ""
else:
application_id = ""
if not selected_app_ids and application_id == "" and not retrieve_servers:
st.write("You must select an application or an application_id to continue.")
st.rerun()
if not calc_apm_availability:
apm_metric_duration_mins = 0
if pull_snapshots:
if int(snapshot_duration_mins) >= 20160:
st.write("Changed snapshot duration to 20159 (two week limit)")
snapshot_duration_mins = 20159
else:
snapshot_duration_mins = 0
if not retrieve_servers:
machine_metric_duration_mins = 0
DEBUG = debug_output
# Replace with the desired output file path and name or leave as it to create dynamically (recommended)
OUTPUT_EXCEL_FILE = APPDYNAMICS_ACCOUNT_NAME+"_analysis_"+datetime.date.today().strftime("%m-%d-%Y")+".xlsx"
# Set the base URL for the AppDynamics REST API
# --- replace this with your on-prem controller URL if you're on prem
BASE_URL = "https://"+APPDYNAMICS_ACCOUNT_NAME+".saas.appdynamics.com"
# --- MAIN application code
with st.status("Extracting data...", expanded=True) as status:
st.write(f"Logging into controller at {BASE_URL}...")
authenticate("initial")
# Initialize empty DataFrame
information_df = pd.DataFrame()
license_usage_df = pd.DataFrame()
applications_df = pd.DataFrame()
bts_df = pd.DataFrame()
tiers_df = pd.DataFrame()
nodes_df = pd.DataFrame()
backends_df = pd.DataFrame()
healthRules_df = pd.DataFrame()
snapshots_df = pd.DataFrame()
#initialize aggregate dataframes
all_bts_df = pd.DataFrame()
all_tiers_df = pd.DataFrame()
all_nodes_df = pd.DataFrame()
all_nodes_merged_df = pd.DataFrame()
all_backends_df = pd.DataFrame()
all_healthRules_df = pd.DataFrame()
all_snapshots_df = pd.DataFrame()
all_snapshots_merged_df = pd.DataFrame()
all_servers_df = pd.DataFrame()
all_servers_merged_df = pd.DataFrame()
all_apm_merged_df = pd.DataFrame()
if retrieve_apm:
# Get applications for processing
st.write("Retrieving applications...")
applications_response = get_applications()
applications, applications_status = validate_json(applications_response)
if applications_status == "valid":
applications_df = pd.DataFrame(applications)
applications_df = applications_df.rename(columns={
"id": "app_id",
"name": "app_name"
})
if selected_app_ids:
# Filter the DataFrame based on selected_app_ids
if "ALL" in selected_app_ids:
applications_df = applications_df # Keep all rows
else:
applications_df = applications_df[applications_df['app_id'].isin(selected_app_ids)]
if DEBUG:
debug_df(applications_df, "applications_df")
st.write(f"Found {applications_df.shape[0]} applications.")
if snes:
play_sound("sounds/smb_coin.wav")
#get current date and time and build info sheet - shoutout to Peter Wivagg for the suggestion
now = datetime.datetime.now()
current_date_time = now.strftime("%Y-%m-%d %H:%M:%S")
information_df = pd.DataFrame({
"setting": ["RUN_DATE","BASE_URL", "APPDYNAMICS_ACCOUNT_NAME", "APPDYNAMICS_API_CLIENT", "Selected Apps", "or application id", "APM availability (mins)", "Machine availability (mins)", "metric_rollup", "Retrieve snapshots", "Snapshot range (mins)"],
"value": [current_date_time, BASE_URL, APPDYNAMICS_ACCOUNT_NAME, APPDYNAMICS_API_CLIENT, selected_apps, application_id, apm_metric_duration_mins, machine_metric_duration_mins, metric_rollup, pull_snapshots, snapshot_duration_mins]
})
# Process each application
st.write(f"Processing applications...")
for _, application in applications_df.iterrows():
app_id = application["app_id"]
app_name = application["app_name"]
# Get and process business transactions
st.write(f"Retrieving business transactions for {app_name}...")
bts_response, bts_status = get_bts(app_id)
bts_data, bts_status = validate_and_parse_xml(bts_response, xpath=".//business-transaction")
if bts_status == "valid":
if snes:
play_sound("sounds/smb_coin.wav")
bts_df['app_id'] = app_id