Back to index

nordugrid-arc-nox  1.1.0~rc6
slave.py
Go to the documentation of this file.
00001 from mod_python import apache
00002 import os,sys
00003 
00004 CHUNK_SIZE=2**20
00005 
00006 # Generator to buffer file chunks
00007 def fbuffer(f, chunk_size=10000):
00008    while True:
00009       chunk = f.read(chunk_size)
00010       if not chunk: break
00011       yield chunk
00012 
00013 
00014 def handler(req):
00015     """
00016     Function handling apache slave mode
00017     Checks if requested hardlink exists, opens file, deletes
00018     hardlink from server and PUTs or GETs requested file
00019     """
00020 
00021     req.allow_methods(['M_PUT','M_GET'])
00022 
00023     if req.filename.endswith('.transfering'):
00024         raise apache.SERVER_RETURN, apache.HTTP_FORBIDDEN
00025 
00026     if os.path.isfile(req.filename) and not req.filename.endswith('.py'):
00027 
00028         req_method = req.the_request[:3]
00029 
00030         tmp_filename=req.filename+'.transfering'
00031 
00032         if req_method == 'GET':
00033             f = open(req.filename, 'rb', CHUNK_SIZE)
00034         elif req_method == 'PUT':
00035             f = open(req.filename, 'ab', CHUNK_SIZE)
00036 
00037         os.rename(req.filename, tmp_filename)
00038 
00039         if req_method == 'GET':
00040             for chunk in fbuffer(f):
00041                 req.write(chunk)
00042 
00043         elif req_method == 'PUT':
00044             for chunk in fbuffer(req):
00045                 f.write(chunk)
00046 
00047         
00048         if req_method == 'GET':
00049            if req.headers_in.get("range", "").startswith("bytes=%ld"%f.tell()):
00050               os.remove(tmp_filename)
00051            else:
00052               os.rename(tmp_filename, req.filename)
00053         elif req_method == 'PUT':
00054            if req.headers_in.get("Content-Range", "").endswith(str(f.tell())):
00055               os.remove(tmp_filename)
00056            else:
00057               os.rename(tmp_filename, req.filename)
00058         f.close()
00059         return apache.OK
00060         
00061 
00062     else:
00063         raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND