Skip to content

Commit f4d28c6

Browse files
authored
1.2.4 (#655)
v1.2.4: - Change logging mechanism - Added LOG_LEVEL parameter - Always return CR_NUMBER and CR_SYSID --------- Signed-off-by: Laurent Rochette <laurent.rochette@codefresh.io>
1 parent 7b0b7a6 commit f4d28c6

File tree

3 files changed

+81
-70
lines changed

3 files changed

+81
-70
lines changed

incubating/service-now/CHANGELOG.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,13 @@
11
# Changelog
2+
3+
## [1.2.4] - 2023-09-21
4+
### Changed
5+
- Change logging mechanism
6+
- Added LOG_LEVEL parameter
7+
8+
### Fixed
9+
- Always return CR_NUMBER and CR_SYSID
10+
211
## [1.2.3] - 2023-09-20
312
### Changed
413

incubating/service-now/lib/snow.py

Lines changed: 64 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -2,46 +2,44 @@
22
import sys
33
import json
44
import requests
5+
import logging
56

67
API_NAMESPACE=409723
78
env_file_path = "/meta/env_vars_to_export"
89

910
def getBaseUrl(instance):
1011
baseUrl = "%s/api" %(instance);
11-
if DEBUG:
12-
print("baseUrl: " + baseUrl)
12+
logging.debug("baseUrl: " + baseUrl)
1313
return baseUrl
1414

1515
def processCallbackResponse(response):
16-
print("Processing answer from CR creation REST call")
17-
print("Callback returned code %s" % (response.status_code))
16+
logging.info("Processing answer from CR creation REST call")
17+
logging.debug("Callback returned code %s" % (response.status_code))
1818
if (response.status_code != 200 and response.status_code != 201):
19-
print("Callback creation failed with code %s" % (response.status_code))
20-
print("Error: " + response.text)
19+
logging.error("Callback creation failed with code %s" % (response.status_code))
20+
logging.error("Error: " + response.text)
2121
sys.exit(response.status_code)
2222

23-
print("Callback creation successful")
23+
logging.info("Callback creation successful")
2424

2525

2626
def processCreateChangeRequestResponse(response):
27-
if DEBUG:
28-
print("Processing answer from CR creation REST call")
29-
print(" Change Request returned code %s" % (response.status_code))
27+
logging.debug("Processing answer from CR creation REST call")
28+
logging.debug(" Change Request returned code %s" % (response.status_code))
3029
if (response.status_code != 200 and response.status_code != 201):
31-
print(" Change Request creation failed with code %s" % (response.status_code))
32-
print(" ERROR: " + response.text)
30+
logging.error(" Change Request creation failed with code %s" % (response.status_code))
31+
logging.error(" ERROR: " + response.text)
3332
sys.exit(response.status_code)
3433

35-
print(" Change Request creation successful")
34+
logging.info(" Change Request creation successful")
3635
data=response.json() # json.loads(response.text)
3736
CR_NUMBER=data["result"]["number"]
3837
CR_SYSID=data["result"]["sys_id"]
3938
FULL_JSON=json.dumps(data, indent=2)
4039

41-
print(f" Change Request Number: {CR_NUMBER}")
42-
print(f" Change Request sys_id: {CR_SYSID}")
43-
if DEBUG:
44-
print( " Change Request full answer:\n" + FULL_JSON)
40+
logging.info(f" Change Request Number: {CR_NUMBER}")
41+
logging.info(f" Change Request sys_id: {CR_SYSID}")
42+
logging.debug( " Change Request full answer:\n" + FULL_JSON)
4543

4644
if os.path.exists(env_file_path):
4745
env_file = open(env_file_path, "a")
@@ -59,26 +57,22 @@ def processCreateChangeRequestResponse(response):
5957
# Fields required are pasted in the data
6058
def createChangeRequest(user, password, baseUrl, data):
6159

62-
if DEBUG:
63-
print("Entering createChangeRequest:")
60+
logging.debug("Entering createChangeRequest:")
6461

6562
if (bool(data)):
6663
crBody=json.loads(data)
67-
if DEBUG:
68-
print("Data: " + data)
64+
logging.debug("Data: " + data)
6965
else:
7066
crBody= {}
71-
if DEBUG:
72-
print(" Data: None")
67+
logging.debug(" Data: None")
7368
crBody["cf_build_id"] = os.getenv('CF_BUILD_ID')
7469

7570

7671
url="%s/now/table/change_request" % (baseUrl)
7772

78-
if DEBUG:
79-
print(f" URL: {url}")
80-
print(f" User: {user}")
81-
print(f" Body: {crBody}")
73+
logging.debug(f" URL: {url}")
74+
logging.debug(f" User: {user}")
75+
logging.debug(f" Body: {crBody}")
8276

8377
resp=requests.post(url,
8478
json = crBody,
@@ -88,16 +82,18 @@ def createChangeRequest(user, password, baseUrl, data):
8882

8983
def processModifyChangeRequestResponse(response, action):
9084

91-
if DEBUG:
92-
print("Processing answer from CR %s REST call" %(action))
93-
print(" %s Change Request returned code %s" % (action,response.status_code))
85+
logging.debug("Processing answer from CR %s REST call" %(action))
86+
logging.debug(" %s Change Request returned code %s" % (action,response.status_code))
9487
if (response.status_code != 200 and response.status_code != 201):
95-
print(" %s Change Request creation failed with code %s" % (action, response.status_code))
96-
print(" ERROR: " + response.text)
88+
logging.error(" %s Change Request creation failed with code %s" % (action, response.status_code))
89+
logging.error(" ERROR: " + response.text)
9790
sys.exit(response.status_code)
9891

99-
print(" %s Change Request successful" %(action))
92+
logging.info(" %s Change Request successful" %(action))
10093
data=response.json() # json.loads(response.text)
94+
CR_NUMBER=data["result"]["number"]
95+
CR_SYSID=data["result"]["sys_id"]
96+
10197
FULL_JSON=json.dumps(data, indent=2)
10298

10399
if (action == "close" ):
@@ -111,6 +107,9 @@ def processModifyChangeRequestResponse(response, action):
111107
if os.path.exists(env_file_path):
112108
env_file = open(env_file_path, "a")
113109
env_file.write(f"{jsonVar}=/codefresh/volume/servicenow-cr-close.json\n")
110+
env_file.write(f"CR_NUMBER={CR_NUMBER}\n")
111+
env_file.write(f"CR_SYSID={CR_SYSID}\n")
112+
114113
env_file.close()
115114

116115
json_file=open("/codefresh/volume/servicenow-cr-close.json", "w")
@@ -120,9 +119,8 @@ def processModifyChangeRequestResponse(response, action):
120119
# Call SNow REST API to close a CR
121120
# Fields required are pasted in the data
122121
def closeChangeRequest(user, password, baseUrl, sysid, code, notes, data):
123-
if DEBUG:
124-
print("Entering closeChangeRequest:")
125-
print(f"DATA: {data}")
122+
logging.debug("Entering closeChangeRequest:")
123+
logging.debug(f"DATA: {data}")
126124
if (bool(data)):
127125
crBody=json.loads(data)
128126
else:
@@ -140,18 +138,16 @@ def closeChangeRequest(user, password, baseUrl, sysid, code, notes, data):
140138
# Call SNow REST API to update a CR
141139
# Fields required are pasted in the data
142140
def updateChangeRequest(user, password, baseUrl, sysid, data):
143-
if DEBUG:
144-
print("Entering updateChangeRequest:")
145-
print(f"DATA: {data}")
141+
logging.debug("Entering updateChangeRequest:")
142+
logging.debug(f"DATA: {data}")
146143
if (bool(data)):
147144
crBody=json.loads(data)
148145
else:
149146
crBody= {}
150-
print("WARNING: CR_DATA is empty. What are you updating exactly?")
147+
logging.error("WARNING: CR_DATA is empty. What are you updating exactly?")
151148

152149
url="%s/now/table/change_request/%s" % (baseUrl, sysid)
153-
if DEBUG:
154-
print(f" update CR URL: {url}")
150+
logging.debug(f" update CR URL: {url}")
155151
resp=requests.patch(url,
156152
json = crBody,
157153
headers = {"content-type":"application/json"},
@@ -162,10 +158,9 @@ def updateChangeRequest(user, password, baseUrl, sysid, data):
162158
#
163159
def callback(user, password, baseUrl, number, cf_build_id, token, policy):
164160

165-
if DEBUG:
166-
print("Entering callback:")
167-
print("CR Number: " + number)
168-
print("CF Build ID: " + cf_build_id)
161+
logging.debug("Entering callback:")
162+
logging.debug("CR Number: " + number)
163+
logging.debug("CF Build ID: " + cf_build_id)
169164

170165
url = "%s/%s/codefresh/callback" % (baseUrl, API_NAMESPACE)
171166

@@ -176,9 +171,8 @@ def callback(user, password, baseUrl, number, cf_build_id, token, policy):
176171
"cf_url": os.getenv("CF_URL"),
177172
"cr_policy": policy
178173
}
179-
if DEBUG:
180-
print("Calling POST on " + url)
181-
print("Data: " + json.dumps(body))
174+
logging.debug("Calling POST on " + url)
175+
logging.debug("Data: " + json.dumps(body))
182176

183177
resp=requests.post(url,
184178
json = body,
@@ -187,32 +181,29 @@ def callback(user, password, baseUrl, number, cf_build_id, token, policy):
187181
processCallbackResponse(response=resp)
188182

189183
def checkSysid(sysid):
190-
if DEBUG:
191-
print("Entering checkSysid: ")
192-
print(" CR_SYSID: %s" % (sysid))
184+
logging.debug("Entering checkSysid: ")
185+
logging.debug(" CR_SYSID: %s" % (sysid))
193186

194187
if ( sysid == None ):
195188
print("FATAL: CR_SYSID is not defined.")
196189
sys.exit(1)
197190

198191
def checkToken(token):
199-
if DEBUG:
200-
print("Entering checkToken: ")
201-
print(" TOKEN: %s" % (token))
192+
logging.debug("Entering checkToken: ")
193+
logging.debug(" TOKEN: %s" % (token))
202194

203195
if ( token == None ):
204-
print("FATAL: TOKEN is not defined.")
196+
logging.error("FATAL: TOKEN is not defined.")
205197
sys.exit(1)
206198

207199
def checkConflictPolicy(policy):
208-
if DEBUG:
209-
print("Entering checkConflictPolicy: ")
210-
print(" CR_CONFLICT_POLICY: %s" % (policy))
200+
logging.debug("Entering checkConflictPolicy: ")
201+
logging.debug(" CR_CONFLICT_POLICY: %s" % (policy))
211202

212203
if policy == "ignore" or policy == "reject" or policy == "wait":
213204
return
214205
else:
215-
print("FATAL: CR_CONFLICT_POLICY invalid value. Accepted values are ignore, reject or wait.")
206+
logging.error("FATAL: CR_CONFLICT_POLICY invalid value. Accepted values are ignore, reject or wait.")
216207
sys.exit(1)
217208

218209
def main():
@@ -226,13 +217,19 @@ def main():
226217
DEBUG = True if os.getenv('DEBUG', "false").lower() == "true" else False
227218
TOKEN = os.getenv('TOKEN')
228219
POLICY = os.getenv('CR_CONFLICT_POLICY')
229-
230220
if DEBUG:
231-
print("Starting ServiceNow plugin for Codefresh")
232-
print(f" ACTION: {ACTION}")
233-
print(f" DATA: {DATA}")
234-
print(" SYSID: %s" % (os.getenv('CR_SYSID')))
235-
print("---")
221+
LOG_LEVEL = "debug"
222+
else:
223+
LOG_LEVEL = os.getenv('LOG_LEVEL', "info")
224+
225+
log_format = "%(asctime)s:%(levelname)s:%(name)s.%(funcName)s: %(message)s"
226+
logging.basicConfig(format = log_format, level = LOG_LEVEL.upper())
227+
228+
logging.info("Starting ServiceNow plugin for Codefresh")
229+
logging.debug(f" ACTION: {ACTION}")
230+
logging.debug(f" DATA: {DATA}")
231+
logging.debug(" SYSID: %s" % (os.getenv('CR_SYSID')))
232+
236233

237234
if ACTION == "createcr":
238235
# Used only later in the callback but eant to check for error early
@@ -280,7 +277,7 @@ def main():
280277
data=DATA
281278
)
282279
else:
283-
printf("FATAL: Unknown action: {ACTION}. Allowed values are createCR, closeCR or updateCR.")
280+
logging.error("FATAL: Unknown action: {ACTION}. Allowed values are createCR, closeCR or updateCR.")
284281
sys.exit(1)
285282

286283

incubating/service-now/step.yaml

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ kind: step-type
22
version: '1.0'
33
metadata:
44
name: service-now
5-
version: 1.2.3
5+
version: 1.2.4
66
isPublic: true
77
description: Integration with ServiceNow Change Management
88
sources:
@@ -86,7 +86,7 @@ spec:
8686
},
8787
"SN_IMAGE_VERSION": {
8888
"type": "string",
89-
"default": "1.2.3",
89+
"default": "1.2.4",
9090
"description": "Version of the ServiceNow image to use, Docker image tag."
9191
},
9292
"SN_INSTANCE": {
@@ -137,7 +137,12 @@ spec:
137137
"DEBUG": {
138138
"type": "boolean",
139139
"default": false,
140-
"description": "a hidden option show more debug info"
140+
"description": "Obsolete - Set LOG_LEVEL to debug for backward compatibility"
141+
},
142+
"LOG_LEVEL": {
143+
"type": "string",
144+
"description": "OPTIONAL - set the log level, e.g. 'debug', 'info', 'warn', 'error', 'critical' (default 'error')",
145+
"default": "error"
141146
}
142147
}
143148
}

0 commit comments

Comments
 (0)