-
Notifications
You must be signed in to change notification settings - Fork 0
/
argocd_sync.py
177 lines (147 loc) · 6 KB
/
argocd_sync.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
from gql import Client, gql
from gql.transport.requests import RequestsHTTPTransport
import os
import time # for the sleep function
# From arguments
RUNTIME = os.getenv('RUNTIME')
APPLICATION = os.getenv('APPLICATION')
SYNC_REVISION = os.getenv('SYNC_REVISION', '')
SYNC_OPT_PRUNE = (os.getenv('SYNC_OPT_PRUNE', 'false').lower() == 'true')
SYNC_OPT_FORCE = (os.getenv('SYNC_OPT_FORCE', 'false').lower() == 'true')
SYNC_OPT_PRUNE_LAST = (os.getenv('SYNC_OPT_PRUNE_LAST', 'false').lower())
SYNC_OPT_APPLY_OUT_OF_SYNC_ONLY = (os.getenv('SYNC_OPT_APPLY_OUT_OF_SYNC_ONLY', 'false').lower())
SYNC_OPT_SERVER_SIDE_APPLY = (os.getenv('SYNC_OPT_SERVER_SIDE_APPLY', 'true').lower())
# From execution context
CF_URL = os.getenv('CF_URL', 'https://g.codefresh.io')
CF_API_KEY = os.getenv('CF_API_KEY')
CF_STEP_NAME = os.getenv('CF_STEP_NAME', 'STEP_NAME')
###############################################################################
def main():
ingress_host = get_runtime_ingress_host()
terminate_current_app_operation(ingress_host)
execute_argocd_sync(ingress_host)
# Generating link to the Apps Dashboard
CF_OUTPUT_URL_VAR = CF_STEP_NAME + '_CF_OUTPUT_URL'
link_to_app = get_link_to_apps_dashboard()
export_variable(CF_OUTPUT_URL_VAR, link_to_app)
###############################################################################
def get_query(query_name):
# To do: get query content from a variable, failback to a file
with open('queries/'+query_name+'.graphql', 'r') as file:
query_content = file.read()
return gql(query_content)
def get_runtime():
transport = RequestsHTTPTransport(
url=CF_URL + '/2.0/api/graphql',
headers={'authorization': CF_API_KEY},
verify=True,
retries=3,
)
client = Client(transport=transport, fetch_schema_from_transport=False)
query = get_query('getRuntime') # gets gql query
variables = {
"runtime": RUNTIME
}
runtime = client.execute(query, variable_values=variables)
return runtime
def get_runtime_ingress_host():
ingress_host = None
runtime = get_runtime()
ingress_host = runtime['runtime']['ingressHost']
return ingress_host
def get_link_to_apps_dashboard():
runtime = get_runtime()
runtime_ns = runtime['runtime']['metadata']['namespace']
url_to_app = CF_URL+'/2.0/applications-dashboard/' + \
runtime_ns+'/'+RUNTIME+'/'+APPLICATION+'/timeline'
return url_to_app
def terminate_query(ingress_host):
'''
Executes the GraphQL query to terminate the current operation based on the
app in the Global Variables and the provided Ingress Host
'''
runtime_api_endpoint = ingress_host + '/app-proxy/api/graphql'
transport = RequestsHTTPTransport(
url=runtime_api_endpoint,
headers={'authorization': CF_API_KEY},
verify=True,
retries=3,
)
client = Client(transport=transport, fetch_schema_from_transport=False)
query = get_query('terminate') # gets gql query
variables = {
"appName": APPLICATION
}
print("Terminating current operation in app: ", variables)
result = client.execute(query, variable_values=variables)
print(result)
def terminate_current_app_operation(ingress_host):
needsToTerminate=True
try:
terminate_query(ingress_host)
print('Terminating current operation in app, ',
'so the current sync action could be performed. Waiting 30 seconds.')
except Exception as e:
# if the error message is because there's NO operatation to termiante
if str(e).find("Reason: Bad Request") > 0:
print(f'Error: {e}')
raise Exception(
f'Error trying to terminate the current operation of the app')
else:
needsToTerminate=False
print("The app doesn't have any current operation. ",
"No need to terminate operations. Continuing...")
if needsToTerminate is True:
print("Waiting for the current operation in the app to be successfully terminated.")
time.sleep(30)
def execute_argocd_sync(ingress_host):
runtime_api_endpoint = ingress_host + '/app-proxy/api/graphql'
transport = RequestsHTTPTransport(
url=runtime_api_endpoint,
headers={'authorization': CF_API_KEY},
verify=True,
retries=3,
)
client = Client(transport=transport, fetch_schema_from_transport=False)
query = get_query('argocd_sync') # gets gql query
variables = {
"applicationName": APPLICATION,
"options": {
"name": APPLICATION,
"dryRun": False,
"prune": SYNC_OPT_PRUNE,
"strategy": {
"hook": {
"force": SYNC_OPT_FORCE
}
},
"syncOptions": {
"items": [
"PruneLast="+SYNC_OPT_PRUNE_LAST,
"ApplyOutOfSyncOnly="+SYNC_OPT_APPLY_OUT_OF_SYNC_ONLY,
"ServerSideApply="+SYNC_OPT_SERVER_SIDE_APPLY,
"PrunePropagationPolicy=foreground"
]
},
"resources": None
}
}
if SYNC_REVISION != '':
variables['options']['revision'] = SYNC_REVISION
print("Syncing app:\n", variables)
result = client.execute(query, variable_values=variables)
print("Result:\n", result)
def export_variable(var_name, var_value):
# if this script is executed in CF build
if os.getenv('CF_BUILD_ID') != None:
# exporting var when used as a freestyle step
path = str(os.getenv('CF_VOLUME_PATH'))
with open(path+'/env_vars_to_export', 'a') as a_writer:
a_writer.write(var_name + "=" + var_value+'\n')
# exporting var when used as a plugin
with open('/meta/env_vars_to_export', 'a') as a_writer:
a_writer.write(var_name + "=" + var_value+'\n')
print("Exporting variable: "+var_name+"="+var_value)
###############################################################################
if __name__ == "__main__":
main()