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_authorize_information(cls, device_ip, username, password, cli,
                                   authz_info, tftp_server, tftp_loc, uuid):
        s = slr("", "", "")
        client = tftpy.TftpClient(tftp_server, 69)
        file_name = device_ip + secrets.token_hex(5) + extension
        dest_file = dest_dir + file_name

        try:
            f = open(dest_file, "w+")
            print(authz_info)
            f.write(authz_info)
            f.close()
            client.upload(tftp_loc + file_name, dest_file)
            cli.append("lic smart reservation install file tftp://" +
                       tftp_server + "/" + tftp_loc + file_name)
            print(cli)
            slrauthzswitch.config_commands(device_ip, username, password, cli)
            s.update_status(slr_req_tbl, uuid, device_ip, s_done, step)
        except Exception as e:
            print(e)
            s.update_status(slr_req_tbl, uuid, device_ip,
                            str(e).split(":")[0], step)

        rows = s.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")
        del (s)
    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
Esempio n. 4
0
    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
Esempio n. 5
0
    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
Esempio n. 6
0
    def send_authorize_information(cls, device_ip, username, password, cli,
                                   authz_info, tftp_server, tftp_loc, uuid):
        s = slr("", "", "")
        try:
            logger.info(
                "Trying to connect to tftp server:{}".format(tftp_server))
            client = tftpy.TftpClient(tftp_server, 69)
            file_name = device_ip + ".txt"
            dest_file = dest_dir + file_name
            try:
                f = open(dest_file, "w+")
                logger.info(authz_info)
                f.write(authz_info)
                f.close()
                logger.info("Trying to upload file:{}".format(file_name))
                client.upload(file_name, dest_file)
                cli.append("lic smart reservation install file tftp://" +
                           tftp_server + "/" + file_name)
                logger.info(cli)
                SlrAuthSwitch.config_commands(device_ip, username, password,
                                              cli)
                #if dlc_status_rows is not empty means dlc is performed
                dlc_status_rows = TokensModel.get_dlc_status(uuid, device_ip)
                if dlc_status_rows:
                    dlc_status = dlc_status_rows[0][2]
                    if dlc_status == "dlc_convert_success":
                        s.update_status(SLR_REQUEST_CODE_TABLE_NAME, uuid,
                                        device_ip, "DLC Success and Completed",
                                        "step3")
                    else:
                        s.update_status(SLR_REQUEST_CODE_TABLE_NAME, uuid,
                                        device_ip,
                                        "DLC Failed and SLR Successful",
                                        "step3")
                else:
                    s.update_status(SLR_REQUEST_CODE_TABLE_NAME, uuid,
                                    device_ip, "Completed", "step3")
            except Exception as e:
                print("file upload failed:", e)
                logger.info("Failed uploading file:{}".format(file_name))
                s.update_status(SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip,
                                str(e).split(":")[0], "step3")
        except Exception as e:
            logger.info(
                "Failure connecting to tftp server:{}".format(tftp_server))
            print("Connection to tftp server failed:", e)

        rows = s.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")
        del s
Esempio n. 7
0
 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
Esempio n. 8
0
    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
Esempio n. 9
0
    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
