Example #1
0
    def delete_request(self, service, req_args):
        """ This method, forms the http DELETE request, applies on the netscaler.
        Reads the response from the netscaler and converts it to base response.
    
        Parameters:
			service - nitro_service object.
        	req_args
        
        Returns:
			Array of requested resources.
        
        Throws:
			Exception
        """
        try:
            ipaddress = service.ipaddress
            version = service.version
            sessionid = service.sessionid
            objtype = self.__class__.get_object_type()
            protocol = service.protocol

            # build URL
            urlstr = protocol + "://" + ipaddress + "/nitro/" + version + "/config/" + objtype

            name = self._get_object_name()
            if (name and len(name) > 0):
                urlstr = urlstr+"/"+nitro_util.encode(nitro_util.encode(name))

            if(req_args or service.warning):
                urlstr = urlstr+"?"
                if(req_args):
                    urlstr = urlstr + "args=" + req_args
                if(service.warning):
                    if (req_args):
                        urlstr = urlstr+"&"
                    urlstr = urlstr + "warning=yes"
            headers = {'Content-type': 'application/vnd.com.citrix.netscaler.'+ objtype +'+json','Connection': 'keep-alive', 'Set-Cookie':'NITRO_AUTH_TOKEN='+sessionid}
            response = requests.delete(urlstr, headers=headers, timeout=service.timeout)
            if not response.ok:
                response = json.loads(response.text)
                raise nitro_exception((response['errorcode']), str(response['message']), str(response['severity']))
            result = service.payload_formatter.string_to_resource(base_response, response.text, self.__class__.__name__) 
            if(result.errorcode != 0):
                if (result.errorcode == 444):
                    service.clear_session(self) 
                if result.severity :
                    if (result.severity == "ERROR"):
                        raise nitro_exception(result.errorcode, str(result.message), str(result.severity))          
                else:
                    raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) 
            return result
        except Exception as e:
            raise e 
Example #2
0
 def post_data(self, service, request, opt):
     try :
         response = self._post(self, service, request, opt)
         result = service.payload_formatter.string_to_resource(base_response, response, self.__class__.__name__)
         if (result.errorcode != 0 and result.errorcode != 1034):
             if (result.errorcode == 444):
                 service.clear_session()
             if result.severity:
                 if (result.severity == "ERROR"):
                     raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
             else:
                 raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
         return result
     except Exception as e:
         raise e
Example #3
0
 def post_bulk_data(cls, service, request, opt=""):
     try:
         response = cls._post(cls, service, request, opt, True)
         result = service.payload_formatter.string_to_resource(base_responses, response, cls.__name__)
         if (result.errorcode != 0):
             if (result.errorcode == 444):
                 service.clear_session()
             if (result.severity):
                 if (result.severity == "ERROR"):
                     raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
             else:
                 raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
         return result
     except Exception as e:
         raise e
Example #4
0
    def rename_resource(self, service, newname):
        """ Use this method to perform a rename operation on netscaler resource.
        
        Parameters:
			service - nitro_service object.
        	newname - new name to be set to the specified resource.
        
        Returns:
			status of the operation performed.
        
        Throws:
			Exception of the type nitro_exception is thrown.
        """
        try:
            if not service.isLogin():
                service.login()
                
            if '_newname' in self.__dict__ : 
                self.newname = newname
            else :
                raise nitro_exception(-1,str("Rename is not supported for this resource"),)
            opt = options()
            opt.action = "rename"
            response = self.post_request(service, opt)
            return response
        except Exception as e:
            raise e
	def _get_nitro_response(self, service, response) :
		ur""" converts nitro response into object and returns the object array in case of get request.
		"""
		try :
			result = service.payload_formatter.string_to_resource(nslimitidentifier_response, response, self.__class__.__name__.replace('_stats',''))
			if(result.errorcode != 0) :
				if (result.errorcode == 444) :
					service.clear_session(self)
				if result.severity :
					if (result.severity == "ERROR") :
						raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
				else :
					raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
			return result.nslimitidentifier
		except Exception as e :
			raise e
Example #6
0
 def _get_nitro_response(self, service, response):
     try:
         resources = [statobjects() for _ in range(1)]
         result = service.get_payload_formatter().string_to_resource(statobjects_response, response)
         if(result.errorcode != 0):
             if (result.errorcode == 444):
                 service.clear_session()
             if(result.severity is not None):
                 if (result.severity == "ERROR"):
                     raise nitro_exception(result.message,result.errorcode)
             else:
                 raise nitro_exception(result.message,result.errorcode)
         resources[0] = result.statobjects
         return resources
     except Exception as e:
         raise e
