Esempio n. 1
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
                name = str(resourcetype._get_object_name())
                if (name and len(name) > 0):
                    urlstr = urlstr+"/"+ str(nitro_util.encode(nitro_util.encode(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, 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:
                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
Esempio n. 2
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 
Esempio n. 3
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, 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 
Esempio n. 4
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
Esempio n. 5
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
Esempio n. 6
0
 def filter(self, filter_str_array):
     """ sets _filter field.
     
     @param _filter set self with the _filter string to perform filtered get operation. 
     
     Set the _filter parameters in filtervalue object which is then converted to json string.
     """
     try:
         if type(filter_str_array) is list :
             filter_str = ""
             for i in filter_str_array:
                 if (filter_str):
                     filter_str = filter_str + ","
                 if not filter_str :
                     filter_str = i.name + ":" + nitro_util.encode(i.value)
                 else:
                     filter_str = filter_str + i.name + ":" + nitro_util.encode(i.value)
             self._filter = filter_str
         else :
             filter_str_array = filter_str_array.split(':') 
             self._filter = filter_str_array[0] + ":" + filter_str_array[1]
     except Exception as e:
         raise e           
Esempio n. 7
0
 def filter(self, filter_str_array):
     """ sets _filter field.
     
     @param _filter set self with the _filter string to perform filtered get operation. 
     
     Set the _filter parameters in filtervalue object which is then converted to json string.
     """
     try:
         if type(filter_str_array) is list:
             filter_str = ""
             for i in filter_str_array:
                 if (filter_str):
                     filter_str = filter_str + ","
                 if not filter_str:
                     filter_str = i.name + ":" + nitro_util.encode(i.value)
                 else:
                     filter_str = filter_str + i.name + ":" + nitro_util.encode(
                         i.value)
             self._filter = filter_str
         else:
             filter_str_array = filter_str_array.split(':')
             self._filter = filter_str_array[0] + ":" + filter_str_array[1]
     except Exception as e:
         raise e
Esempio n. 8
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
Esempio n. 9
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:
            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()
                urlstr = protocol + "://" + ipaddress + "/nitro/" + version + "/config/" + resrc_type
            else:
                resrc_type = resourcetype.__class__.get_object_type()
                urlstr = protocol + "://" + ipaddress + "/nitro/" + version + "/config/" + resrc_type
                name = str(resourcetype._get_object_name())
                if (name and len(name) > 0):
                    urlstr = urlstr + "/" + str(
                        nitro_util.encode(nitro_util.encode(name)))
            warning = service.warning
            onerror = service.onerror
            skipinvalidarg = service.skipinvalidarg

            url_params_dict = OrderedDict()
            if warning and warning == True:
                url_params_dict["warning"] = "yes"
            if onerror:
                url_params_dict["onerror"] = onerror
            if skipinvalidarg:
                url_params_dict["skipinvalidarg"] = "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
                else:
                    headers[
                        'Set-Cookie'] = 'NITRO_AUTH_TOKEN=' + service.sessionid

                response = requests.put(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:
                    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:
                    nitro_response = {}
                    nitro_response['errorcode'] = 0
                    nitro_response['message'] = "Done"
                    nitro_response['severity'] = ""
                    return json.dumps(nitro_response)
        except Exception as e:
            raise e
Esempio n. 10
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