def api_call(url, data=None, calltype="get", headers=None, save_error=True): if API_TOKEN is None: set_token() api_auth_header = { "Authorization": "Bearer " + API_TOKEN, } call = getattr(requests, calltype) try: if headers is not None: headers.update(api_auth_header) if headers["content-type"] == "application/json": r = call(url, verify=False, data=json.dumps(data), headers=headers) else: r = call(url, verify=False, data=data, headers=headers) else: r = call(url, verify=False, headers=api_auth_header, data=data) except requests.exceptions.ConnectionError: print("Error connecting to Rockstor. Is it running?") return {} if r.status_code == 404: msg = "Invalid api end point: %s" % url raise RockStorAPIException(detail=msg) if r.status_code != 200: try: error_d = json.loads(r.text) if settings.DEBUG is True and save_error is True: cur_time = str(int(time.time())) err_file = "/tmp/err-%s.html" % cur_time with open(err_file, "w") as efo: for line in r.text.split("\n"): efo.write("%s\n" % line) print("Error detail is saved at %s" % err_file) if "detail" in error_d: if (error_d["detail"] == "Authentication credentials were not provided." ): # noqa E501 set_token() return api_call( url, data=data, calltype=calltype, headers=headers, save_error=save_error, ) raise RockStorAPIException(detail=error_d["detail"]) except ValueError: raise RockStorAPIException(detail="Internal Server Error") r.raise_for_status() try: ret_val = r.json() except ValueError: ret_val = {} return ret_val
def api_call(self, url, data=None, calltype='get', headers=None, save_error=True): if (self.access_token is None or (time.time() > self.expiration)): self.set_token() api_auth_header = { 'Authorization': 'Bearer ' + self.access_token, } call = getattr(requests, calltype) url = ('%s/api/%s' % (self.url, url)) try: if (headers is not None): headers.update(api_auth_header) if (headers['content-type'] == 'application/json'): r = call(url, verify=False, data=json.dumps(data), headers=headers) else: r = call(url, verify=False, data=data, headers=headers) else: r = call(url, verify=False, headers=api_auth_header, data=data) except requests.exceptions.ConnectionError: print('Error connecting to Rockstor. Is it running?') raise if (r.status_code == 404): msg = ('Invalid api end point: %s' % url) raise RockStorAPIException(detail=msg) if (r.status_code != 200): try: error_d = json.loads(r.text) if (settings.DEBUG is True and save_error is True): cur_time = str(int(time.time())) err_file = '/tmp/err-%s.html' % cur_time with open(err_file, 'w') as efo: for line in r.text.split('\n'): efo.write('%s\n' % line) print('Error detail is saved at %s' % err_file) if ('detail' in error_d): if (error_d['detail'] == 'Authentication credentials were not provided.'): set_token() return api_call(url, data=data, calltype=calltype, headers=headers, save_error=save_error) raise RockStorAPIException(detail=error_d['detail']) except ValueError, e: raise RockStorAPIException(detail='Internal Server Error: %s' % e.__str__()) r.raise_for_status()
def api_call(url, data=None, calltype='get', headers=None, save_error=True): if (API_TOKEN is None): set_token() api_auth_header = {'Authorization': 'Bearer ' + API_TOKEN, } call = getattr(requests, calltype) try: if (headers is not None): headers.update(api_auth_header) if (headers['content-type'] == 'application/json'): r = call(url, verify=False, data=json.dumps(data), headers=headers) else: r = call(url, verify=False, data=data, headers=headers) else: print ('api auth headers = %s' % api_auth_header) print ('url = %s' % url) print ('data = %s' % data) r = call(url, verify=False, headers=api_auth_header, data=data) except requests.exceptions.ConnectionError: print('Error connecting to Rockstor. Is it running?') return {} if (r.status_code == 404): msg = ('Invalid api end point: %s' % url) print msg raise RockStorAPIException(detail=msg) if (r.status_code != 200): print r.text try: error_d = json.loads(r.text) #if ('detail' in error_d): # raise RockStorAPIException(detail=error_d['detail']) if (settings.DEBUG is True and save_error is True): cur_time = str(int(time.time())) err_file = '/tmp/err-%s.html' % cur_time with open(err_file, 'w') as efo: for line in r.text.split('\n'): efo.write('%s\n' % line) print('Error detail is saved at %s' % err_file) except ValueError: raise RockStorAPIException(detail='Internal Server Error') r.raise_for_status() try: ret_val = r.json() except ValueError: ret_val = {} return ret_val
def handle_exception(e, request, e_msg=None): """ if e_msg is provided, exception is raised with that string. This is useful for optionally humanizing the message. Otherwise, error from the exception object is used. """ if (e_msg is not None): e_msg = '%s. Lower level exception: %s' % (e_msg, e.__str__()) logger.error(e_msg) else: e_msg = e.__str__() logger.exception('exception: %s' % e.__str__()) logger.debug('Current Rockstor version: %s' % version) raise RockStorAPIException(detail=e_msg, trace=traceback.format_exc())
def handle_exception(e, request, e_msg=None, status_code=500): """ if e_msg is provided, exception is raised with that string. This is useful for optionally humanizing the message. Otherwise, error from the exception object is used. """ if e_msg is not None: e_msg = "({}). Lower level exception: ({}).".format(e_msg, e.__str__()) logger.error(e_msg) else: e_msg = e.__str__() logger.exception("Exception: {}".format(e.__str__())) logger.debug("Current Rockstor version: {}".format(version)) raise RockStorAPIException(status_code=status_code, detail=e_msg, trace=traceback.format_exc())
def handle_exception(e, request, e_msg=None): """ if e_msg is provided, exception is raised with that string. This is useful for optionally humanizing the message. Otherwise, error from the exception object is used. """ if (e_msg is not None): logger.error(e_msg) else: e_msg = e.__str__() logger.error('request path: %s method: %s data: %s' % (request.path, request.method, request.DATA)) logger.exception('exception: %s' % e.__str__()) run_command(['/usr/bin/tar', '-c', '-z', '-f', settings.ROOT_DIR + 'src/rockstor/logs/error.tgz', settings.ROOT_DIR + 'var/log']) raise RockStorAPIException(detail=e_msg)
def handle_exception(e, request, e_msg=None): """ if e_msg is provided, exception is raised with that string. This is useful for optionally humanizing the message. Otherwise, error from the exception object is used. """ if (e_msg is not None): e_msg = '%s. Lower level exception: %s' % (e_msg, e.__str__()) logger.error(e_msg) else: e_msg = e.__str__() logger.error('request path: %s method: %s data: %s' % (request.path, request.method, request.data)) logger.exception('exception: %s' % e.__str__()) logger.debug('Current Rockstor version: %s' % version) fpath = '%ssrc/rockstor/logs/error.tgz' % settings.ROOT_DIR logdir = '%svar/log' % settings.ROOT_DIR run_command(['/usr/bin/tar', '-c', '-z', '-f', fpath, logdir], throw=False) raise RockStorAPIException(detail=e_msg)
def _toggle_repos(self, on="stable", off="testing", password=None): # toggle between testing and stable repos ncd = settings.UPDATE_CHANNELS[on] fcd = settings.UPDATE_CHANNELS[off] try: offo = UpdateSubscription.objects.get(name=fcd["name"]) offo.status = "inactive" offo.save() switch_repo(offo, on=False) except UpdateSubscription.DoesNotExist: pass try: ono = UpdateSubscription.objects.get(name=ncd["name"]) except UpdateSubscription.DoesNotExist: appliance = Appliance.objects.get(current_appliance=True) ono = UpdateSubscription( name=ncd["name"], description=ncd["description"], url=ncd["url"], appliance=appliance, status="active", ) ono.password = password status, text = repo_status(ono) ono.status = status ono.save() if status == "inactive": e_msg = ("Activation code ({}) could not be authorized for your " "appliance ({}). Verify the code and try again. If the " "problem persists, email [email protected] with this " "message.").format(ono.password, appliance.uuid) raise RockStorAPIException(status_code=400, detail=e_msg) if status != "active": e_msg = ( "Failed to activate subscription. Status code: {} details: {}" ).format(status, text) raise Exception(e_msg) switch_repo(ono) return ono
def _toggle_repos(self, on='stable', off='testing', password=None): # toggle between testing and stabel repos ncd = settings.UPDATE_CHANNELS[on] fcd = settings.UPDATE_CHANNELS[off] try: offo = UpdateSubscription.objects.get(name=fcd['name']) offo.status = 'inactive' offo.save() switch_repo(offo, on=False) except UpdateSubscription.DoesNotExist: pass try: ono = UpdateSubscription.objects.get(name=ncd['name']) except UpdateSubscription.DoesNotExist: appliance = Appliance.objects.get(current_appliance=True) ono = UpdateSubscription(name=ncd['name'], description=ncd['description'], url=ncd['url'], appliance=appliance, status='active') ono.password = password status, text = repo_status(ono) ono.status = status ono.save() if (status == 'inactive'): e_msg = ( 'Activation code({}) could not be authorized for your ' 'appliance({}). Verify the code and try again. If the problem' ' persists, email [email protected] with this ' 'message').format(ono.password, appliance.uuid) raise RockStorAPIException(status_code=400, detail=e_msg) if (status != 'active'): e_msg = ('Failed to activate subscription. status code: ' '%s details: %s' % (status, text)) raise Exception(e_msg) switch_repo(ono) return ono
def handle_exception(e, request): logger.debug('request data: %s' % (request.DATA)) logger.exception('exception') raise RockStorAPIException(detail=e.__str__())