Example #7
0
	def _get_nitro_response(self, service, response) :
		""" converts nitro response into object and returns the object array in case of get request.
		"""
		try :
			result = service.payload_formatter.string_to_resource(responderpolicy_binding_response, response, self.__class__.__name__)
			if(result.errorcode != 0) :
				if (result.errorcode == 444) :
					service.clear_session(self)
				if result.severity :
					if (result.severity == "ERROR") :
						raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
				else :
					raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
			return result.responderpolicy_binding
		except Exception as e :
			raise e
    def _get_nitro_response(self, service, response):
        ur""" converts nitro response into object and returns the object array in case of get request.
		"""
        try:
            result = service.payload_formatter.string_to_resource(
                autoscalepolicy_response, response, self.__class__.__name__.replace("_stats", "")
            )
            if result.errorcode != 0:
                if result.errorcode == 444:
                    service.clear_session(self)
                if result.severity:
                    if result.severity == "ERROR":
                        raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
                else:
                    raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
            return result.autoscalepolicy
        except Exception as e:
            raise e
Example #9
0
 def protocol(self, protocol):
     """ Sets the protocol.
     
     @param protocol The protocol to be set.
     """
     try: 
         if protocol or protocol.lower!="http" or protocol.lower!="https": 
             raise nitro_exception("error: protocol value " + protocol + " is not supported")       
         self._protocol = protocol
     except Exception as e:
         raise e
Example #10
0
    def _put(resourcetype, service, request, bulk=""):
        """ This method, forms the http PUT request, applies on the netscaler.
        Reads the response from the netscaler and converts it to base response.
        
        Parameters:
			service - nitro_service object.
        	request - Json request.
        
        Returns:
			status of the operation performed.
        
        Throws:
			Exception of the type nitro_exception is thrown.
        """
        try :
            ipaddress = service.ipaddress
            version = service.version
            protocol = service.protocol
            if inspect.isclass(resourcetype) :
                resrc_type = resourcetype.get_object_type()
                urlstr = protocol+"://" + ipaddress + "/nitro/" + version + "/config/" + resrc_type     
            else :
                resrc_type = resourcetype.__class__.get_object_type()
                urlstr = protocol+"://" + ipaddress + "/nitro/" + version + "/config/" + resrc_type + "/"+ resourcetype._get_object_name()
            warning = service.warning
            onerror = service.onerror
            if((warning and warning == True) or onerror): 
                if warning and warning==True :
                        urlstr = urlstr + "?warning=yes"
                if onerror :
                    if (warning and warning==True) :
                        urlstr = urlstr + "&onerror=" + onerror
                    else :
                        urlstr = urlstr + "?onerror=" + onerror
            if bulk :
                headers = {'Content-type': 'application/vnd.com.citrix.netscaler.'+ resrc_type +'_list+json','Connection': 'keep-alive', 'Set-Cookie':'NITRO_AUTH_TOKEN='+ service.sessionid}
            else :
                headers = {'Content-type': 'application/vnd.com.citrix.netscaler.'+ resrc_type +'+json','Connection': 'keep-alive', 'Set-Cookie':'NITRO_AUTH_TOKEN='+ service.sessionid}
            response = requests.put(urlstr, data=request, headers=headers, timeout=service.timeout)
            if not response.ok:
                response = json.loads(response.text)
                raise nitro_exception((response['errorcode']), str(response['message']), str(response['severity']))
            elif bulk:
                return response.text
            else:
                nitro_response = {}
                nitro_response['errorcode'] = 0
                nitro_response['message'] = "Done"
                nitro_response['severity']= ""
                return json.dumps(nitro_response)      
        except Exception as e:
            raise e
Example #11
0
 def __init__(self, ip, protocol="http", payload_format=Json()):
     """ nitro_service class constructor specifying ip, format and protocol.
     
     @param ip Ipadress of the netscaler on which configuration is to be run.
     @param format format wire language to be used. eg: Json,XML
     @param protocol Protocol.
     """
     self._ipaddress = ip
     self._version = "v1"
     self._protocol = protocol
     self._format = payload_format
     if protocol.lower()!="http" and protocol.lower()!="https":
         raise nitro_exception("error: protocol value " + protocol + " is not supported")
