Example #1
0
 def isRequestConfigEnabled(self, config_key, default=False):
     value = System.getConfig().getConfigValue("testing", config_key)
     if value is None:
         return default
     elif value.lower() in ("yes", "y", "true", "on"):
         return True
     elif value.lower() in ("no", "n", "false", "off"):
         return False
     else:
         return default
Example #2
0
 def reserve(self, coverage_id, request_id=None, until=None):
     """
     Tries to reserve a ``coverage_id`` until a given datetime. If ``until``
     is omitted, the configuration value 
     ``resources.coverages.coverage_id.reservation_time`` is used.
     
     If the ID is already reserved and the ``resource_id`` is not equal to
     the reserved ``resource_id``, a :class:`~.CoverageIdReservedError` is
     raised. If the ID is already taken by an existing coverage a 
     :class:`~.CoverageIdInUseError` is raised.
     These exceptions are sub-classes of :exc:`~.CoverageIdError`.
     """
     
     obj, _ = ReservedCoverageIdRecord.objects.get_or_create(
         coverage_id=coverage_id,
         defaults={
             "until": timezone.now()
         }
     )
     
     if not until:
         values = System.getConfig().getConfigValue(
             "resources.coverages.coverage_id", "reservation_time"
         ).split(":")
         
         for _ in xrange(len(values[:4]) - 4):
             values.insert(0, 0)
         
         dt = timedelta(days=int(values[0]), hours=int(values[1]),
                        minutes=int(values[2]), seconds=int(values[3]))
         until = timezone.now() + dt
     
     if timezone.now() < obj.until:
         if not (obj.request_id == request_id and obj.request_id is not None):
             raise CoverageIdReservedError(
                 "Coverage ID '%s' is reserved until %s" % (coverage_id, obj.until)
             )
     elif CoverageRecord.objects.filter(coverage_id=coverage_id).count() > 0:
         raise CoverageIdInUseError("Coverage ID '%s' is already in use."
             % coverage_id
         )
     
     obj.request_id = request_id
     obj.until = until
     obj.save()
Example #3
0
def create_temporary_rectified_vrt(path_or_ds, srid=None,
    resample=gdal.GRA_NearestNeighbour, memory_limit=0.0,
    max_error=APPROX_ERR_TOL, method=METHOD_GCP, order=0):

    try:
        from eoxserver.core.system import System
        vrt_tmp_dir = System.getConfig().getConfigValue("processing.gdal.reftools", "vrt_tmp_dir")
    except: vrt_tmp_dir = None
    
    _, vrt_path = mkstemp(
        dir = vrt_tmp_dir,
        suffix = ".vrt"
    )
    
    create_rectified_vrt(path_or_ds, vrt_path, srid, 
        resample, memory_limit, max_error, 
        method, order)
    
    return vrt_path
def getAllowedActions():

    global ALLOWED_ACTIONS

    if (ALLOWED_ACTIONS is not None): return ALLOWED_ACTIONS

    ACTIONS_UPPER = map(lambda s: s.upper(), ACTIONS)
    ACTIONS_U2N = dict(zip(ACTIONS_UPPER, ACTIONS))

    # unpack the allowed actions
    conf = System.getConfig()
    tmp = conf.getConfigValue("services.ows.wcst11", "allowed_actions")
    tmp = map(lambda s: s.strip().upper(), tmp.split(","))
    tmp = filter(lambda s: s in ACTIONS_UPPER, tmp)
    tmp = map(lambda s: ACTIONS_U2N[s], tmp)

    ALLOWED_ACTIONS = set(tmp)

    # always allow Add action
    #ALLOWED_ACTIONS.add( "Add" )

    return ALLOWED_ACTIONS
