def send_request_cssm(self, uuid, oauthToken): print( "-------------------------------------------------------------------------------------------" ) print("contact cssm debugs") print( "-------------------------------------------------------------------------------------------" ) threads = [] slr_table = slr_req_tbl try: rows = TokensModel.find_by_uuid(uuid, "device_store") except Exception as e: print(e) return database_err, 500 if not rows: return ({"request": "No Devices with this UUID"}), 400 for row in rows: print("Launching threads to get auth tokens") response_update = {} response_update['status'] = resp_status_started TokensModel.update(uuid, response_update, "upload_info_store") self.slr.update_status(slr_table, row[0], row[1], s_start, step) th = threading.Thread(target=slrcontactcssm.get_cssm_response, args=(row[6], row[5], oauthToken, row[1], row[0])) th.start() threads.append(th) return (accept), 201
def get(self, uuid): threads = [] logger.info(uuid) try: rows = TokensModel.find_by_uuid(uuid, "device_store") except Exception as e: print(e) logger.error({"message": "Data search operation failed!"}, exc_info=True) return {"message": "Data search operation failed!"}, 500 for row in rows: logger.info("Launching threads to get auth tokens") # Updating the response status Step 2 started response_update = {'status': "S2s"} TokensModel.update(uuid, response_update, "upload_info_store") self.slr.update_status(SLR_REQUEST_CODE_TABLE_NAME, row[0], row[1], "Started", "step1") th = threading.Thread(target=SlrRequestCode.execute_cli_wrapper, args=(row[1], row[2], row[3], req_token_command, row[0], row[4], row[5], row[6])) th.start() threads.append(th) logger.info({"request": "accepted"}) return {"request": "accepted"}, 201
def process_request(self, uuid): threads = [] slr_table = slr_req_tbl try: rows = TokensModel.find_by_uuid(uuid, "device_store") except Exception as e: print(e) return database_err, 500 for row in rows: response_update = {} response_update['status'] = resp_status_started TokensModel.update(uuid, response_update, "upload_info_store") self.slr.update_status(slr_table, row[0], row[1], s_start, step) print(row) val = self.slr.find_by_uuid_ipaddr(uuid, slr_table, row[1]) print(val) if val[0][3] == s_done: th = threading.Thread( target=slrauthzswitch.send_authorize_information, args=(row[1], row[2], row[3], req_token_command, val[0][6], val[0][9], val[0][10], uuid)) th.start() threads.append(th) else: self.slr.update_status(slr_table, uuid, row[1], "Error in previous step", step) rows = self.slr.find_by_step_status(slr_req_tbl, uuid, s_start, step) if (len(rows) == 0): response_update = {} response_update['status'] = resp_status_complete TokensModel.update(uuid, response_update, "upload_info_store") return accept, 201
def send_request_cssm(self, uuid, oauthToken): logger.info("contact CSSM debugs") threads = [] slr_table = SLR_REQUEST_CODE_TABLE_NAME try: rows = TokensModel.find_by_uuid(uuid, "device_store") except Exception as e: print(e) logger.error({"message": "Data search operation failed!"}, exc_info=True) return {"message": "Data search operation failed!"}, 500 if not rows: logger.error("No Devices with this UUID") return ({"request": "No Devices with this UUID"}), 400 for row in rows: logger.info("Launching threads to get auth tokens") # Updating the response status to Step 3 started response_update = {'status': "S3s"} TokensModel.update(uuid, response_update, "upload_info_store") self.slr.update_status(slr_table, row[0], row[1], "Started", "step2") ''' Bulk DLC Call''' if TokensModel.find_fileType(uuid) != "sl" and TokensModel.find_slr_type(uuid) == "slr": domain_name, dlcRequest = SlrRequestCode.get_dlc_conversion_api_body(uuid) if dlcRequest: self.slr_bulkDLC(uuid, domain_name, dlcRequest, config.OAUTH_TOKEN) if TokensModel.find_fileType(uuid) != "sl" and TokensModel.find_slr_type(uuid) == "slrx": domain_name, dlcRequest = ImportCodes.get_dlc_payload(uuid) if dlcRequest: self.slr_bulkDLC(uuid, domain_name, dlcRequest, config.OAUTH_TOKEN) th = threading.Thread(target=SlrContactCSSM.get_cssm_response, args=(row[6], row[5], oauthToken, row[1], row[0])) th.start() threads.append(th) logger.info({"request": "accepted"}) return {"request": "accepted"}, 201
def get(self, uuid, page): try: rows_uuid = TokensModel.find_by_uuid(uuid, "device_store") except: return {"message": "Data search operation failed!"}, 500 if not rows_uuid: return {'message': "Request with UUID: '{}' doesn't exists.".format(uuid)}, 404 config.NO_OF_DEVICES = len(rows_uuid) config.NO_OF_PAGES = ceil(config.NO_OF_DEVICES/10) print("Pagination: UUID for this request is:", uuid) print("Pagination: Total number of pages:", config.NO_OF_PAGES) print("Pagination: Page number requested is:", page) if page < 1 or page > config.NO_OF_PAGES: return {'message': "Page doesn't exists!"}, 400 try: rows = TokensModel.find_by_uuid_slice(uuid, page, "device_store") except: return {"message": "Data search operation failed!"}, 500 devices = [] for row in rows: devices.append({'ipaddr': row[1], 'username': row[2], 'password': row[3], 'sa_name': row[4], 'va_name': row[5], 'domain': row[6]}) print("==>> Printing devices from within get method for resource: Tokens <<==") print(devices) if rows: return {'uuid': uuid, 'totalpages': config.NO_OF_PAGES, 'devices': devices} return {"message": "Request with UUID: '{}' not found!".format(uuid)}, 404
def get(self, uuid): try: rows = TokensModel.find_by_uuid(uuid, "upload_info_store") except Exception as e: print(e) return database_err, 500 return {'status': rows[0][5]}, 201
def get(self, uuid): try: rows = TokensModel.find_by_uuid(uuid, "upload_info_store") except Exception as e: print(e) logger.error({"message": "Data search operation failed!"}, exc_info=True) return {"message": "Data search operation failed!"}, 500 return {'status': rows[0][5]}, 201
def generate_output(self, uuid, page): slr_table = SLR_REQUEST_CODE_TABLE_NAME response = {} try: total_rows = TokensModel.find_by_uuid(uuid, "device_store") except Exception as e: print(e) logger.error({"message": "Data search operation failed!"}, exc_info=True) return {"message": "Data search operation failed!"}, 500 config.NO_OF_DEVICES = len(total_rows) config.NO_OF_PAGES = ceil(config.NO_OF_DEVICES / NUMBER_OF_DEVICES_PER_PAGE) response["totalpages"] = config.NO_OF_PAGES response["devices"] = [] try: rows = TokensModel.find_by_uuid_slice(uuid, page, "device_store") except Exception as e: print(e) logger.error({"message": "Data search operation failed!"}, exc_info=True) return {"message": "Data search operation failed!"}, 500 for row in rows: ip_address = row[1] try: val = self.slr.find_by_uuid_ipaddr(uuid, slr_table, ip_address) except Exception as e: print(e) logger.error({"message": "Data search operation failed!"}, exc_info=True) return {"message": "Data search operation failed!"}, 500 device_dict = {} for i in col: device_dict[col[i]] = row[i] logger.info(val) device_dict['s2Status'] = "" device_dict['s3Status'] = "" device_dict['s4Status'] = "" try: device_dict['s2Status'] = val[0][2] device_dict['s3Status'] = val[0][3] device_dict['s4Status'] = val[0][4] except Exception as e: print(e) response["devices"].append(device_dict) del device_dict logger.info("Final response") logger.info(response) return response, 201
def generate_output(self, uuid, page): slr_table = None slr_table = slr_req_tbl if (slr_table == None): return invalid_request, 404 response = {} try: total_rows = TokensModel.find_by_uuid(uuid, "device_store") except Exception as e: print(e) return database_err, 500 config.NO_OF_DEVICES = len(total_rows) config.NO_OF_PAGES = ceil(config.NO_OF_DEVICES / num_of_device_per_page) response[pages] = config.NO_OF_PAGES response[device] = [] try: rows = TokensModel.find_by_uuid_slice(uuid, page, "device_store") except Exception as e: print(e) return database_err, 500 for row in rows: ip_address = row[ip_addr] try: val = self.slr.find_by_uuid_ipaddr(uuid, slr_table, ip_address) except Exception as e: print(e) return database_err, 500 device_dict = {} for i in col: device_dict[col[i]] = row[i] print(val) device_dict['s2Status'] = "" device_dict['s3Status'] = "" device_dict['s4Status'] = "" try: device_dict['s2Status'] = val[0][2] device_dict['s3Status'] = val[0][3] device_dict['s4Status'] = val[0][4] except Exception as e: print(e) response[device].append(device_dict) del (device_dict) print("Final response") print(response) return (response), 201
def get(self, uuid): try: rows = TokensModel.find_by_uuid(uuid, "slr_request_code_tbl") except Exception as e: print(e) logger.error("Data search operation failed!", exc_info=True) return {"message": "Data search operation failed!"}, 500 if rows: # Counter for total no of devices for which auth codes needs to be generated total_devices = len(rows) not_started_counter = 0 started_counter = 0 failed_counter = 0 processed_counter = 0 # Updated for all status types for row in rows: if row[3] == "NS": not_started_counter += 1 elif row[3] == "Started": started_counter += 1 elif row[3] == "Completed": processed_counter += 1 elif "Error" in row[3]: failed_counter += 1 processed_counter += 1 if processed_counter == total_devices: status = "Completed" elif not_started_counter == total_devices: status = "NotStarted" else: status = "In-Progress" return { 'message': 'Successfully fetched status of Auth Codes!', 'progress': status, 'total': total_devices, 'failed': failed_counter, 'processed': processed_counter }, 200 else: logger.error("Request with UUID: '{}' not found!".format(uuid)) return { "message": "Request with UUID: '{}' not found!".format(uuid) }, 404
def post(self, uuid): data = Validate.parser.parse_args() rows = TokensModel.find_by_uuid(uuid, "validation_store") if not rows: logger.error("Request with UUID: '{}' doesn't exists.".format(uuid)) return {'message': "Request with UUID: '{}' doesn't exists.".format(uuid)}, 404 domains = TokensModel.find_by_uuid_distinct(uuid, "validation_store") for domain in domains: url = "https://apmx.cisco.com/services/api/smart-accounts-and-licensing/v1/accounts/" + domain + \ "/customer/virtual-accounts" headers = { "Authorization": data['oauth_token'], "Content-Type": "application/json" } response = requests.request("GET", url, headers=headers) logger.info(response.json()) logger.info("success") return {"message": "success"}, 201
def process_request(self, uuid): threads = [] slr_table = SLR_REQUEST_CODE_TABLE_NAME try: rows = TokensModel.find_by_uuid(uuid, "device_store") except Exception as e: print(e) logger.error({"message": "Data search operation failed!"}, exc_info=True) return {"message": "Data search operation failed!"}, 500 for row in rows: # Updating the response status to Step 4 started response_update = {'status': "S4s"} TokensModel.update(uuid, response_update, "upload_info_store") self.slr.update_status(slr_table, row[0], row[1], "Started", "step3") logger.info(row) val = self.slr.find_by_uuid_ipaddr(uuid, slr_table, row[1]) logger.info(val) if val[0][3] == "Completed": th = threading.Thread( target=SlrAuthSwitch.send_authorize_information, args=(row[1], row[2], row[3], ["end"], val[0][6], val[0][9], val[0][10], uuid)) th.start() threads.append(th) else: self.slr.update_status(slr_table, uuid, row[1], "Error in previous step", "step3") rows = self.slr.find_by_step_status( SLR_REQUEST_CODE_TABLE_NAME, uuid, "Started", "step3") if len(rows) == 0: # Updating the response status to Step 4 completed response_update = {'status': "S4c"} TokensModel.update(uuid, response_update, "upload_info_store") logger.info({"request": "accepted"}) return {"request": "accepted"}, 201
def get(self, uuid): threads = [] print(uuid) response = accept slr_table = slr_req_tbl try: rows = TokensModel.find_by_uuid(uuid, "device_store") except Exception as e: print(e) return database_err, 500 for row in rows: print("Launching threads to get auth tokens") response_update = {} response_update['status'] = resp_status_started TokensModel.update(uuid, response_update, "upload_info_store") self.slr.update_status(slr_table, row[0], row[1], s_start, step) th = threading.Thread(target=slrrequestcode.execute_cli_wrapper, args=(row[1], row[2], row[3], req_token_command, row[0])) th.start() threads.append(th) return (response), 201
def update_req_codes_slr(cls, validated_json): # s = slr("", "", "") # Start extracting required fields from json uuid = validated_json['registration-uuid'] registration_name = validated_json['registration-name'] # First check if devices with this UUID already exists try: rows_slr = TokensModel.find_by_uuid(uuid, "slr_request_code_tbl") rows = TokensModel.find_by_uuid(uuid, "device_store") except Exception as e: print(e) return {"message": "Data search operation failed!", 'code': 500} if rows_slr: # Changed to 200 from 400 on UI Dev team request print("==>> UUID already exists in slr_request_code_tbl...") return { "message": "Registration request with this UUID already exists!", 'code': 200 } if rows: # Changed to 200 from 400 on UI Dev team request print("==>> UUID already exists in device_store...") return { "message": "Registration request with this UUID already exists!", 'code': 200 } # Creat update_slr_reqcode_table_dict insert_slr_reqcode_table_list = [] insert_device_store_table_list = [] insert_upload_info_store_table_list = [] for device in validated_json['devices']: # Traverse through validated_json dictionary and create a list of flat key-value pair dict each_device_reqcode_dict = {} each_device_store_dict = {} each_device_upload_info_store_dict = {} # Initialize lic_count_str & lic_ent_tag_str lic_count_str, lic_ent_tag_str = "", "" # Prepare fields for slr_request_code_tbl each_device_reqcode_dict['uuid'] = uuid each_device_reqcode_dict['ipaddr'] = device['device-uuid'] each_device_reqcode_dict['step1'] = device['step1'] each_device_reqcode_dict['step2'] = "NS" each_device_reqcode_dict['step3'] = "NS" each_device_reqcode_dict['authz_req_code'] = device['request-code'] each_device_reqcode_dict['authz_response_code'] = "" each_device_reqcode_dict['license'] = "" for license in device['licenses']: print("\n\n") print("**** Printing license sub-json...") print(license) lic_count_str += license['license-count'] + " " lic_ent_tag_str += license['license-entitlement-tag'] + " " each_device_reqcode_dict['license_count'] = lic_count_str.strip() each_device_reqcode_dict[ 'license_entitlement_tag'] = lic_ent_tag_str.strip() print("\n\n") print("**** Importing license count...") print(each_device_reqcode_dict['license_count']) print("**** Importing license cent tag...") print(each_device_reqcode_dict['license_entitlement_tag']) print("\n\n") each_device_reqcode_dict['tftp_server_ip'] = "" each_device_reqcode_dict['tftp_server_path'] = "" each_device_reqcode_dict['device_uuid'] = device['device-uuid'] # Prepare fields for device_store each_device_store_dict['uuid'] = uuid each_device_store_dict['ipaddr'] = device['device-uuid'] each_device_store_dict['username'] = "******" each_device_store_dict['password'] = "******" each_device_store_dict['sa_name'] = device['sa-name'] each_device_store_dict['va_name'] = device['va-name'] each_device_store_dict['domain'] = device['domain'] each_device_store_dict['device_uuid'] = device['device-uuid'] # Prepare fields for upload_info_store each_device_upload_info_store_dict['uuid'] = uuid each_device_upload_info_store_dict['userid'] = "NA" each_device_upload_info_store_dict['filename'] = registration_name each_device_upload_info_store_dict['type'] = "slr" each_device_upload_info_store_dict[ 'timestamp'] = datetime.datetime.fromtimestamp( time.time()).strftime('%Y-%m-%d %H:%M:%S') # each_device_upload_info_store_dict['status'] = "S2c" each_device_upload_info_store_dict['status'] = "S2ci" # Now add each_device_reqcode_dict to update_slr_reqcode_table_list insert_slr_reqcode_table_list.append(each_device_reqcode_dict) # Now add each_device_store_dict to update_device_store_table_list insert_device_store_table_list.append(each_device_store_dict) # Now add each_device_upload_info_store_dict to insert_upload_info_store_table_list insert_upload_info_store_table_list.append( each_device_upload_info_store_dict) # Now print list of flat key-value pair dict - update_slr_reqcode_table_list print( "==>> Printing update_slr_reqcode_table_list before inserting into slr_request_code_tbl..." ) print(insert_slr_reqcode_table_list) # Now print list of flat key-value pair dict - update_device_store_table_list print( "==>> Printing update_device_store_table_list before inserting into device_store..." ) print(insert_device_store_table_list) # Now print list of flat key-value pair dict - insert_upload_info_store_table_list print( "==>> Printing insert_upload_info_store_table_list before inserting into upload_info_store" ) print(insert_upload_info_store_table_list) try: TokensModel.insert_slr(uuid, insert_slr_reqcode_table_list, "slr_request_code_tbl") print( "==>> Now printing slr_request_code_tbl after updateing request_codes..." ) if TokensModel.find_by_uuid(uuid, "slr_request_code_tbl"): print("==>> Done printing slr_request_code_tbl") except Exception as e: print( "==>> Printig exception while inserting data into slr_request_code_tbl..." ) print(e) return { 'message': "Data insert operation slr_request_code_tbl failed!", 'code': 500 } try: TokensModel.insert(uuid, insert_device_store_table_list, "device_store") print( "==>> Now printing device_store after updating sa, va, domain..." ) if TokensModel.find_by_uuid(uuid, "device_store"): print("==>> Done printing device_store") except Exception as e: print( "==>> Printig exception while inserting data into device_store..." ) print(e) return { 'message': "Data insert operation device_store failed!", 'code': 500 } try: TokensModel.insert(uuid, insert_upload_info_store_table_list, "upload_info_store") print( "==>> Now printing upload_info_store after updating registration-name, status..." ) if TokensModel.find_by_uuid(uuid, "upload_info_store"): print("==>> Done printing upload_info_store") except Exception as e: print( "==>> Printig exception while inserting data into upload_info_store..." ) print(e) return { 'message': "Data insert operation device_store failed!", 'code': 500 } # Finally return success - 201 return {'message': "Tables successfully updated!", 'code': 201}
def update_auth_codes_slr(cls, validated_json): s = slr("", "", "") # Start extracting required fields from json uuid = validated_json['registration-uuid'] # registration_name = validated_json['registration-name'] # First check if devices with this UUID already exists try: rows_slr = TokensModel.find_by_uuid(uuid, "slr_request_code_tbl") rows = TokensModel.find_by_uuid(uuid, "device_store") except Exception as e: print(e) return {"message": "Data search operation failed!", 'code': 500} if not rows_slr: # Changed to 200 from 400 on UI Dev team request print("==>> UUID doesn't exists in slr_request_code_tbl...") return { "message": "Registration request with this UUID doesn't exists!", 'code': 200 } if not rows: # Changed to 200 from 400 on UI Dev team request print("==>> UUID doesn't exists in device_store...") return { "message": "Registration request with this UUID doesn't exists!", 'code': 200 } # Prepare fields for upload_info_store upload_info_store_dict = {} upload_info_store_dict['status'] = "S3si" try: TokensModel.update(uuid, upload_info_store_dict, "upload_info_store") except Exception as e: print(e) return { 'message': "Status update operation upload_info_store failed!", 'code': 500 } for device in validated_json['devices']: # Update status for step2 (Auth-Code generation) for each device try: s.update_status_device_uuid("slr_request_code_tbl", uuid, device['device-uuid'], device['step2'], 'step2') except Exception as e: print( "++>> Not able to update step2 status in slr_request_code_tbl..." ) print(e) # Update Auth-Code for each device try: s.update_authz_response_code_device_uuid( "slr_request_code_tbl", uuid, device['device-uuid'], device['auth-code']) except Exception as e: print( "++>> Not able to update Auth-Code in slr_request_code_tbl..." ) print(e) # Prepare fields for upload_info_store upload_info_store_dict['status'] = "S3ci" # We are updating timestamp only when step2 is complete upload_info_store_dict['timestamp'] = datetime.datetime.fromtimestamp( time.time()).strftime('%Y-%m-%d %H:%M:%S') try: TokensModel.update(uuid, upload_info_store_dict, "upload_info_store") except Exception as e: print(e) return { 'message': "Status update operation slr_request_code_tbl failed!", 'code': 500 } # Finally return success - 201 return {'message': "Tables successfully updated!", 'code': 201}
def get(self, uuid): try: rows = TokensModel.join_by_uuid(uuid, "slr_request_code_tbl", "device_store") logger.info( "Printing rows of devices. This should be one per device...") logger.info(rows) except Exception as e: print(e) logger.error("Data(UUID) search operation failed!", exc_info=True) return {"message": "Data(UUID) search operation failed!"}, 500 try: update_row = TokensModel.find_by_uuid(uuid, "upload_info_store") logger.info("***** Printing row from upload_info_store...") logger.info(update_row) logger.info("***** Done printing row from upload_info_store.") except Exception as e: print(e) logger.error("Data(UUID) search operation failed!", exc_info=True) return {"message": "Data(UUID) search operation failed!"}, 500 if update_row: if update_row[0][5] != "S2c": # Changed to 200 from 400 on UI Dev team request logger.info( "Request Codes are not yet generated for UUID: {}".format( uuid)) return { "message": "Request Codes are not yet generated for UUID: {}".format( uuid) }, 200 if rows: # Counter for devices with request code generated successfully counter = 0 devices = [] response_update = {} response_update['status'] = "S2sx" try: TokensModel.update(uuid, response_update, "upload_info_store") except Exception as e: print(e) logger.error( "Status update operation upload_info_store failed!", exc_info=True) return { 'message': "Status update operation upload_info_store failed!", 'code': 500 } for row in rows: licenses = [] # Update individual device status based on ip addr row[1] # self.slr.update_status("slr_request_code_tbl", row[0], row[1], "Request Code Export Started", "step1") # Find out if for this device req code generation was successful if row[2] == "Completed": counter += 1 # license count and ent tag are passed as list lic_count_list = str(row[6]).split(" ") lic_ent_list = str(row[7]).split(" ") logger.info("lic_count_list:") logger.info(lic_count_list) logger.info("lic_ent_list:") logger.info(lic_ent_list) for element in range(len(lic_count_list)): # First handle lic entitlement & count coming in as null string lic_ent = lic_ent_list[element] lic_count = lic_count_list[element] if lic_ent == "": lic_ent = "None" if lic_count == "": lic_count = "None" licenses.append({ 'license-entitlement-tag': lic_ent, 'license-count': lic_count }) # Handle request code coming in as null string request_code = row[5] if request_code == "": request_code = "None" devices.append({ 'device-uuid': row[11], 'sa-name': row[8], 'va-name': row[9], 'domain': row[10], 'request-code': request_code, 'step1': row[2], 'licenses': licenses }) logger.info( "==>> Printing devices from within get method for resource: Tokens <<==" ) logger.info(devices) logger.info( "==>> Printing licenses from within get method for resource: Tokens <<==" ) logger.info(licenses) # Update individual device status based on ip addr row[1] # self.slr.update_status("slr_request_code_tbl", row[0], row[1], "Request Code Export Completed", # "step1") # Now update 'upload_info_store' to S2cx response_update['status'] = "S2cx" try: TokensModel.update(uuid, response_update, "upload_info_store") except Exception as e: print(e) logger.error( "Status update operation upload_info_store failed!", exc_info=True) return { 'message': "Status update operation upload_info_store failed!", 'code': 500 } try: registration_row = TokensModel.find_by_uuid( uuid, "upload_info_store") except Exception as e: print(e) logger.error("Data(UUID) search operation failed!", exc_info=True) return {"message": "Data(UUID) search operation failed!"}, 500 try: domain_name, dlcRequest = SlrRequestCode.get_dlc_conversion_api_body( uuid) dlcRequest_dict = {"virtualAccounts": []} for key, value in dlcRequest.items(): dlcRequest_dict["virtualAccounts"].append({ "dlcRequests": value, "name": key }) except Exception as e: print(e) logger.error("Data(UUID) search operation failed!", exc_info=True) return {"message": "Data(UUID) search operation failed!"}, 500 return { 'registration-name': registration_row[0][2], 'slr-data-export-type': 'request_codes', 'registration-uuid': uuid, 'exported-on': datetime.datetime.fromtimestamp( time.time()).strftime('%Y-%m-%d %H:%M:%S'), 'total-devices': len(rows), 'devices-with-success': counter, 'devices': devices, 'dlcData': dlcRequest_dict } else: # Changed to 200 from 404 on UI Dev team request logger.info("Request with UUID: '{}' not found!".format(uuid)) return { "message": "Request with UUID: '{}' not found!".format(uuid) }, 200
def get(self, uuid): try: rows = TokensModel.join_by_uuid(uuid, "slr_request_code_tbl", "device_store") logger.info( "Printing rows of devices. This should be one per device...") logger.info(rows) except Exception as e: print(e) logger.error("Data(UUID) search operation failed!", exc_info=True) return {"message": "Data(UUID) search operation failed!"}, 500 try: update_row = TokensModel.find_by_uuid(uuid, "upload_info_store") logger.info("***** Printing row from upload_info_store...") logger.info(update_row) logger.info("***** Done printing row from upload_info_store.") except Exception as e: print(e) logger.error("Data(UUID) search operation failed!", exc_info=True) return {"message": "Data(UUID) search operation failed!"}, 500 if update_row: if update_row[0][5] != "S3c": # Changed to 200 from 400 on UI Dev team request logger.info( "Auth Codes are not yet generated for UUID: {}".format( uuid)) return { "message": "Auth Codes are not yet generated for UUID: {}".format( uuid) }, 200 if rows: # Counter for devices with auth code generated successfully counter = 0 devices = [] response_update = {} response_update['status'] = "S3sx" # This is a update status for all devices in a request try: TokensModel.update(uuid, response_update, "upload_info_store") except Exception as e: print(e) logger.error( "Auth codes export status update operation upload_info_store failed!", exc_info=True) return { 'message': "Auth codes export status update operation upload_info_store failed!", 'code': 500 } for row in rows: # Update individual device status based on ip addr row[1] # self.slr.update_status("slr_request_code_tbl", row[0], row[1], "Auth Code Export Started", "step2") # Find out if for this device auth code generation was successful if row[3] == "Completed": counter += 1 # Handle auth_code coming in as null string auth_code = row[12] if auth_code == "": auth_code = "None" devices.append({ 'device-uuid': row[11], 'auth-code': auth_code, 'step2': row[3] }) logger.info( "==>> Printing devices from within get method for resource: Tokens <<==" ) logger.info(devices) # Update individual device status based on ip addr row[1] # self.slr.update_status("slr_request_code_tbl", row[0], row[1], "Auth Code Export Completed", "step2") # Now update 'upload_info_store' to S3cx response_update['status'] = "S3cx" try: TokensModel.update(uuid, response_update, "upload_info_store") except Exception as e: print(e) logger.error( "Auth codes export status update operation upload_info_store failed!", exc_info=True) return { 'message': "Auth codes export status update operation upload_info_store failed!", 'code': 500 } try: registration_row = TokensModel.find_by_uuid( uuid, "upload_info_store") except Exception as e: print(e) logger.error("Data(UUID) search operation failed!", exc_info=True) return {"message": "Data(UUID) search operation failed!"}, 500 return { 'registration-name': registration_row[0][2], 'slr-data-export-type': 'auth_codes', 'registration-uuid': uuid, 'exported-on': datetime.datetime.fromtimestamp( time.time()).strftime('%Y-%m-%d %H:%M:%S'), 'total-devices': len(rows), 'devices-with-success': counter, 'devices': devices } else: # Changed to 200 from 404 on UI Dev team request logger.error("Request with UUID: '{}' not found!".format(uuid), exc_info=True) return { "message": "Request with UUID: '{}' not found!".format(uuid) }, 200
def post(self): File.parser.add_argument('registration_type', type=str, required=True, help="This field cannot be blank.") data = File.parser.parse_args() logger.info("OAuth token is: {}".format(data['oauth_token'])) # Generate UUID to identify registration request uuid_str = str(uuid.uuid4()) config.UUID = uuid_str # Valid registration_type list registration_list = ['sl', 'slr'] if data['registration_type'] not in registration_list: logger.error("Registration type is not valid!") return {'message': "Registration type is not valid!"}, 400 if 'file' not in request.files: logger.error("No File in the request!") return {"message": "No File in the request!"}, 400 file = request.files['file'] if file.filename == '': logger.error("No File selected!") return {'message': "No File selected!"}, 400 if not File.allowed_file(file.filename): logger.error("File type not allowed! Only CSV files are allowed!") return { 'message': "File type not allowed! Only CSV files are allowed!" }, 400 # Validate each field/column of CSV file validate_flag, errors, df = File.validate_csv( file, data['registration_type']) if not validate_flag: logger.error("CSV file validation failed!: '{}'".format(errors)) return { 'message': "CSV file validation failed!: '{}'".format(errors) }, 400 # Create dictionary for upload_info_store upload_info_dict = { 'uuid': uuid_str, 'userid': config.USER_ID, 'filename': file.filename, 'type': data['registration_type'], 'timestamp': datetime.datetime.fromtimestamp( time.time()).strftime('%Y-%m-%d %H:%M:%S'), 'status': "csv_file_uploaded" } # Also set REGISTRATION_NAME as filename in config file config.REGISTRATION_NAME = file.filename # Create dictionaries for device_store, validation_store, device_status_store converted_json, converted_validation_json, converted_status_json = File.csv_to_json( df) # Enter data into the database store device_store if TokensModel.find_by_uuid(uuid_str, "device_store"): logger.info("Request with UUID: '{}' already exists.".format(uuid)) return { 'message': "Request with UUID: '{}' already exists.".format(uuid) }, 400 try: TokensModel.insert(uuid_str, converted_json, "device_store") except Exception as e: print(e) logger.error("Data insert operation device_store failed!", exc_info=True) return { "message": "Data insert operation device_store failed!" }, 500 # Enter data into the database store account_validation if TokensModel.find_by_uuid(uuid_str, "validation_store"): logger.info("Request with UUID: '{}' already exists.".format(uuid)) return { 'message': "Request with UUID: '{}' already exists.".format(uuid) }, 400 try: TokensModel.insert(uuid_str, converted_validation_json, "validation_store") except Exception as e: print(e) logger.error("Data insert operation validation_store failed!", exc_info=True) return { "message": "Data insert operation validation_store failed!" }, 500 # Enter data into the database store device_status_store if TokensModel.find_by_uuid(uuid_str, "device_status_store"): logger.info("Request with UUID: '{}' already exists.".format(uuid)) return { 'message': "Request with UUID: '{}' already exists.".format(uuid) }, 400 try: TokensModel.insert(uuid_str, converted_status_json, "device_status_store") except Exception as e: print(e) logger.error("Data insert operation device_status_store failed!", exc_info=True) return { "message": "Data insert operation device_status_store failed!" }, 500 try: if data['registration_type'] == 'slr': TokensModel.insert(uuid_str, converted_json, "slr_request_code_tbl") except Exception as e: print(e) logger.error("Data insert operation slr_request_code_tbl failed!", exc_info=True) return { "message": "Data insert operation slr_request_code_tbl failed!" }, 500 # Enter data into the database store upload_info_store if TokensModel.find_by_uuid(uuid_str, "upload_info_store"): logger.info("Request with UUID: '{}' already exists.".format(uuid)) return { 'message': "Request with UUID: '{}' already exists.".format(uuid) }, 400 try: TokensModel.insert(uuid_str, [upload_info_dict], "upload_info_store") except Exception as e: print(e) logger.error("Data insert operation failed!", exc_info=True) return {"message": "Data insert operation failed!"}, 500 config.NO_OF_DEVICES = len(converted_json) config.NO_OF_PAGES = ceil(len(converted_json) / 10) new_request = { 'uuid': uuid_str, 'totalpages': config.NO_OF_PAGES, 'message': 'File is uploaded!' } # For debugging logger.info(new_request) if TokensModel.find_by_uuid(uuid_str, "validation_store"): logger.info("Printed validation_store") if TokensModel.find_by_uuid(uuid_str, "device_status_store"): logger.info("Printed device_status_store") if TokensModel.find_by_uuid(uuid_str, "upload_info_store"): logger.info("Printed upload_info_store") logger.info( "The request has been fulfilled and has resulted in one or more new resources being created" ) return new_request, 201
def post(self): File.parser.add_argument('registration_type', type=str, required=True, help="This field cannot be blank." ) data = File.parser.parse_args() print("OAuth token is:", data['oauth_token']) # Generate UUID to identify registration request uuid_str = str(uuid.uuid4()) if 'file' not in request.files: return {"message": "No File in the request!"}, 400 file = request.files['file'] if file.filename == '': return {'message': "No File selected!"}, 400 if not File.allowed_file(file.filename): return {'message': "File type not allowed! Only CSV files are allowed!"}, 400 # Create dictionary for upload_info_store upload_info_dict = {} upload_info_dict['uuid'] = uuid_str upload_info_dict['userid'] = config.USER_ID upload_info_dict['filename'] = file.filename upload_info_dict['type'] = data['registration_type'] upload_info_dict['timestamp'] = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') upload_info_dict['status'] = "csv_file_uploaded" # Also set REGISTRATION_NAME as filename in config file config.REGISTRATION_NAME = file.filename # Create dictionaries for device_store, validation_store, device_status_store converted_json, converted_validation_json, converted_status_json = File.csv_to_json(file) # Enter data into the database store device_store if TokensModel.find_by_uuid(uuid_str, "device_store"): return {'message': "Request with UUID: '{}' already exists.".format(uuid)}, 400 try: TokensModel.insert(uuid_str, converted_json, "device_store") except Exception as e: print(e) return {"message": "Data insert operation device_store failed!"}, 500 # Enter data into the database store account_validation if TokensModel.find_by_uuid(uuid_str, "validation_store"): return {'message': "Request with UUID: '{}' already exists.".format(uuid)}, 400 try: TokensModel.insert(uuid_str, converted_validation_json, "validation_store") except Exception as e: print(e) return {"message": "Data insert operation validation_store failed!"}, 500 # Enter data into the database store device_status_store if TokensModel.find_by_uuid(uuid_str, "device_status_store"): return {'message': "Request with UUID: '{}' already exists.".format(uuid)}, 400 try: TokensModel.insert(uuid_str, converted_status_json, "device_status_store") except Exception as e: print(e) return {"message": "Data insert operation device_status_store failed!"}, 500 try: if data['registration_type'] == 'slr': TokensModel.insert(uuid_str, converted_json, "slr_request_code_tbl") except Exception as e: print (e) return {"message": "Data insert operation slr_request_code_tbl failed!"}, 500 # Enter data into the database store upload_info_store if TokensModel.find_by_uuid(uuid_str, "upload_info_store"): return {'message': "Request with UUID: '{}' already exists.".format(uuid)}, 400 try: TokensModel.insert(uuid_str, [upload_info_dict], "upload_info_store") except Exception as e: print(e) return {"message": "Data insert operation failed!"}, 500 config.NO_OF_DEVICES = len(converted_json) config.NO_OF_PAGES = ceil(len(converted_json)/10) new_request = { 'uuid': uuid_str, 'totalpages': config.NO_OF_PAGES, 'message': 'File is uploaded!' } # For debugging print(new_request) if TokensModel.find_by_uuid(uuid_str, "validation_store"): print("Printed validation_store") if TokensModel.find_by_uuid(uuid_str, "device_status_store"): print("Printed device_status_store") if TokensModel.find_by_uuid(uuid_str, "upload_info_store"): print("Printed upload_info_store") return new_request, 201