Esempio n. 10
0
    def get_cssm_response(cls, domain_name, va_name, oauthToken, device_ip, uuid):
        sl_token_dict = {}
        sl_token_dict['sl_token'] = ''
        sl_token_dict['error'] = ''
        final_msg = ""


        url = url_prefix.format(domain_name, va_name)
        print("Value of the rest api url is ")
        print(url)

        headers = {
            "Authorization": "Bearer " + oauthToken,
            "Content-Type": "application/json",
            "Cache-Control": "no-cache"
        }
        payload = "{\"description\": \"SLR Token Automation\",\"expiresAfterDays\": 30,\"exportControlled\":" \
                  " \"Not Allowed\"}"
        s = slr("", "", "")
        try:
            i = 0
            status = s_done
            val = s.find_by_uuid_ipaddr(uuid, slr_table, device_ip)
            if val[0][2] != s_done:
                print(val[0][2])
                print(val)
                s.update_status(slr_table, uuid, device_ip, "Error in previous step", step)
                if (len(rows) == 0):
                    response_update = {}
                    response_update['status'] = resp_status_complete
                    TokensModel.update(uuid, response_update, "upload_info_store")
                del(s)
                return
            tags = val[0][11]
            first = 1
            licenses = []
            try:
                license_count = s.get_license_count(val[0]).split(delim);
                print(license_count)
                for tag in tags.split(delim):
                    try:
                        licenses.append({ "entitlementTag":tag, "quantity":license_count[i], "precedence":"LONGEST_TERM_FIRST"})
                    except Exception as e:
                        s.update_status(slr_table, uuid, device_ip, "License count and licenses are not set properly", step)
                        print(e)
                        rows = s.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")
                        del(s)
                    i = i + 1
            except Exception as e:
                s.update_status(slr_table, uuid, device_ip, "License is not seperated by spaces", step)
                rows = s.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

            body = {"reservationRequests":[{ "reservationCode":val[0][5], "reservationType":"SPECIFIC", "licenses":licenses}]}
            print("Reservation request for uuid " + uuid + " for deive with ip " +  device_ip)
            print("-----------------------------------------------------------------------------")
            print(headers)
            print(body)
            print("-----------------------------------------------------------------------------")
            a = json.dumps(body)
            response = requests.request("POST", url, data=a, headers=headers, timeout=10)
            print(response.content.decode())
            if val[0][3] == s_done:
                print("Already marked step as completed, don't proceed further. This can happen when rest call takes time. It is more of a race condition, seen once in my testing. Handling for the same")
                return
            try:
                msg = response.json()
                print(msg['status'])
                if msg['status'] == "ERROR":
                    status = s_fail + response.json()['statusMessage']
                else:
                    status = s_done
            except Exception as e:
                print(e)
                status = s_fail + "Response from cssm failed"
            
            s.update_status(slr_table, uuid, device_ip, status, step)
            try:
                print(msg)
                print(msg['authorizationCodes'][0])
                if (1 == first) :
                    first = 0
                else:
                    final_msg = final_msg + delim
                print(msg['authorizationCodes'][0]['authorizationCode'])
                final_msg = final_msg + msg['authorizationCodes'][0]['authorizationCode'] 
            except Exception as e:
                print(e)
                s.update_authz_response_code(slr_req_tbl, uuid, device_ip, 'Error in getting response from cssm')
            s.update_authz_response_code(slr_req_tbl, uuid, device_ip, final_msg)
        except Exception as e:
            print(e)

        rows = s.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")
        del(s)