def getAllowedActions() :

    global ALLOWED_ACTIONS

    if ( ALLOWED_ACTIONS is not None ) : return ALLOWED_ACTIONS

    ACTIONS_UPPER = map( lambda s : s.upper() , ACTIONS )
    ACTIONS_U2N = dict( zip( ACTIONS_UPPER , ACTIONS ) ) 

    # unpack the allowed actions 
    conf = System.getConfig()
    tmp  = conf.getConfigValue("services.ows.wcst11","allowed_actions")
    tmp  = map( lambda s : s.strip().upper() , tmp.split(",") )
    tmp  = filter( lambda s : s in ACTIONS_UPPER , tmp ) 
    tmp  = map( lambda s : ACTIONS_U2N[s] , tmp ) 

    ALLOWED_ACTIONS = set( tmp ) 

    # always allow Add action  
    #ALLOWED_ACTIONS.add( "Add" ) 

    return ALLOWED_ACTIONS 
Example #6
0
def contextCreate( requestId = None , reponseHandler = None , maxAttempts = 3 ) : 

    conf = System.getConfig()

    log_file   = conf.getConfigValue("core.system","logging_filename") 
    log_level  = conf.getConfigValue("core.system","logging_level" ) 
    log_format = conf.getConfigValue("core.system","logging_format" ) 

    path_temp0 = conf.getConfigValue("services.ows.wcst11","path_wcst_temp") 
    path_perm0 = conf.getConfigValue("services.ows.wcst11","path_wcst_perm") 
    muti_act   = ( "True" == conf.getConfigValue("services.ows.wcst11","allow_multiple_actions") ) 

    context = {} 
    context['responseHandler'] = checkResponseHandler( reponseHandler ) 
    context['isAsync']         = reponseHandler is not None 
    context['mutipleActionsAllowed'] = muti_act
    context['loggingFilename'] = log_file 
    context['loggingLevel']    = log_level
    context['loggingFormat']   = log_format 

    logging.debug("WCSt11: loggingFilename %s "  % str(log_file) )
    logging.debug("WCSt11: loggingformat %s "  % str(log_format) )
    logging.debug("WCSt11: loggingLevel %s "  % str(log_level) )

    for i in xrange( maxAttempts ) :
    
        # internal transaction ID (used as request ID if not provided by the client) 
        tid = getNewRequestID() 

        path_temp = os.path.join( path_temp0 , tid ) 
        path_perm = os.path.join( path_perm0 , tid ) 

        # check if directories do not exist 
        try : 
            os.mkdir( path_temp )
        except Exception as e : 
            logging.warning( "Failed to create the temporary storage directory! %s" % str(path_temp) ) 
            continue # try another process ID

        try : 
            os.mkdir( path_perm )
        except Exception as e : 
            os.rmdir( path_temp ) 
            logging.warning( "Failed to create the permanent storage directory! %s" % str(path_perm) ) 
            continue # try another process ID

        # store the values 
        context['requestId'] = tid if ( requestId is None ) else requestId
        context['tid']       = tid 
        context['pathTemp']  = path_temp
        context['pathPerm']  = path_perm

        # store the current working directory
        context['pathOrig']  = os.getcwd() 

        # change to the temporary storage dir 
        os.chdir( path_temp ) 

        #---------------------------------------------

        logging.debug("WCSt11: Request ID:        %s %s" % ( tid , "" if ( requestId is None ) else "(%s)" %(requestId) ) )
        logging.debug("WCSt11: Permanent Storage:  %s" % path_perm )
        logging.debug("WCSt11: Temporary Storage:  %s" % path_temp )

        break 

    else : 
        msg = "WCSt11: Failed to create an unique WCS transaction's context!" 
        logging.error( msg ) 
        raise OSError , msg 

    return context 
