source: MILK/trunk/milk_server/milk_server/lib/ndgInterface.py @ 4469

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/MILK/trunk/milk_server/milk_server/lib/ndgInterface.py@4469
Revision 4469, 5.5 KB checked in by cbyrom, 12 years ago (diff)

Strip out code not relevant to MILK - mainly WCS and WMS stuff - also including the CSML server code + trackback code
Also tidy up structure of 'public' dir - setting up new 'style' dir and
centralising icons in icons dir + remove all unused icons, javascript and stylesheets.
Also strip out testcase code and populate new test directory structure.

Line 
1# Copyright (C) 2007 STFC & NERC (Science and Technology Facilities Council).
2# This software may be distributed under the terms of the
3# Q Public License, version 1.0 or later.
4# http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt
5"""
6Manages interface to NDG documents and data, including caching
7"""
8
9from cache import Cache
10from csml_cache import CSMLExtractCache
11import os, tempfile, logging
12import csml
13try:
14    import cdms2 as cdms
15except:
16    import cdms
17from ndgUtils import ndgRetrieve, ndgObject, xmlHandler2
18from pylons import request,session
19
20from pylons import g # for handle to access control PEP interface
21try:
22    from ndg.security.common.authz.pdp import PDPError
23    from ndg.security.common.authz.pep import PEPError
24except ImportError, e:
25    from warnings import warn
26    warn(__name__ + ": access control is disabled: %s" % e, RuntimeWarning)
27
28class ndgInterface:
29   
30    def __init__(self):
31        ''' Instantiate with three level cache:
32                - a file cache
33                - a xmlhandler object cache, and
34                - a parsed CSML object cache.'''
35
36        self.CSMLDataCache=CSMLExtractCache(
37                request.environ['paste.config']['app_conf']['tmp_dir'],max_size=10)
38        self.CSMLDocCache=Cache(max_size=10)
39        self.XMLHCache=Cache(max_size=10)
40       
41
42    def GetXML(self,uri,outputSchema='', useCache=True):
43        '''
44        This method provides a secure interface to the server
45        document cache and a remote NDG exist. It is assumed that
46        the local filesystem is protected in that you can't get to
47        files except via the CSML api
48        @param uri: ndg format uri to locate doc from
49        @keyword outputSchema: format to return doc in
50        @keyword useCache: check for data in the cache and use this, if set to
51        True (the default)   
52        '''
53        #    Note that this method should not be used to obtain
54        #unsecured discovery documents, these are called directly
55        #in the retrieve controller!
56
57        logging.info("Getting XML from uri, '%s' (outputschema: '%s')" \
58                     %(uri, outputSchema))
59        try:
60            ndgO=ndgObject(uri)
61            localFile=0
62        except ValueError:
63            ''' It's a local file not an ndg identifier '''
64            logging.info("File appears to be local - look for it there...")
65            ndgO=uri
66            localFile=1
67       
68        if session and 'ndgCleared' in session:
69            cleared=session['ndgCleared']
70        else:
71            cleared=None
72       
73        if outputSchema or not useCache:
74            #bypass the cache ...
75            status,xmlh=ndgRetrieve(ndgO,
76                                    request.environ['ndgConfig'],
77                                    output=outputSchema,
78                                    discovery=g.standalone)
79        else:
80            try:
81                xmlh=self.XMLHCache[uri]
82                status=1
83                logging.info('XMLH Cache hit for [%s]'%uri)
84            except:
85                logging.info('XMLH Cache miss for [%s]'%uri)
86                if localFile:
87                    status,xmlH=self.__getLocal(uri)
88                else:   
89                    status,xmlh=ndgRetrieve(ndgO,
90                                            request.environ['ndgConfig'],
91                                            output=outputSchema,
92                                            discovery=g.standalone)
93                if status: 
94                    self.XMLHCache[uri]=xmlh
95           
96        if not status: return status,xmlh
97       
98        # convert doc to an XML tree
99        xmlh=xmlHandler2.xmlHandler(xmlh,string=1)
100       
101        # valid values of the return objects SHOULD BE
102        #   ok:         status=1, xmlh=an xml handler instance.
103        #   exceptions, status=0, xmlh='Exception(e)'
104       
105        status,xmlh=self.__gatekeep(ndgO,xmlh)
106        if status:
107            if cleared is None:
108                session['ndgCleared']=[uri]
109            else:
110                session['ndgCleared'].append(uri)
111            session.save()
112       
113        return status,xmlh
114           
115
116    def __gatekeep(self,uri,x):
117        ''' This is the NDG gatekeeper '''
118        if 'ndgSec' in session:
119            securityTokens=session['ndgSec']
120        else:
121            securityTokens=None
122
123        if not hasattr(g, 'pep'):
124            if not g.standalone:
125                raise PEPError(\
126                "Security is disabled but the standalone flag is set to False")
127               
128            logging.info("__gatekeep: access control is disabled - standalone " + \
129                     "config flag is set")
130           
131        try:
132            # Arguments are: a handle to the resource and a handle to the users
133            # security tokens
134            g.pep(dict(uri=uri, doc=x), securityTokens, None)
135            return True, x
136       
137        except PDPError, e:
138            # Caught a known access control condition
139            return False, 'Access Denied for %s %s' % (uri, e)
140
141               
142    def __getLocal(self,uri):
143        ''' Returns a local csml file (used for testing) '''
144        csml_dir = request.environ['paste.config']['app_conf']['csml_dir']
145        path = os.path.join(csml_dir, file)
146        if os.path.exists(path+'.csml'):
147            f = path+'.csml'
148        elif os.path.exists(path+'.xml'):
149            f = path +'.xml'
150        else:
151            return 0, '<p>Cannot find CSML file %s</p>' % file
152        r=f.read()
153        return 1,r     
154       
155
156
157interface=ndgInterface()
Note: See TracBrowser for help on using the repository browser.