Example #12
0
    def _get_nitro_response(self, service, response):
        r""" converts nitro response into object and returns the object array in case of get request.
		"""
        try:
            result = service.payload_formatter.string_to_resource(
                videooptimizationpacingpolicylabel_response, response,
                self.__class__.__name__.replace('_stats', ''))
            if (result.errorcode != 0):
                if (result.errorcode == 444):
                    service.clear_session(self)
                if result.severity:
                    if (result.severity == "ERROR"):
                        raise nitro_exception(result.errorcode,
                                              str(result.message),
                                              str(result.severity))
                else:
                    raise nitro_exception(result.errorcode,
                                          str(result.message),
                                          str(result.severity))
            return result.videooptimizationpacingpolicylabel
        except Exception as e:
            raise e
    def _get_nitro_response(self, service, response):
        r""" converts nitro response into object and returns the object array in case of get request.
		"""
        try:
            result = service.payload_formatter.string_to_resource(
                routerdynamicrouting_response, response,
                self.__class__.__name__)
            if (result.errorcode != 0):
                if (result.errorcode == 444):
                    service.clear_session(self)
                if result.severity:
                    if (result.severity == "ERROR"):
                        raise nitro_exception(result.errorcode,
                                              str(result.message),
                                              str(result.severity))
                else:
                    raise nitro_exception(result.errorcode,
                                          str(result.message),
                                          str(result.severity))
            return result.routerdynamicrouting
        except Exception as e:
            raise e
Example #14
0
    def stat_request(self, service,opt):
        """ This method, forms the http GET request, applies on the netscaler.
        Reads the response from the netscaler and converts it to corresponding stat resource type.
        
        Parameters:
			service
        	opt - Options class object
        
        Returns:
			Array of requested resources.
        """
        try:
            ipaddress = service.ipaddress
            version = service.version
            sessionid = service.sessionid
            objtype = self.__class__.get_object_type()
            objtype = objtype.split('_stats')
            objtype = objtype[0]
            protocol = service.protocol

            # build URL
            urlstr = protocol + "://" + ipaddress + "/nitro/" + version + "/stat/" + objtype;

            name = self._get_object_name();
            if (name and len(name) > 0):
                urlstr = urlstr+"/"+ str(nitro_util.encode(nitro_util.encode(name)))

            if (opt or service.warning):
                optionstr = ""
                if (opt):
                    optionstr = opt.to_string()
                    if (len(optionstr) > 0):
                        urlstr = urlstr +"?"
                        urlstr = urlstr + optionstr
                if (service.warning):
                    if (opt and len(optionstr) > 0):
                        urlstr = urlstr+"&"
                    else:
                        urlstr = urlstr+"?"
                    urlstr = urlstr+"warning=yes"
            headers = {'Content-type': 'application/vnd.com.citrix.netscaler.'+ objtype +'+json','Connection': 'keep-alive', 'Set-Cookie':'NITRO_AUTH_TOKEN='+sessionid}
            response = requests.get(urlstr, headers=headers, verify = service.certvalidation)
            if not response.ok:
                response = json.loads(response.text)
                raise nitro_exception((response['errorcode']), str(response['message']), str(response['severity']))
            else:
                result = self._get_nitro_response(service, response.text)
                return result
        except Exception as e:
            raise e
 def __init__(self, ip, protocol="http", payload_format=Json()):
     """ nitro_service class constructor specifying ip, format and protocol.
     
     @param ip Ipadress of the netscaler on which configuration is to be run.
     @param format format wire language to be used. eg: Json,XML
     @param protocol Protocol.
     """
     self._ipaddress = ip
     self._version = "v1"
     self._protocol = protocol
     self._format = payload_format
     if protocol.lower() != "http" and protocol.lower() != "https":
         raise nitro_exception("error: protocol value " + protocol +
                               " is not supported")