Example #7
0
def contextCreate(requestId=None, reponseHandler=None, maxAttempts=3):

    conf = System.getConfig()

    log_file = conf.getConfigValue("core.system", "logging_filename")
    log_level = conf.getConfigValue("core.system", "logging_level")
    log_format = conf.getConfigValue("core.system", "logging_format")

    path_temp0 = conf.getConfigValue("services.ows.wcst11", "path_wcst_temp")
    path_perm0 = conf.getConfigValue("services.ows.wcst11", "path_wcst_perm")
    muti_act = ("True" == conf.getConfigValue("services.ows.wcst11",
                                              "allow_multiple_actions"))

    context = {}
    context['responseHandler'] = checkResponseHandler(reponseHandler)
    context['isAsync'] = reponseHandler is not None
    context['mutipleActionsAllowed'] = muti_act
    context['loggingFilename'] = log_file
    context['loggingLevel'] = log_level
    context['loggingFormat'] = log_format

    logging.debug("WCSt11: loggingFilename %s " % str(log_file))
    logging.debug("WCSt11: loggingformat %s " % str(log_format))
    logging.debug("WCSt11: loggingLevel %s " % str(log_level))

    for i in xrange(maxAttempts):

        # internal transaction ID (used as request ID if not provided by the client)
        tid = getNewRequestID()

        path_temp = os.path.join(path_temp0, tid)
        path_perm = os.path.join(path_perm0, tid)

        # check if directories do not exist
        try:
            os.mkdir(path_temp)
        except Exception as e:
            logging.warning(
                "Failed to create the temporary storage directory! %s" %
                str(path_temp))
            continue  # try another process ID

        try:
            os.mkdir(path_perm)
        except Exception as e:
            os.rmdir(path_temp)
            logging.warning(
                "Failed to create the permanent storage directory! %s" %
                str(path_perm))
            continue  # try another process ID

        # store the values
        context['requestId'] = tid if (requestId is None) else requestId
        context['tid'] = tid
        context['pathTemp'] = path_temp
        context['pathPerm'] = path_perm

        # store the current working directory
        context['pathOrig'] = os.getcwd()

        # change to the temporary storage dir
        os.chdir(path_temp)

        #---------------------------------------------

        logging.debug("WCSt11: Request ID:        %s %s" %
                      (tid, "" if
                       (requestId is None) else "(%s)" % (requestId)))
        logging.debug("WCSt11: Permanent Storage:  %s" % path_perm)
        logging.debug("WCSt11: Temporary Storage:  %s" % path_temp)

        break

    else:
        msg = "WCSt11: Failed to create an unique WCS transaction's context!"
        logging.error(msg)
        raise OSError, msg

    return context
