uri_checker.py :  » Development » SnapLogic » snaplogic » server » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Development » SnapLogic 
SnapLogic » snaplogic » server » uri_checker.py
# $SnapHashLicense:
# 
# SnapLogic - Open source data services
# 
# Copyright (C) 2008-2009, SnapLogic, Inc.  All rights reserved.
# 
# See http://www.snaplogic.org for more information about
# the SnapLogic project. 
# 
# This program is free software, distributed under the terms of
# the GNU General Public License Version 2. See the LEGAL file
# at the top of the source tree.
# 
# "SnapLogic" is a trademark of SnapLogic, Inc.
# 
# 
# $

# $Id: uri_checker.py 9423 2009-10-22 20:28:19Z dhiraj $ 

"""
Checks to see if a given URI belongs to the server.

Surprisingly, one of the challenges faced by a server is knowing for sure if a
given URI points to itself. The reason is that a given host can have a number
of network adapters, including the loopback adapter. These adapters can have
any number of IP addresses configured on them. It will take some effort on each
platform to get the list of network adapters and then figure out the IP addresses
and hostnames associated with each of those adapters. A more reliable way
of gathering this information, is to have the server connect to the URI and see
if the request circles back to it. This code does just that for the server.
The server provides this "self check" feature which it exercises to figure
out if a given URI points to itself. Once the answer is known, the information
is cached for future requests. This service is made available to other modules
in the server and to CCs of the server.

So how does the server actually implement the self check feature?
When the server receives a target URI that must be tested, it parses out the
host/port/protocol information from it. It then creates a "self check URI" using
this information. The server also generates a pair of tokens (say A and B). Token
A is sent in a POST request to the self check URI. Any server which receives this
request should check its memory to see if token A exists (if it is the same
server, then the token would exist). If it does exist, then the server should
return token B in response to the request. If it does not exist, then a 404 is
return. When the requesting Server receives the response and gets token B, it knows
that the target URI points to itself. If it doesn't receive token B, then the
target URI probably points to some remote SnapLogic server or some other server.

"""

from __future__ import with_statement
import os
import md5
import urlparse
from threading import Lock

from snaplogic.common import uri_prefix,snap_crypt,snap_http_lib
from snaplogic.common.config import credentials_store,snap_config
from snaplogic import snapi_base
from snaplogic.snapi_base import keys
from snaplogic import server
from snaplogic.server import RhResponse


uri_cache = []
"""These URIs point to the server."""
uri_negative_cache = []
"""These URIs don't point to the server."""

challenge_response = {}
"""Holds the mapping from challenge to expected response."""

challenge_lock = Lock()
cache_lock = Lock()

my_host = None
my_port = None

def is_mine(uri, cred=None):
    """
    Returns True if the URI belong to this server, else, returns False.
    
    @param uri: The URI to be checked.
    @type uri:  str
    
    @param cred: Credentials, if any (username, password).
    @type cred:  tuple.
    
    @return: True if URI belongs to server, False if not.
    @rtype:  bool
    
    """
    global challenge_response, my_host, my_port
    parsed_uri = urlparse.urlparse(uri)
    
    if my_host is None:
        common = snap_config.get_instance().get_section('common')
        p = snap_http_lib.parse_uri(common['main_process_uri'])
        my_host = [p.hostname.lower()]
        my_port = p.port
    
    # If host and port match, don't do any further checks.
    if parsed_uri.hostname.lower() in my_host and my_port == parsed_uri.port:
        return True
    
    u = urlparse.urlunparse((parsed_uri[0].lower(), parsed_uri[1].lower(), uri_prefix.SELF_CHECK, "", "", ""))
    
    with cache_lock:
        if u in uri_cache:
            return True
        elif u in uri_negative_cache:
            return False
    
    k = snap_crypt.generate_random_string()
    v = snap_crypt.generate_random_string()
    
    with challenge_lock:
        challenge_response[k] = v

    try:
        response = snapi_base.send_req('POST', u, k)
        if response == v:
            ret = True
        else:
            ret = False
    except Exception, e:
        # Any kind of connection error indicates the URI must be of a remote server.
        ret = False
        
    finally:
        with challenge_lock:
            del challenge_response[k]
    
    with cache_lock:
        if ret:
            uri_cache.append(u)
        else:
            if len(uri_negative_cache) > 10000:
                # Don't let the negative cache get too big. This is unlikely to happen.
                del uri_negative_cache[0]
            uri_negative_cache.append(u)
        
    return ret


def process_self_check(http_req):
    """
    Return response to the check request.

    @param http_req:        HTTP request object.
    @type  http_req:        L{HttpRequest}

    @return:                RhResponse object with data and code
                            to be written to client.
    @rtype:                 L{RhResponse}
    
    """
    http_req.make_input_rp()
    
    try:
        k = http_req.input.next()
    except StopIteration:
        return RhResponse(http_req.BAD_REQUEST, "Check URI request had no key")
    
    with challenge_lock:
        v = challenge_response.get(k)
        
    return RhResponse(http_req.OK, v)


def process_uri_check(http_req):
    """
    Return response to the URI check request.

    @param http_req:        HTTP request object.
    @type  http_req:        L{HttpRequest}

    @return:                RhResponse object with data and code
                            to be written to client.
    @rtype:                 L{RhResponse}
    
    """
    http_req.make_input_rp()
    
    try:
        uri = http_req.input.next()
    except StopIteration:
        return RhResponse(http_req.BAD_REQUEST, "Check URI request had no key")
    
    ret = is_mine(uri)
    
    if ret:
        return RhResponse(http_req.OK, "URI belongs to this server")
    else:
        return RhResponse(http_req.NOT_FOUND, "URI does no to this server")
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.