Example #16
0
    def stat_request(self, service,opt):
        """ This method, forms the http GET request, applies on the netscaler.
        Reads the response from the netscaler and converts it to corresponding stat resource type.
        
        Parameters:
			service
        	opt - Options class object
        
        Returns:
			Array of requested resources.
        """
        try:
            ipaddress = service.ipaddress
            version = service.version
            sessionid = service.sessionid
            objtype = self.__class__.get_object_type()
            objtype = objtype.split('_stats')
            objtype = objtype[0]
            protocol = service.protocol

            # build URL
            urlstr = protocol + "://" + ipaddress + "/nitro/" + version + "/stat/" + objtype;

            name = self._get_object_name();
            if (name and len(name) > 0):
                urlstr = urlstr+"/"+ str(nitro_util.encode(nitro_util.encode(name)))

            if (opt or service.warning):
                optionstr = ""
                if (opt):
                    optionstr = opt.to_string()
                    if (len(optionstr) > 0):
                        urlstr = urlstr +"?"
                        urlstr = urlstr + optionstr
                if (service.warning):
                    if (opt and len(optionstr) > 0):
                        urlstr = urlstr+"&"
                    else:
                        urlstr = urlstr+"?"
                    urlstr = urlstr+"warning=yes"
            headers = {'Content-type': 'application/vnd.com.citrix.netscaler.'+ objtype +'+json','Connection': 'keep-alive', 'Set-Cookie':'NITRO_AUTH_TOKEN='+sessionid}
            response = requests.get(urlstr, headers=headers, timeout=service.timeout)
            if not response.ok:
                response = json.loads(response.text)
                raise nitro_exception((response['errorcode']), str(response['message']), str(response['severity']))
            else:
                result = self._get_nitro_response(service, response.text)
                return result
        except Exception as e:
            raise e
Example #17
0
    def protocol(self, protocol):
        """ Sets the protocol.

        

        @param protocol The protocol to be set.

        """

        try:

            if protocol or protocol.lower != "http" or protocol.lower != "https":

                raise nitro_exception("error: protocol value " + protocol +
                                      " is not supported")

            self._protocol = protocol

        except Exception as e:

            raise e
Example #18
0
    def __init__(self,
                 connect_context,
                 protocol="http",
                 payload_format=Json()):
        """ nitro_service class constructor specifying ip, format and protocol.

        

        @param connect_context Ipadress of the netscaler on which configuration is to be run. OR an instance of MasContext.

        @param format format wire language to be used. eg: Json,XML

        @param protocol Protocol.

        """

        if isinstance(connect_context, MasContext):

            self._mascontext = connect_context

        else:

            self._ipaddress = connect_context

        self._version = "v1"

        self._protocol = protocol

        self._format = payload_format

        if protocol.lower() != "http" and protocol.lower() != "https":

            raise nitro_exception("error: protocol value " + protocol +
                                  " is not supported")

        _skipinvalidarg = False

        _idempotent = False
    def _post(resourcetype, service, request, opt, bulk=""):
        """ This method, forms the http POST request, applies on the netscaler.
        Reads the response from the netscaler and converts it to base response.
        
        Parameters:
			service - nitro_service object.
        	request - Json request.
        
        Returns:
			status of the operation performed.
        
        Throws:
			Exception
        """
        try:
            ipaddress = service.ipaddress
            version = service.version
            protocol = service.protocol
            if inspect.isclass(resourcetype):
                resrc_type = resourcetype.get_object_type()
            else:
                resrc_type = resourcetype.__class__.get_object_type()
            urlstr = protocol + "://" + ipaddress + "/nitro/" + version + "/config/" + resrc_type
            warning = service.warning
            onerror = service.onerror
            if (opt or (warning and warning == True) or onerror):
                if opt:
                    if opt.action:
                        urlstr = urlstr + "?action=" + opt.action
                if warning and warning == True:
                    if opt:
                        urlstr = urlstr + "&warning=yes"
                    else:
                        urlstr = urlstr + "?warning=yes"
                if onerror:
                    if opt or (warning and warning == True):
                        urlstr = urlstr + "&onerror=" + onerror
                    else:
                        urlstr = urlstr + "?onerror=" + onerror
            if service.sessionid:
                if bulk:
                    headers = {
                        'Content-type':
                        'application/vnd.com.citrix.netscaler.' + resrc_type +
                        '_list+json',
                        'Connection':
                        'keep-alive',
                        'Set-Cookie':
                        'NITRO_AUTH_TOKEN=' + service.sessionid
                    }
                else:
                    headers = {
                        'Content-type':
                        'application/vnd.com.citrix.netscaler.' + resrc_type +
                        '+json',
                        'Connection':
                        'keep-alive',
                        'Set-Cookie':
                        'NITRO_AUTH_TOKEN=' + service.sessionid
                    }
            else:
                headers = {
                    'Content-type':
                    'application/vnd.com.citrix.netscaler.' + resrc_type +
                    '+json',
                    'Connection':
                    'keep-alive'
                }
            response = requests.post(urlstr,
                                     data=request,
                                     headers=headers,
                                     timeout=service.timeout,
                                     verify=service.certvalidation)
            if not response.ok:
                response = json.loads(response.text)
                raise nitro_exception((response['errorcode']),
                                      str(response['message']),
                                      str(response['severity']))
            elif bulk and response.text:
                return response.text
            else:
                nitro_response = {}
                if resrc_type == "login":
                    nitro_response['sessionid'] = urllib2.unquote(
                        response.cookies['NITRO_AUTH_TOKEN'])
                nitro_response['errorcode'] = 0
                nitro_response['message'] = "Done"
                nitro_response['severity'] = ""
                return json.dumps(nitro_response)
        except Exception as e:
            raise e