Esempio n. 11
0
    def get_cssm_response(cls, domain_name, va_name, oauthToken, device_ip, uuid):
        final_msg = ""
        url = URL_PREFIX.format(domain_name, va_name)
        logger.info("Value of the rest api url is ")
        logger.info(url)

        headers = {
            "Authorization": "Bearer " + oauthToken,
            "Content-Type": "application/json",
            "Cache-Control": "no-cache"
        }
        s = slr("", "", "")
        try:
            i = 0
            val = s.find_by_uuid_ipaddr(uuid, slr_table_name, device_ip)
            if val[0][2] != "Completed":
                logger.info(val[0][2])
                logger.info(val)
                logger.error("Error in previous step")
                s.update_status(slr_table_name, uuid, device_ip, "Error in previous step", "step2")
                rows = s.find_by_step_status(SLR_REQUEST_CODE_TABLE_NAME, uuid, "Started", "step2")
                if len(rows) == 0:
                    # Updating the response status to Step 3 Complete
                    response_update = {'status': "S3c"}
                    TokensModel.update(uuid, response_update, "upload_info_store")
                return
            tags = val[0][11]
            licenses = []
            try:
                license_count = s.get_license_count(val[0]).split(delim)
                logger.info(license_count)
                for tag in tags.split(delim):
                    if int(license_count[i]) > 0:
                        try:
                            licenses.append(
                                {"entitlementTag": tag, "quantity": license_count[i], "precedence":
                                    "LONGEST_TERM_FIRST"})
                        except Exception as e:
                            s.update_status(slr_table_name, uuid, device_ip,
                                            "License count and licenses are not set properly",
                                            "step2")
                            print(e)
                            logger.error("License count and licenses are not set properly", exc_info=True)
                            rows = s.find_by_step_status(SLR_REQUEST_CODE_TABLE_NAME, uuid, "Started", "step2")
                            if len(rows) == 0:
                                # Updating the response status to Step 3 Complete
                                response_update = {'status': "S3c"}
                                TokensModel.update(uuid, response_update, "upload_info_store")
                    i = i + 1
            except Exception as e:
                print(e)
                s.update_status(slr_table_name, uuid, device_ip, "License is not separated by spaces", "step2")
                logger.error("License is not separated by spaces", exc_info=True)
                rows = s.find_by_step_status(SLR_REQUEST_CODE_TABLE_NAME, uuid, "Started", "step2")
                if len(rows) == 0:
                    # Updating the response status to Step 3 Complete
                    response_update = {'status': "S3c"}
                    TokensModel.update(uuid, response_update, "upload_info_store")
                return

            body = {"reservationRequests": [
                {"reservationCode": val[0][5], "reservationType": "SPECIFIC", "licenses": licenses}]}
            logger.info("Reservation request for uuid " + uuid + " for device with ip " + device_ip)
            logger.info(headers)
            logger.info(body)
            a = json.dumps(body)
            # New call added for response with retries
            response = SlrContactCSSM.send_post_with_retries(url, a, headers, 30)
            # response = requests.request("POST", url, data=a, headers=headers, timeout=10)
            logger.info("Now printing response.json & contents.decode as per old call...")
            logger.info(response.json())
            logger.info(response.content.decode())
            if val[0][3] == "Completed":
                logger.info("Already marked step as completed, don't proceed further. This can happen when rest call \
                            takes time. It is more of a race condition, seen once in my testing. Handling for the same")
                return
            try:
                msg = response.json()
                logger.info(msg['status'])
                if msg['status'] == "ERROR":
                    status = "Fail: " + response.json()['statusMessage']
                else:
                    status = "Completed"
            except Exception as e:
                print(e)
                status = "Fail: " + "Response from cssm failed"
                logger.error(status, exc_info=True)
            s.update_status(slr_table_name, uuid, device_ip, status, "step2")
            try:
                logger.info(msg)
                logger.info(msg['authorizationCodes'][0])
                print(msg)
                logger.info(msg['authorizationCodes'][0]['authorizationCode'])
                final_msg = final_msg + msg['authorizationCodes'][0]['authorizationCode']
                print(final_msg)
            except Exception as e:
                print(e)
                s.update_authz_response_code(SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip, 'Error in getting response '
                                                                                           'from cssm')
                logger.error("Error in getting response from CSSM", exc_info=True)
            s.update_authz_response_code(SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip, final_msg)
        except Exception as e:
            logger.info("@@@@@ Printing Exception from main CSSM reserve license call...")
            print(e)
            logger.error('Error! Code: {c}, Message, {m}'.format(c=type(e).__name__, m=str(e)))
            # Following code is added to catch HTTP ConnectionError (Wrong URL etc)
            status = "Fail: " + str(type(e).__name__)
            s.update_authz_response_code(SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip, 'Error in getting response '
                                                                                       'from cssm')
            s.update_status(slr_table_name, uuid, device_ip, status, "step2")

        rows = s.find_by_step_status(SLR_REQUEST_CODE_TABLE_NAME, uuid, "Started", "step2")
        rows_completed = s.find_by_step_status(SLR_REQUEST_CODE_TABLE_NAME, uuid, "Completed", "step2")
        if (len(rows) == 0) and (len(rows_completed) != 0):
            # Updating the response status to Step 3 Complete
            response_update = {'status': "S3c"}
            TokensModel.update(uuid, response_update, "upload_info_store")