def _wcst11AlterCapabilities( respSrc , OWS ) : 

    conf = System.getConfig()
    regs = System.getRegistry() 

    # get the service URL  
    base_url = conf.getConfigValue("services.owscommon","http_service_url") 

    # =====================================================================
    # check the content 

    try : 

        # check if the WCST11 request handler is registered and enabled
        if not regs.getImplementationStatus("services.ows.wcs11Transaction.WCS11TransactionHandler") :  
            raise Exception , "Operation handler is not enabled!"

        # check if payload contains XML content 
        if respSrc.content_type not in ("text/xml","application/xml") : 
            raise Exception , "Not XML!"
    
        # parse the original payload 
        root = etree.fromstring( respSrc.content )

        # check the root element 
        if splitQN( root.tag )[1] != "Capabilities" :
            raise Exception , "Not Capabilities!"

        # check version  
        if not root.get('version','').startswith(OWS.version) : 
            raise Exception ,"Not Capabilities version %s!" % OWS.version 

        # look for OperationsMetadata 
        eOM = root.find( OWS.E_OperationsMetadata ) 

        # look for ServiceIdentification 
        eSI = root.find( OWS.E_ServiceIdentification ) 

        if ( eOM is None ) and ( eSI is None ) : 
            raise Exception , "No element to be altered has been found!"

    except Exception as e : 

        # keep track of the failures 
        logger.debug( "_wcst11AlterCapabilities(): version %s : Content not altered! reason: %s " % ( OWS.version , str(e) ) ) 

        # return unafected original response 
        return respSrc  

    # =====================================================================
    # insert new Profile element to ServiceIdentification

    conf = System.getConfig()
 
    if eOM is not None :

        #insert sub-element before the selected elements 
        def insertBefore( dst , src , before ) : 

            # get the sublelements  
            elements = filter( lambda e : ( e is not None ) , map( lambda tag : dst.find( tag ) , before ) ) 

            try: 
                # locate firts sublelemet 
                dl  = list( dst ) 
                idx = min( map( lambda e : dl.index( e ) , elements ) )

                # create element 
                e = etree.Element( src ) 

                # insert element at the desired position 
                dst.insert( idx , e ) 

            except: 
            
                # simply append elemet at the end 
                e = etree.SubElement( dst , src ) 

            return e 

        before = ( OWS11.E_Fees , OWS11.E_AccessConstraints ) ; 

        # ows:Profile - WCSt >>Multiple Actions<< 
        if ( "True" == conf.getConfigValue("services.ows.wcst11","allow_multiple_actions") ) : 
            #etree.SubElement( eSI , OWS.E_Profile ).text = "urn:ogc:extension:WCS:1.1:TransactionMultipleActions"
            insertBefore( eSI , OWS.E_Profile , before ).text = "urn:ogc:extension:WCS:1.1:TransactionMultipleActions"

        # unpack the allowed actions 
        allowedActions = conf.getConfigValue("services.ows.wcst11","allowed_actions")
        allowedActions = set( filter( lambda s : s in ACTIONS_UPPER , map( lambda s : s.strip().upper() , allowedActions.split(",") ) ) )  

        # annotate allowd actions 
        for action in allowedActions : 
            # ows:Profile - WCSt allowed action action
            #etree.SubElement( eSI , OWS.E_Profile ).text = "urn:ogc:extension:WCS:1.1:Transaction%s" % ACTIONS_U2N[action] 
            insertBefore( eSI , OWS.E_Profile , before ).text = "urn:ogc:extension:WCS:1.1:Transaction%s" % ACTIONS_U2N[action] 

    # =====================================================================
    # insert new Operation element to OperationMetadata 

    if eOM is not None : 

        # ows:Operation
        eOp= etree.SubElement( eOM , OWS.E_Operation, { A_name : "transaction" } )

        # ows:DCP
        tmp = etree.SubElement( eOp , OWS.E_DCP )
        tmp = etree.SubElement( tmp , OWS.E_HTTP )
        tmp = etree.SubElement( tmp , OWS.E_Post , { A_href : base_url , A_type : "simple" } )

        # ows:Constraint 
        if 1 < int(OWS.version[0]) : 
            tmp = etree.SubElement( tmp , OWS.E_Constraint , { A_name : "PostEncoding" } )
            tmp = etree.SubElement( tmp , OWS.E_AllowedValues )
            tmp = etree.SubElement( tmp , OWS.E_Value )
            tmp.text = "XML"

        # ows:Parameter 
        tmp = etree.SubElement( eOp , OWS.E_Parameter , { A_name : "service" } )
        tmp = etree.SubElement( tmp , OWS.E_AllowedValues )
        tmp = etree.SubElement( tmp , OWS.E_Value )
        tmp.text = "WCS"

        # ows:Parameter 
        tmp = etree.SubElement( eOp , OWS.E_Parameter , { A_name : "version" } )
        tmp = etree.SubElement( tmp , OWS.E_AllowedValues )
        tmp = etree.SubElement( tmp , OWS.E_Value )
        tmp.text = "1.1"

    # =====================================================================
    # return the altered payload 

    return Response( content= etree.tostring(root,"UTF-8") , content_type=respSrc.content_type , status=respSrc.status ) 