Example #20
0
    def get_request(self, service, opt):
        """ This method, forms the http GET request, applies on the netscaler.
        Reads the response from the netscaler and converts it to corresponding 
        resource type.
        
        Parameters:
            service - nitro_service object.
            opt - Options class object
        
        Returns:
            Array of requested resources.
        """
        try:
            if (service.isMasContext):
                ipaddress = service.mas_ipaddress
            else:
                ipaddress = service.ipaddress

            version = service.version
            sessionid = service.sessionid
            objtype = self.__class__.get_object_type()
            protocol = service.protocol

            # build URL
            urlstr = protocol + "://" + ipaddress + "/nitro/" + version + "/config/" + objtype

            name = self._get_object_name()
            if (name and len(name) > 0):
                urlstr = urlstr + "/" + str(
                    nitro_util.encode(nitro_util.encode(name)))

            if (opt or (service.warning)):
                optionstr = ""
                if (opt):
                    optionstr = opt.to_string()
                    if (len(optionstr) > 0):
                        urlstr = urlstr + "?"
                        urlstr = urlstr + optionstr
                if (service.warning):
                    if (opt and len(optionstr) > 0):
                        urlstr = urlstr + "&"
                    else:
                        urlstr = urlstr + "?"
                    urlstr = urlstr + "warning=yes"

            headers = {
                'Content-type':
                'application/vnd.com.citrix.netscaler.' + objtype + '+json',
                'Connection':
                'keep-alive'
            }

            retry = True
            retries = 0
            while retry:
                # set sessionid in headers
                if service.isMasContext:
                    headers['Cookie'] = 'SESSID=' + service.mas_sessionid
                    headers[
                        '_MPS_API_PROXY_MANAGED_INSTANCE_IP'] = service.mas_target_nsip
                else:
                    headers[
                        'Set-Cookie'] = 'NITRO_AUTH_TOKEN=' + service.sessionid
                response = requests.get(urlstr,
                                        headers=headers,
                                        verify=service.certvalidation,
                                        timeout=(service.connection_timeout,
                                                 service.read_timeout))
                if not response.ok:
                    response = json.loads(response.text)
                    if not service.isMasContext and response["errorcode"] in [
                            ERROR_CODE_SESSION_EXPIRED,
                            ERROR_CODE_NOT_LOGGED_IN
                    ] and retries < MAX_LOGIN_RETRIES_ALLOWED:
                        retries += 1
                        # Re-Login
                        service.clear_session()
                        service.login()
                    else:
                        try:
                            response["severity"]
                        except KeyError:
                            response["severity"] = "ERROR"
                        raise nitro_exception((response['errorcode']),
                                              str(response['message']),
                                              str(response['severity']))
                else:
                    result = self._get_nitro_response(service, response.text)
                    return result
        except Exception as e:
            raise e
