|
| 1 | +import os |
| 2 | +import json |
| 3 | +import logging |
| 4 | +import boto3 |
| 5 | +import requests |
| 6 | +import traceback |
| 7 | +from flask import Flask |
| 8 | +from flask import request |
| 9 | +from logging.handlers import SysLogHandler |
| 10 | +from urllib.request import Request, urlopen, URLError, HTTPError |
| 11 | + |
| 12 | +ENVIRONMENT = os.environ['ENVIRONMENT'] |
| 13 | +VIZION_API_KEY = os.environ['VIZION_API_KEY'] |
| 14 | +VIZION_API_DATA_S3_BUCKET = os.environ['VIZION_API_DATA_S3_BUCKET'] |
| 15 | +VIZION_ADD_CONTAINER_REFERENCE_API = os.environ['VIZION_API_HOST'] + "/references" |
| 16 | +VIZION_GET_REFERENCE_INFO_API = os.environ['VIZION_API_HOST'] + "/references/%s" |
| 17 | +VIZION_GET_REFERENCE_UPDATES_API = os.environ['VIZION_API_HOST'] + "/references/%s/updates" |
| 18 | +VIZION_UNSUBSCRIBE_FROM_REFERENCE_API = os.environ['VIZION_API_HOST'] + "/references/%s" |
| 19 | +VIZION_LIST_ALL_ACTIVE_REFERENCES_API = os.environ['VIZION_API_HOST'] + "/references?include_metadata=true" |
| 20 | +VIZION_LIST_ALL_AVAILABLE_CARRIERS_API = os.environ['VIZION_API_HOST'] + "/carriers" |
| 21 | +PAPERTRAIL_HOST = os.environ['PAPERTRAIL_HOST'] |
| 22 | +PAPERTRAIL_PORT = os.environ['PAPERTRAIL_PORT'] |
| 23 | +SLACK_WEBHOOK_URL = os.environ['SLACK_WEBHOOK_URL'] |
| 24 | +SLACK_INFO_CHANNEL = os.environ['SLACK_INFO_CHANNEL'] |
| 25 | +SLACK_ERROR_CHANNEL = os.environ['SLACK_ERROR_CHANNEL'] |
| 26 | + |
| 27 | +logging.basicConfig() |
| 28 | +logger = logging.getLogger() |
| 29 | +logger.setLevel(logging.INFO) |
| 30 | + |
| 31 | +if ENVIRONMENT != "DEV" and PAPERTRAIL_HOST != "" and PAPERTRAIL_PORT != "": |
| 32 | + syslog = SysLogHandler(address=(PAPERTRAIL_HOST, int(PAPERTRAIL_PORT))) |
| 33 | + format = '%(asctime)s Environment: ' + ENVIRONMENT + ' - VIZION-API: %(message)s' |
| 34 | + formatter = logging.Formatter(format, datefmt='%b %d %H:%M:%S') |
| 35 | + syslog.setFormatter(formatter) |
| 36 | + logger.addHandler(syslog) |
| 37 | + |
| 38 | +headers = {'X-API-Key': VIZION_API_KEY, 'Content-Type': 'application/json'} |
| 39 | + |
| 40 | +app = Flask(__name__) |
| 41 | + |
| 42 | +def post_message_on_slack(SLACK_CHANNEL, SLACK_MESSAGE='DEFAULT MESSAGE'): |
| 43 | + if SLACK_WEBHOOK_URL != "" and SLACK_CHANNEL != "": |
| 44 | + slack_message = { |
| 45 | + "username": "Serverless Vizion API Notification Bot", |
| 46 | + "channel": SLACK_CHANNEL, |
| 47 | + "text": SLACK_MESSAGE |
| 48 | + } |
| 49 | + |
| 50 | + req = Request(SLACK_WEBHOOK_URL, data=bytes(json.dumps(slack_message), encoding="utf-8")) |
| 51 | + |
| 52 | + try: |
| 53 | + response = urlopen(req) |
| 54 | + response.read() |
| 55 | + logger.info("Notified Slack in the '" + slack_message['channel'] + "' channel.") |
| 56 | + except HTTPError as error: |
| 57 | + error = traceback.format_exc() |
| 58 | + error_statement = "ERROR: Failed to Send Notification on Slack - Reason: " + str(error) |
| 59 | + logger.error(error_statement) |
| 60 | + except URLError as error: |
| 61 | + error = traceback.format_exc() |
| 62 | + error_statement = "ERROR: Failed to Send Notification on Slack - Reason: " + str(error) |
| 63 | + logger.error(error_statement) |
| 64 | + |
| 65 | +def add_json_object_on_s3(json_object, data_type, timestamp=""): |
| 66 | + s3_client = boto3.client('s3') |
| 67 | + |
| 68 | + object_key = "vizion-api-data/" + json_object['carrier_scac'] + "/" + json_object['container_id'] + "/" + data_type + timestamp + ".json" |
| 69 | + |
| 70 | + return s3_client.put_object( |
| 71 | + Body=str(json.dumps(json_object)), |
| 72 | + Bucket=VIZION_API_DATA_S3_BUCKET, |
| 73 | + Key=object_key |
| 74 | + ) |
| 75 | + |
| 76 | + logger.info("File Uploaded on AWS S3 Successfully.") |
| 77 | + |
| 78 | +@app.route("/") |
| 79 | +def main(): |
| 80 | + print_statement = "Vizion API Integration is Running." |
| 81 | + |
| 82 | + logger.info(print_statement) |
| 83 | + |
| 84 | + return { |
| 85 | + 'statusCode': 200, |
| 86 | + 'body': print_statement |
| 87 | + } |
| 88 | + |
| 89 | +@app.route("/add-container-reference/", methods=["POST"]) |
| 90 | +def add_container_reference(): |
| 91 | + try: |
| 92 | + response = requests.post(VIZION_ADD_CONTAINER_REFERENCE_API, headers=headers, data=request.data) |
| 93 | + response_status = response.status_code |
| 94 | + response_message = response.text |
| 95 | + |
| 96 | + if response_message == "": |
| 97 | + response_message = { |
| 98 | + "httpMessage":"Added.", |
| 99 | + "httpStatusCode": response_status |
| 100 | + } |
| 101 | + else: |
| 102 | + response_message = json.loads(response_message) |
| 103 | + add_json_object_on_s3(response_message['reference'], "creation") |
| 104 | + |
| 105 | + logger.info("Container Reference Added Successfully.") |
| 106 | + |
| 107 | + return { |
| 108 | + 'statusCode': response_status, |
| 109 | + 'body': response_message |
| 110 | + } |
| 111 | + except Exception as exp: |
| 112 | + exp = traceback.format_exc() |
| 113 | + error_statement = "ERROR: Failed to Add Container Reference - Reason: " + str(exp) |
| 114 | + logger.error(error_statement) |
| 115 | + post_message_on_slack(SLACK_ERROR_CHANNEL, ":heavy_exclamation_mark:" + error_statement) |
| 116 | + |
| 117 | + return { |
| 118 | + 'statusCode': 500, |
| 119 | + 'body': error_statement |
| 120 | + } |
| 121 | + |
| 122 | +@app.route("/get-reference-info/<string:referenceId>", methods=["GET"]) |
| 123 | +def get_reference_info(referenceId): |
| 124 | + try: |
| 125 | + response = requests.get(VIZION_GET_REFERENCE_INFO_API % referenceId, headers=headers) |
| 126 | + response_status = response.status_code |
| 127 | + response_message = response.text |
| 128 | + |
| 129 | + if response_message == "": |
| 130 | + response_message = { |
| 131 | + "httpMessage":"Received.", |
| 132 | + "httpStatusCode": response_status |
| 133 | + } |
| 134 | + else: |
| 135 | + response_message = json.loads(response_message) |
| 136 | + add_json_object_on_s3(response_message, "info") |
| 137 | + |
| 138 | + logger.info("Container Reference Received Successfully.") |
| 139 | + |
| 140 | + return { |
| 141 | + 'statusCode': response_status, |
| 142 | + 'body': response_message |
| 143 | + } |
| 144 | + except Exception as exp: |
| 145 | + exp = traceback.format_exc() |
| 146 | + error_statement = "ERROR: Failed to Get Container Reference Info - Reason: " + str(exp) |
| 147 | + logger.error(error_statement) |
| 148 | + post_message_on_slack(SLACK_ERROR_CHANNEL, ":heavy_exclamation_mark:" + error_statement) |
| 149 | + |
| 150 | + return { |
| 151 | + 'statusCode': 500, |
| 152 | + 'body': error_statement |
| 153 | + } |
| 154 | + |
| 155 | +@app.route("/get-reference-updates/<string:referenceId>", methods=["GET"]) |
| 156 | +def get_reference_updates(referenceId): |
| 157 | + try: |
| 158 | + response = requests.get(VIZION_GET_REFERENCE_UPDATES_API % referenceId, headers=headers) |
| 159 | + response_status = response.status_code |
| 160 | + response_message = response.text |
| 161 | + |
| 162 | + if response_message == "": |
| 163 | + response_message = { |
| 164 | + "httpMessage":"Received.", |
| 165 | + "httpStatusCode": response_status |
| 166 | + } |
| 167 | + else: |
| 168 | + response_message = json.loads(response_message) |
| 169 | + for item in response_message: |
| 170 | + add_json_object_on_s3(item['payload'], "updates", "-" + item['updated_at']) |
| 171 | + |
| 172 | + logger.info("Container Reference Updates Received Successfully.") |
| 173 | + |
| 174 | + return { |
| 175 | + 'statusCode': response_status, |
| 176 | + 'body': response_message |
| 177 | + } |
| 178 | + except Exception as exp: |
| 179 | + exp = traceback.format_exc() |
| 180 | + error_statement = "ERROR: Failed to Get Container Reference Updates - Reason: " + str(exp) |
| 181 | + logger.error(error_statement) |
| 182 | + post_message_on_slack(SLACK_ERROR_CHANNEL, ":heavy_exclamation_mark:" + error_statement) |
| 183 | + |
| 184 | + return { |
| 185 | + 'statusCode': 500, |
| 186 | + 'body': error_statement |
| 187 | + } |
| 188 | + |
| 189 | +@app.route("/get-reference-updates-via-callback/", methods=["POST"]) |
| 190 | +def get_reference_updates_via_callback(): |
| 191 | + try: |
| 192 | + response_status = 200 |
| 193 | + response_message = json.loads(request.data) |
| 194 | + add_json_object_on_s3(response_message['payload'], "updates-via-callback", "-" + response_message['updated_at']) |
| 195 | + |
| 196 | + logger.info("Container Reference Updates Received via Callback Successfully.") |
| 197 | + |
| 198 | + return { |
| 199 | + 'statusCode': response_status, |
| 200 | + 'body': response_message |
| 201 | + } |
| 202 | + except Exception as exp: |
| 203 | + exp = traceback.format_exc() |
| 204 | + error_statement = "ERROR: Failed to Get Container Reference Updates via Callback - Reason: " + str(exp) |
| 205 | + logger.error(error_statement) |
| 206 | + post_message_on_slack(SLACK_ERROR_CHANNEL, ":heavy_exclamation_mark:" + error_statement) |
| 207 | + |
| 208 | + return { |
| 209 | + 'statusCode': 500, |
| 210 | + 'body': error_statement |
| 211 | + } |
| 212 | + |
| 213 | +@app.route("/unsubscribe-from-reference/<string:referenceId>", methods=["DELETE"]) |
| 214 | +def unsubscribe_from_reference(referenceId): |
| 215 | + try: |
| 216 | + response = requests.delete(VIZION_UNSUBSCRIBE_FROM_REFERENCE_API % referenceId, headers=headers) |
| 217 | + response_status = response.status_code |
| 218 | + response_message = response.text |
| 219 | + |
| 220 | + if response_message == "": |
| 221 | + response_message = { |
| 222 | + "httpMessage":"Deleted.", |
| 223 | + "httpStatusCode": response_status |
| 224 | + } |
| 225 | + else: |
| 226 | + response_message = json.loads(response_message) |
| 227 | + |
| 228 | + logger.info("Container Reference Deleted Successfully.") |
| 229 | + |
| 230 | + return { |
| 231 | + 'statusCode': response_status, |
| 232 | + 'body': response_message |
| 233 | + } |
| 234 | + except Exception as exp: |
| 235 | + exp = traceback.format_exc() |
| 236 | + error_statement = "ERROR: Failed to Unsubscribe Container Reference - Reason: " + str(exp) |
| 237 | + logger.error(error_statement) |
| 238 | + post_message_on_slack(SLACK_ERROR_CHANNEL, ":heavy_exclamation_mark:" + error_statement) |
| 239 | + |
| 240 | + return { |
| 241 | + 'statusCode': 500, |
| 242 | + 'body': error_statement |
| 243 | + } |
| 244 | + |
| 245 | +@app.route("/list-all-active-references/", methods=["GET"]) |
| 246 | +def list_all_active_references(): |
| 247 | + try: |
| 248 | + api_url = VIZION_LIST_ALL_ACTIVE_REFERENCES_API |
| 249 | + container_references_list = [] |
| 250 | + nextToken = True |
| 251 | + while(nextToken == True): |
| 252 | + response = requests.get(api_url, headers=headers) |
| 253 | + response_status = response.status_code |
| 254 | + response_message = response.text |
| 255 | + |
| 256 | + if response_message == "": |
| 257 | + response_message = { |
| 258 | + "httpMessage":"Received.", |
| 259 | + "httpStatusCode": response_status |
| 260 | + } |
| 261 | + else: |
| 262 | + response_message = json.loads(response_message) |
| 263 | + container_references_list = container_references_list + response_message['data'] |
| 264 | + if response_message['metadata']['page'] != response_message['metadata']['page_count']: |
| 265 | + page_number = int(response_message['metadata']['page']) + 1 |
| 266 | + api_url = VIZION_LIST_ALL_ACTIVE_REFERENCES_API + "&page=" + str(page_number) |
| 267 | + else: |
| 268 | + nextToken = False |
| 269 | + |
| 270 | + logger.info("Container References List Received Successfully.") |
| 271 | + |
| 272 | + return { |
| 273 | + 'statusCode': response_status, |
| 274 | + 'body': container_references_list |
| 275 | + } |
| 276 | + except Exception as exp: |
| 277 | + exp = traceback.format_exc() |
| 278 | + error_statement = "ERROR: Failed to Get the List of All Container References - Reason: " + str(exp) |
| 279 | + logger.error(error_statement) |
| 280 | + post_message_on_slack(SLACK_ERROR_CHANNEL, ":heavy_exclamation_mark:" + error_statement) |
| 281 | + |
| 282 | + return { |
| 283 | + 'statusCode': 500, |
| 284 | + 'body': error_statement |
| 285 | + } |
| 286 | + |
| 287 | +@app.route("/list-all-available-carriers/", methods=["GET"]) |
| 288 | +def list_all_available_carriers(): |
| 289 | + try: |
| 290 | + response = requests.get(VIZION_LIST_ALL_AVAILABLE_CARRIERS_API, headers=headers) |
| 291 | + response_status = response.status_code |
| 292 | + response_message = response.text |
| 293 | + |
| 294 | + if response_message == "": |
| 295 | + response_message = { |
| 296 | + "httpMessage":"Received.", |
| 297 | + "httpStatusCode": response_status |
| 298 | + } |
| 299 | + else: |
| 300 | + response_message = json.loads(response_message) |
| 301 | + |
| 302 | + logger.info("Supported Carriers List Received Successfully.") |
| 303 | + |
| 304 | + return { |
| 305 | + 'statusCode': response_status, |
| 306 | + 'body': response_message |
| 307 | + } |
| 308 | + except Exception as exp: |
| 309 | + exp = traceback.format_exc() |
| 310 | + error_statement = "ERROR: Failed to Get the List of All Supported Carriers - Reason: " + str(exp) |
| 311 | + logger.error(error_statement) |
| 312 | + post_message_on_slack(SLACK_ERROR_CHANNEL, ":heavy_exclamation_mark:" + error_statement) |
| 313 | + |
| 314 | + return { |
| 315 | + 'statusCode': 500, |
| 316 | + 'body': error_statement |
| 317 | + } |
| 318 | + |
| 319 | +def lambda_handler(event, context): |
| 320 | + return main() |
| 321 | + |
| 322 | +# For local testing |
| 323 | +if __name__ == '__main__': |
| 324 | + app.run() |
0 commit comments