Esempio n. 12
0
    def execute_cli_wrapper(cls, device_ip, username, password, cli, uuid):
        print("Value of username is " + username + " password " + password)
        s = slr("", "", "")
        s.update_req_token(slr_req_tbl, uuid, device_ip, "")
        try:
            lic_rows = s.find_by_uuid_ipaddr(uuid, slr_req_tbl, device_ip)
            license = s.get_license(lic_rows[0])
            if license is None:
                output = slrrequestcode.config_commands(
                    device_ip, username, password, cli)
                print("Value of the output is " + output)
                s.update_req_token(slr_req_tbl, uuid, device_ip,
                                   output.split('\n')[-2])
                output = slrrequestcode.config_commands(
                    device_ip, username, password, req_udi_command)
                print(output)
                udi = (output.split('\n'))
                print("Value of udi is " + str(udi))
                first = 1
                first_count = 1
                result = ""
                lic_count_string = ""
                result_lic_count = ""
                for entitlement_tag in udi:
                    print(entitlement_tag)
                    if entitlement_tag_string in entitlement_tag:
                        if first:
                            lic = entitlement_tag.split(":")[-1].replace(
                                " ", "")
                            first = 0
                        else:
                            lic = entitlement_tag.split(":")[-1]
                        result = result + lic
                    if count_string in entitlement_tag:
                        if first_count:
                            lic_count_string = entitlement_tag.split(
                                ":")[-1].replace(" ", "")
                            first_count = 0
                        else:
                            lic_count_string = entitlement_tag.split(":")[-1]
                        result_lic_count = result_lic_count + lic_count_string
                print("Value of entitlement tag is " + result)
                print("Value of count of licenses is " + result_lic_count)
                s.update_entitlement_tag(slr_req_tbl, uuid, device_ip, result)
                s.update_license_count(slr_req_tbl, uuid, device_ip,
                                       result_lic_count)
            else:
                output = slrrequestcode.config_commands(
                    device_ip, username, password, cli)
                print("Value of the output is " + output)
                s.update_req_token(slr_req_tbl, uuid, device_ip,
                                   output.split('\n')[-2])
                s.update_entitlement_tag(slr_req_tbl, uuid, device_ip, license)

            s.update_status(slr_req_tbl, uuid, device_ip, s_done, step)
        except Exception as e:
            print(e)
            s.update_status(slr_req_tbl, uuid, device_ip,
                            str(e).split(":")[0], step)

        rows = s.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")
        del (s)