Example #21
0
    def _post(resourcetype, service, request, opt, bulk=""):
        """ This method, forms the http POST request, applies on the netscaler.
        Reads the response from the netscaler and converts it to base response.
        
        Parameters:
            service - nitro_service object.
            request - Json request.
        
        Returns:
            status of the operation performed.
        
        Throws:
            Exception
        """
        try:
            if (service.isMasContext):
                ipaddress = service.mas_ipaddress
            else:
                ipaddress = service.ipaddress
            version = service.version
            protocol = service.protocol
            if inspect.isclass(resourcetype):
                resrc_type = resourcetype.get_object_type()
            else:
                resrc_type = resourcetype.__class__.get_object_type()
            urlstr = protocol + "://" + ipaddress + "/nitro/" + version + "/config/" + resrc_type
            warning = service.warning
            onerror = service.onerror
            skipinvalidarg = service.skipinvalidarg
            idempotent = service.idempotent
            url_params_dict = OrderedDict()
            if opt:
                if opt.action:
                    url_params_dict["action"] = opt.action
            if warning and warning == True:
                url_params_dict["warning"] = "yes"
            if onerror:
                url_params_dict["onerror"] = onerror
            if skipinvalidarg:
                url_params_dict["skipinvalidarg"] = "yes"
            # Add idempotent flag only if action is empty and resource-name doesn't have "_binding" and is not one of idempotent_invalid_resources
            if idempotent and not (opt and opt.action) and (
                    "_binding" not in resrc_type) and (
                        resrc_type
                        not in base_resource.idempotent_invalid_resources):
                url_params_dict["idempotent"] = "yes"

            urlstr += base_resource.construct_url_queryparams_str(
                url_params_dict)

            if bulk:
                headers = {
                    'Content-type':
                    'application/vnd.com.citrix.netscaler.' + resrc_type +
                    '_list+json',
                    'Connection':
                    'keep-alive'
                }
            else:
                headers = {
                    'Content-type':
                    'application/vnd.com.citrix.netscaler.' + resrc_type +
                    '+json',
                    'Connection':
                    'keep-alive'
                }

            retry = True
            retries = 0
            while retry:
                # set sessionid in headers
                if service.isMasContext:
                    headers['Cookie'] = 'SESSID=' + service.mas_sessionid
                    headers[
                        '_MPS_API_PROXY_MANAGED_INSTANCE_IP'] = service.mas_target_nsip
                elif service.sessionid:
                    headers[
                        'Set-Cookie'] = 'NITRO_AUTH_TOKEN=' + service.sessionid

                response = requests.post(urlstr,
                                         data=request,
                                         headers=headers,
                                         verify=service.certvalidation,
                                         timeout=(service.connection_timeout,
                                                  service.read_timeout))
                if not response.ok:
                    # in case of "bulk request" - '200' Ok is returned as statuscode for session expiry error,
                    # hence it will not be handled in above if block
                    response = json.loads(response.text)
                    if not service.isMasContext and response["errorcode"] in [
                            ERROR_CODE_SESSION_EXPIRED,
                            ERROR_CODE_NOT_LOGGED_IN
                    ] and retries < MAX_LOGIN_RETRIES_ALLOWED:
                        retries += 1
                        # Re-Login
                        service.clear_session()
                        service.login()
                    else:
                        #response returned by MAS in case of error does not have severity..
                        try:
                            response["severity"]
                        except KeyError:
                            response["severity"] = "ERROR"
                        raise nitro_exception((response['errorcode']),
                                              str(response['message']),
                                              str(response['severity']))
                elif bulk and response.text:
                    response_json = json.loads(response.text)
                    if not service.isMasContext and response_json[
                            "errorcode"] in [
                                ERROR_CODE_SESSION_EXPIRED,
                                ERROR_CODE_NOT_LOGGED_IN
                            ] and retries < MAX_LOGIN_RETRIES_ALLOWED:
                        retries += 1
                        # Re-Login
                        service.clear_session()
                        service.login()
                    else:
                        return response.text
                else:
                    response_needed = resourcetype.is_responseneeded(
                        resrc_type, opt)
                    if response_needed and response.text:
                        return response.text
                    nitro_response = {}
                    if resrc_type == "login":
                        nitro_response['sessionid'] = urllib2.unquote(
                            response.cookies['NITRO_AUTH_TOKEN'])
                    nitro_response['errorcode'] = 0
                    nitro_response['message'] = "Done"
                    nitro_response['severity'] = ""
                    return json.dumps(nitro_response)
        except Exception as e:
            raise e