Example #9
0
def _wcst11AlterCapabilities(respSrc, OWS):

    conf = System.getConfig()
    regs = System.getRegistry()

    # get the service URL
    base_url = conf.getConfigValue("services.owscommon", "http_service_url")

    # =====================================================================
    # check the content

    try:

        # check if the WCST11 request handler is registered and enabled
        if not regs.getImplementationStatus(
                "services.ows.wcs11Transaction.WCS11TransactionHandler"):
            raise Exception, "Operation handler is not enabled!"

        # check if payload contains XML content
        if respSrc.content_type not in ("text/xml", "application/xml"):
            raise Exception, "Not XML!"

        # parse the original payload
        root = etree.fromstring(respSrc.content)

        # check the root element
        if splitQN(root.tag)[1] != "Capabilities":
            raise Exception, "Not Capabilities!"

        # check version
        if not root.get('version', '').startswith(OWS.version):
            raise Exception, "Not Capabilities version %s!" % OWS.version

        # look for OperationsMetadata
        eOM = root.find(OWS.E_OperationsMetadata)

        # look for ServiceIdentification
        eSI = root.find(OWS.E_ServiceIdentification)

        if (eOM is None) and (eSI is None):
            raise Exception, "No element to be altered has been found!"

    except Exception as e:

        # keep track of the failures
        logger.debug(
            "_wcst11AlterCapabilities(): version %s : Content not altered! reason: %s "
            % (OWS.version, str(e)))

        # return unafected original response
        return respSrc

    # =====================================================================
    # insert new Profile element to ServiceIdentification

    conf = System.getConfig()

    if eOM is not None:

        #insert sub-element before the selected elements
        def insertBefore(dst, src, before):

            # get the sublelements
            elements = filter(lambda e: (e is not None),
                              map(lambda tag: dst.find(tag), before))

            try:
                # locate firts sublelemet
                dl = list(dst)
                idx = min(map(lambda e: dl.index(e), elements))

                # create element
                e = etree.Element(src)

                # insert element at the desired position
                dst.insert(idx, e)

            except:

                # simply append elemet at the end
                e = etree.SubElement(dst, src)

            return e

        before = (OWS11.E_Fees, OWS11.E_AccessConstraints)

        # ows:Profile - WCSt >>Multiple Actions<<
        if ("True" == conf.getConfigValue("services.ows.wcst11",
                                          "allow_multiple_actions")):
            #etree.SubElement( eSI , OWS.E_Profile ).text = "urn:ogc:extension:WCS:1.1:TransactionMultipleActions"
            insertBefore(
                eSI, OWS.E_Profile, before
            ).text = "urn:ogc:extension:WCS:1.1:TransactionMultipleActions"

        # unpack the allowed actions
        allowedActions = conf.getConfigValue("services.ows.wcst11",
                                             "allowed_actions")
        allowedActions = set(
            filter(lambda s: s in ACTIONS_UPPER,
                   map(lambda s: s.strip().upper(),
                       allowedActions.split(","))))

        # annotate allowd actions
        for action in allowedActions:
            # ows:Profile - WCSt allowed action action
            #etree.SubElement( eSI , OWS.E_Profile ).text = "urn:ogc:extension:WCS:1.1:Transaction%s" % ACTIONS_U2N[action]
            insertBefore(
                eSI, OWS.E_Profile, before
            ).text = "urn:ogc:extension:WCS:1.1:Transaction%s" % ACTIONS_U2N[
                action]

    # =====================================================================
    # insert new Operation element to OperationMetadata

    if eOM is not None:

        # ows:Operation
        eOp = etree.SubElement(eOM, OWS.E_Operation, {A_name: "transaction"})

        # ows:DCP
        tmp = etree.SubElement(eOp, OWS.E_DCP)
        tmp = etree.SubElement(tmp, OWS.E_HTTP)
        tmp = etree.SubElement(tmp, OWS.E_Post, {
            A_href: base_url,
            A_type: "simple"
        })

        # ows:Constraint
        if 1 < int(OWS.version[0]):
            tmp = etree.SubElement(tmp, OWS.E_Constraint,
                                   {A_name: "PostEncoding"})
            tmp = etree.SubElement(tmp, OWS.E_AllowedValues)
            tmp = etree.SubElement(tmp, OWS.E_Value)
            tmp.text = "XML"

        # ows:Parameter
        tmp = etree.SubElement(eOp, OWS.E_Parameter, {A_name: "service"})
        tmp = etree.SubElement(tmp, OWS.E_AllowedValues)
        tmp = etree.SubElement(tmp, OWS.E_Value)
        tmp.text = "WCS"

        # ows:Parameter
        tmp = etree.SubElement(eOp, OWS.E_Parameter, {A_name: "version"})
        tmp = etree.SubElement(tmp, OWS.E_AllowedValues)
        tmp = etree.SubElement(tmp, OWS.E_Value)
        tmp.text = "1.1"

    # =====================================================================
    # return the altered payload

    return Response(content=etree.tostring(root, "UTF-8"),
                    content_type=respSrc.content_type,
                    status=respSrc.status)