Esempio n. 13
0
    def execute_cli_wrapper(cls, device_ip, username, password, cli, uuid, sa,
                            va, domain):
        logger.info("Value of username is " + username + " password " +
                    password)
        config.ERROR, sw_ver_str, device_type_dict = Helper.check_dlc_required(
            device_ip, uuid, sa, va, domain, "x", username, password)
        dlc_required = TokensModel.select_dlc(uuid)
        logger.info("DLC_Required Flag set to:" + dlc_required)
        if not config.ERROR:
            if sw_ver_str and device_type_dict['device_type'] is not None:
                s = slr("", "", "")
                s.update_req_token(SLR_REQUEST_CODE_TABLE_NAME, uuid,
                                   device_ip, "")
                result = ""
                result_lic_count = ""
                try:
                    if dlc_required == "True":
                        dlc_process_status = SlrRequestCode.check_dlc_status_on_device(
                            device_ip, username, password, dlc_proc_stat_cmd)
                        if dlc_process_status != '' and dlc_process_status == 'Not Complete':
                            dlc_conversion_data = SlrRequestCode.execute_dlc_cli(
                                device_ip, username, password,
                                dlc_conversion_command)
                            if dlc_conversion_data != '':
                                logger.info("DLC_conversion_data")
                                logger.info(type(dlc_conversion_data))
                                logger.info(dlc_conversion_data)
                                SlrRequestCode.generate_dlc_data_dict(
                                    device_ip, dlc_conversion_data, va)
                                SlrRequestCode.insert_dlc_data_to_table(
                                    uuid, device_ip, dlc_conversion_data)
                    lic_rows = s.find_by_uuid_ipaddr(
                        uuid, SLR_REQUEST_CODE_TABLE_NAME, device_ip)
                    device_license = s.get_license(lic_rows[0])
                    if device_license is None:
                        output = SlrRequestCode.config_commands(
                            device_ip, username, password, cli)
                        logger.info("Value of the output is " + output)
                        req_code = output.split('\n')[-2]
                        if req_code.find("Request code:") != -1:
                            data = req_code.split("code: ")
                            req_code = data[1]
                        s.update_req_token(SLR_REQUEST_CODE_TABLE_NAME, uuid,
                                           device_ip, req_code)
                        output = SlrRequestCode.config_commands(
                            device_ip, username, password, req_udi_command)
                        logger.info(output)
                        udi = (output.split('\n'))
                        logger.info("Value of udi is " + str(udi))
                        first = 1
                        first_count = 1
                        for entitlement_tag in udi:
                            logger.info(entitlement_tag)
                            if "Entitlement tag" in entitlement_tag:
                                if first:
                                    lic = entitlement_tag.split(
                                        ":")[-1].replace(" ", "")
                                    first = 0
                                else:
                                    lic = entitlement_tag.split(":")[-1]
                                result = result + lic
                            if "Count:" in entitlement_tag:
                                if first_count:
                                    lic_count_string = entitlement_tag.split(
                                        ":")[-1].replace(" ", "")
                                    first_count = 0
                                else:
                                    lic_count_string = entitlement_tag.split(
                                        ":")[-1]
                                result_lic_count = result_lic_count + lic_count_string
                        logger.info("Value of entitlement tag is " + result)
                        logger.info("Value of count of licenses is " +
                                    result_lic_count)
                        # If we don't get lic ent tag and count from the device, indicate error
                        if (result == "") or (result_lic_count == ""):
                            result = "LIC_ENT_TAG_NOT_FOUND"
                            result_lic_count = "LIC_COUNT_NOT_FOUND"
                        s.update_entitlement_tag(SLR_REQUEST_CODE_TABLE_NAME,
                                                 uuid, device_ip, result)
                        s.update_license_count(SLR_REQUEST_CODE_TABLE_NAME,
                                               uuid, device_ip,
                                               result_lic_count)
                    else:
                        output = SlrRequestCode.config_commands(
                            device_ip, username, password, cli)
                        logger.info("Value of the output is " + output)
                        req_code = output.split('\n')[-2]
                        if req_code.find("Request code:") != -1:
                            data = req_code.split("code: ")
                            req_code = data[1]
                        s.update_req_token(SLR_REQUEST_CODE_TABLE_NAME, uuid,
                                           device_ip, req_code)
                        s.update_entitlement_tag(SLR_REQUEST_CODE_TABLE_NAME,
                                                 uuid, device_ip,
                                                 device_license)
                    # If we don't get lic ent tag and count from the device, it is considered as failed
                    if (result == "LIC_ENT_TAG_NOT_FOUND") or (
                            result_lic_count == "LIC_COUNT_NOT_FOUND"):
                        s.update_status(
                            SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip,
                            "License details not found from the "
                            "device", "step1")
                    else:
                        s.update_status(SLR_REQUEST_CODE_TABLE_NAME, uuid,
                                        device_ip, "Completed", "step1")
                except Exception as e:
                    print(e)
                    s.update_status(SLR_REQUEST_CODE_TABLE_NAME, uuid,
                                    device_ip,
                                    str(e).split(":")[0], "step1")
                    # Added 04/16/19 - As export button and get auth key button is enabled eventhough
                    # connection to device timed-out
                    # Updating response status to Step 2 failed
                    response_update = {'status': "S2f"}
                    TokensModel.update(uuid, response_update,
                                       "upload_info_store")

                rows = s.find_by_step_status(SLR_REQUEST_CODE_TABLE_NAME, uuid,
                                             "Started", "step1")
                rows_completed = s.find_by_step_status(
                    SLR_REQUEST_CODE_TABLE_NAME, uuid, "Completed", "step1")
                if (len(rows) == 0) and (len(rows_completed) != 0):
                    # Updating the response status to Step 2 completed
                    response_update = {'status': "S2c"}
                    TokensModel.update(uuid, response_update,
                                       "upload_info_store")
                del s
            else:
                logger.info("==>> Unsupported Network Device type...")
                response = {
                    'ipaddr': device_ip,
                    'username': username,
                    'password': password,
                    'sa_name': sa,
                    'va_name': va,
                    'domain': domain,
                    'status': 'Unsupported Device PID!'
                }
                config.ERROR = True
                TokensModel.update(uuid, response, "device_status_store")

        else:
            logger.error("No connectivity to the device...")
            response_update = {
                'ipaddr': device_ip,
                'username': username,
                'password': password,
                'sa_name': sa,
                'va_name': va,
                'domain': domain,
                'status': 'No Connectivity!'
            }
            config.ERROR = True
            TokensModel.update(uuid, response_update, "device_status_store")