Example #22
0
    def delete_request(self, service, req_args):
        """ This method, forms the http DELETE request, applies on the netscaler.
        Reads the response from the netscaler and converts it to base response.
    
        Parameters:
            service - nitro_service object.
            req_args
        
        Returns:
            Array of requested resources.
        
        Throws:
            Exception
        """
        try:
            if (service.isMasContext):
                ipaddress = service.mas_ipaddress
            else:
                ipaddress = service.ipaddress
            version = service.version
            sessionid = service.sessionid
            objtype = self.__class__.get_object_type()
            protocol = service.protocol

            # build URL
            urlstr = protocol + "://" + ipaddress + "/nitro/" + version + "/config/" + objtype

            name = self._get_object_name()
            if (name and len(name) > 0):
                urlstr = urlstr + "/" + nitro_util.encode(
                    nitro_util.encode(name))

            url_params_dict = OrderedDict()
            if (service.skipinvalidarg):
                url_params_dict["skipinvalidarg"] = "yes"
            if (req_args):
                url_params_dict["args"] = req_args
            if (service.warning):
                url_params_dict["warning"] = "yes"

            urlstr += base_resource.construct_url_queryparams_str(
                url_params_dict)

            headers = {
                'Content-type':
                'application/vnd.com.citrix.netscaler.' + objtype + '+json',
                'Connection':
                'keep-alive'
            }

            retry = True
            retries = 0
            while retry:
                # set sessionid in headers
                if service.isMasContext:
                    headers['Cookie'] = 'SESSID=' + service.mas_sessionid
                    headers[
                        '_MPS_API_PROXY_MANAGED_INSTANCE_IP'] = service.mas_target_nsip
                else:
                    headers[
                        'Set-Cookie'] = 'NITRO_AUTH_TOKEN=' + service.sessionid
                response = requests.delete(urlstr,
                                           headers=headers,
                                           verify=service.certvalidation,
                                           timeout=(service.connection_timeout,
                                                    service.read_timeout))
                if not response.ok:
                    response = json.loads(response.text)
                    if not service.isMasContext and response["errorcode"] in [
                            ERROR_CODE_SESSION_EXPIRED,
                            ERROR_CODE_NOT_LOGGED_IN
                    ] and retries < MAX_LOGIN_RETRIES_ALLOWED:
                        retries += 1
                        service.clear_session()
                        service.login()
                    else:
                        #response returned by MAS in case of error does not have severity..
                        try:
                            response["severity"]
                        except KeyError:
                            response["severity"] = "ERROR"
                        raise nitro_exception((response['errorcode']),
                                              str(response['message']),
                                              str(response['severity']))
                else:
                    result = service.payload_formatter.string_to_resource(
                        base_response, response.text, self.__class__.__name__)
                    return result
        except Exception as e:
            raise e
    def delete_request(self, service, req_args):
        """ This method, forms the http DELETE request, applies on the netscaler.
        Reads the response from the netscaler and converts it to base response.
    
        Parameters:
			service - nitro_service object.
        	req_args
        
        Returns:
			Array of requested resources.
        
        Throws:
			Exception
        """
        try:
            ipaddress = service.ipaddress
            version = service.version
            sessionid = service.sessionid
            objtype = self.__class__.get_object_type()
            protocol = service.protocol

            # build URL
            urlstr = protocol + "://" + ipaddress + "/nitro/" + version + "/config/" + objtype

            name = self._get_object_name()
            if (name and len(name) > 0):
                urlstr = urlstr + "/" + nitro_util.encode(
                    nitro_util.encode(name))

            if (req_args or service.warning):
                urlstr = urlstr + "?"
                if (req_args):
                    urlstr = urlstr + "args=" + req_args
                if (service.warning):
                    if (req_args):
                        urlstr = urlstr + "&"
                    urlstr = urlstr + "warning=yes"
            headers = {
                'Content-type':
                'application/vnd.com.citrix.netscaler.' + objtype + '+json',
                'Connection':
                'keep-alive',
                'Set-Cookie':
                'NITRO_AUTH_TOKEN=' + sessionid
            }
            response = requests.delete(urlstr,
                                       headers=headers,
                                       timeout=service.timeout,
                                       verify=service.certvalidation)
            if not response.ok:
                response = json.loads(response.text)
                raise nitro_exception((response['errorcode']),
                                      str(response['message']),
                                      str(response['severity']))
            result = service.payload_formatter.string_to_resource(
                base_response, response.text, self.__class__.__name__)
            if (result.errorcode != 0):
                if (result.errorcode == 444):
                    service.clear_session(self)
                if result.severity:
                    if (result.severity == "ERROR"):
                        raise nitro_exception(result.errorcode,
                                              str(result.message),
                                              str(result.severity))
                else:
                    raise nitro_exception(result.errorcode,
                                          str(result.message),
                                          str(result.severity))
            return result
        except Exception as e:
            raise e