Esempio n. 14
0
    def execute_cli_wrapper(cls, device_ip, username, password, cli, uuid):
        print("Value of username is " + username + " password " + password)
        s = slr("", "", "")
        s.update_req_token(slr_req_tbl, uuid, device_ip, "")
        result = ""
        result_lic_count = ""
        try:
            lic_rows = s.find_by_uuid_ipaddr(uuid, slr_req_tbl, device_ip)
            license = s.get_license(lic_rows[0])
            if license is None:
                output = slrrequestcode.config_commands(
                    device_ip, username, password, cli)
                print("Value of the output is " + output)
                s.update_req_token(slr_req_tbl, uuid, device_ip,
                                   output.split('\n')[-2])
                output = slrrequestcode.config_commands(
                    device_ip, username, password, req_udi_command)
                print(output)
                udi = (output.split('\n'))
                print("Value of udi is " + str(udi))
                first = 1
                first_count = 1
                # result = ""
                # result_lic_count = ""
                for entitlement_tag in udi:
                    print(entitlement_tag)
                    if entitlement_tag_string in entitlement_tag:
                        if first:
                            lic = entitlement_tag.split(":")[-1].replace(
                                " ", "")
                            first = 0
                        else:
                            lic = entitlement_tag.split(":")[-1]
                        result = result + lic
                    if count_string in entitlement_tag:
                        if first_count:
                            lic_count_string = entitlement_tag.split(
                                ":")[-1].replace(" ", "")
                            first_count = 0
                        else:
                            lic_count_string = entitlement_tag.split(":")[-1]
                        result_lic_count = result_lic_count + lic_count_string
                print("Value of entitlement tag is " + result)
                print("Value of count of licenses is " + result_lic_count)
                # If we don't get lic ent tag and count from the device, indicate error
                if (result is "") or (result_lic_count is ""):
                    result = "LIC_ENT_TAG_NOT_FOUND"
                    result_lic_count = "LIC_COUNT_NOT_FOUND"
                s.update_entitlement_tag(slr_req_tbl, uuid, device_ip, result)
                s.update_license_count(slr_req_tbl, uuid, device_ip,
                                       result_lic_count)
            else:
                output = slrrequestcode.config_commands(
                    device_ip, username, password, cli)
                print("Value of the output is " + output)
                s.update_req_token(slr_req_tbl, uuid, device_ip,
                                   output.split('\n')[-2])
                s.update_entitlement_tag(slr_req_tbl, uuid, device_ip, license)
            # If we don't get lic ent tag and count from the device, it is considered as failed
            if (result is "LIC_ENT_TAG_NOT_FOUND") or (result_lic_count is
                                                       "LIC_COUNT_NOT_FOUND"):
                s.update_status(slr_req_tbl, uuid, device_ip,
                                "License details not found from the device",
                                step)
            else:
                s.update_status(slr_req_tbl, uuid, device_ip, s_done, step)
        except Exception as e:
            print(e)
            s.update_status(slr_req_tbl, uuid, device_ip,
                            str(e).split(":")[0], step)
            # Added 04/16/19 - As export button and get auth key button is enabled eventhough
            # connection to device timed-out
            response_update = {}
            response_update['status'] = resp_status_failed
            TokensModel.update(uuid, response_update, "upload_info_store")

        rows = s.find_by_step_status(slr_req_tbl, uuid, s_start, step)
        rows_completed = s.find_by_step_status(slr_req_tbl, uuid, s_done, step)
        if (len(rows) == 0) and (len(rows_completed) != 0):
            response_update = {}
            response_update['status'] = resp_status_complete
            TokensModel.update(uuid, response_update, "upload_info_store")
        del (s)
Esempio n. 15
0
    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
Esempio n. 16
0
    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}
Esempio n. 17
0
    def check_dlc_required(cls, device_ip, uuid, sa, va, domain, oauth_token,
                           username, password):
        pid_str = None
        try:
            # get device verison
            sw_version = Helper.check_version(device_ip, username, password)
            sw_ver_str = sw_version['version']
            logger.info(" ++++++++ SW VERSION STRING: {}".format(sw_ver_str))
        except Exception as e:
            logger.error(e)
            logger.error(
                "====>>>>    ERROR: Unable to fetch device SW Version! {}".
                format(device_ip))
            response = {
                'ipaddr': device_ip,
                'username': username,
                'password': password,
                'sa_name': sa,
                'va_name': va,
                'domain': domain,
                'status': sw_version['error']
            }
            config.ERROR = True
            TokensModel.update(uuid, response, "device_status_store")

        try:
            # get device PID
            # Start here define empty PID dctionary in case we are not able to get thru check_pid method
            pid = Helper.check_pid(device_ip, username, password)
            pid_str = pid['pid']
            logger.info(" ++++++++ PID DICT: {}".format(
                json.dumps(pid, indent=4)))
            logger.info(" ++++++++ PID STRING: {}".format(pid_str))
            # device_type_dict = Tokens.check_device_type(pid_str)
        except Exception as e:
            logger.error(e)
            logger.error(
                "====>>>>    ERROR: Unable to fetch device PID! {}".format(
                    device_ip))
            response = {
                'ipaddr': device_ip,
                'username': username,
                'password': password,
                'sa_name': sa,
                'va_name': va,
                'domain': domain,
                'status': pid['error']
            }
            config.ERROR = True
            TokensModel.update(uuid, response, "device_status_store")

        try:
            # check if PID is found and if it is belongs to a router or a switch
            device_type_dict = Helper.check_device_type(pid_str, uuid)
            logger.info(" ++++++++ device_type_dict DICT: {}".format(
                json.dumps(device_type_dict, indent=4)))
            logger.info(" ++++++++ DEVICE STRING: {}".format(
                device_type_dict['device_type']))
        except Exception as e:
            logger.error(
                "====>>>>    ERROR: Unable to find PID! Check config.yaml file! {}"
                .format(device_ip))
            logger.error('Error! Code: {c}, Message, {m}'.format(
                c=type(e).__name__, m=str(e)))
            status_str = "Unable to parse config.yaml file! Check file contents! ERROR: " + type(e).__name__ \
                         + " - " + str(e)
            response = {
                'ipaddr': device_ip,
                'username': username,
                'password': password,
                'sa_name': sa,
                'va_name': va,
                'domain': domain,
                'status': status_str
            }
            config.ERROR = True
            TokensModel.update(uuid, response, "device_status_store")
        return config.ERROR, sw_ver_str, device_type_dict