1 from datetime import datetime
2 from Queue import Queue, Empty
3 from itertools import chain
6 from threading import Event
7 from django.utils.http import urlunquote
9 from django.utils.timezone import localtime, UTC
10 from gridftp import FTPClient, Buffer, HandleAttr, OperationAttr
13 class FTPException(Exception):
18 def __init__(self, proxy=None, buffer_size=4096):
21 self._buffer = Buffer(buffer_size)
23 self.attr = HandleAttr()
24 self.op_attr = OperationAttr()
27 self.op_attr.set_authorization(proxy)
29 self.cli = FTPClient(self.attr)
31 # limit size of a queue to 4 MB
32 self.stream = Queue((4 * 2**20) / buffer_size or 1)
36 self.op_attr.destroy()
39 def _read(self, arg, handle, error, buff, length, offset, eof):
41 self.stream.put(str(buff))
44 self.cli.register_read(self._buffer, self._read, None)
46 def _write(self, arg, handle, error, buff, length, offset, eof):
50 chunk = self.stream.get()
57 self._buffer.fill(chunk)
59 self.cli.register_write(self._buffer, size, offset, eof, self._write, None)
61 def _done(self, arg, handle, error):
69 if self._error is not None:
71 print 'GridFTP ERROR:', self._error
73 match = re.search(r'A system call failed: (.*)$', self._error.replace('\r\n', '\n'), re.MULTILINE)
75 msg = match.groups()[0] if match else "Unknown error"
77 raise FTPException(msg)
79 def listing(self, url):
80 self.cli.verbose_list(url, self._done, None, self.op_attr)
81 self.cli.register_read(self._buffer, self._read, None)
86 while not self.stream.empty():
87 result += self.stream.get()
89 return self._parse_mlst(result)
92 def _parse_mlst(listing):
93 for item in listing.strip().splitlines():
94 # we may receive empty string when there are multiple consecutive newlines in listing
96 attrs, name = item.split(' ', 1)
99 for attr in attrs.split(';'):
101 key, value = attr.split('=', 1)
102 attrs_dict[key] = value
108 'type': 'directory' if attrs_dict['Type'] == 'dir' else 'file',
109 'size': int(attrs_dict['Size']),
110 'date': localtime(datetime.strptime(attrs_dict['Modify'], "%Y%m%d%H%M%S").replace(tzinfo=UTC())),
114 self.cli.get(url, self._done, None, self.op_attr)
115 self.cli.register_read(self._buffer, self._read, None)
119 yield self.stream.get(timeout=0.1)
121 if self._end.wait(0):
127 self.cli.put(url, self._done, None, self.op_attr)
128 self.cli.register_write(self._buffer, 0, 0, False, self._write, None)
130 def move(self, src, dst):
131 self.cli.move(src, dst, self._done, None, self.op_attr)
136 data = self.listing(url).next()
138 if data['name'] == '.':
139 data['name'] = os.path.basename(os.path.normpath(url))
143 def delete(self, url):
144 self.cli.delete(url, self._done, None, self.op_attr)
148 def rmdir(self, url):
149 self.cli.rmdir(url, self._done, None, self.op_attr)
153 def mkdir(self, url):
154 self.cli.mkdir(url, self._done, None, self.op_attr)
159 def match_ext(archive, *extensions):
160 for ext in extensions:
161 if archive.endswith(ext):
165 def compress(self, server, path, files, archive):
166 self._check_disk_stack_args(*([path, archive] + files))
168 if self.match_ext(archive, '.tar.gz', '.tgz'):
169 cmd, args = 'tar', ['cvzf', archive, '-C', path] + files
170 elif self.match_ext(archive, '.tar.bz2', '.tbz'):
171 cmd, args = 'tar', ['cvjf', archive, '-C', path] + files
172 elif self.match_ext(archive, '.zip'):
173 cmd, args = 'jar', (['cvMf', archive] + list(chain.from_iterable(('-C', path, f) for f in files)))
175 raise ValueError('Unknown archive type: {}'.format(archive))
177 self.op_attr.set_disk_stack('#'.join(["popen:argv=", cmd] + args))
179 return self.get(server)
181 def extract(self, server, archive, dst):
182 self._check_disk_stack_args(*[archive, dst])
184 if self.match_ext(archive, '.tar.gz', '.tgz'):
185 cmd, args = 'tar', ('xvzf', archive, '-C', dst)
186 elif self.match_ext(archive, '.tar.bz2', '.tbz'):
187 cmd, args = 'tar', ('xvjf', archive, '-C', dst)
188 elif self.match_ext(archive, '.zip'):
189 cmd, args = 'unzip', (archive, '-d', dst)
191 raise ValueError('Unknown archive type: {}'.format(archive))
193 self.op_attr.set_disk_stack('#'.join(("popen:argv=", cmd) + args))
195 return self.get(server)
198 def _check_disk_stack_args(*args):
199 for char in ['#', ',', ';', '%23', '%3B']:
202 raise ValueError('Unsupported character `{}` in `{}`!'.format(urlunquote(char), urlunquote(arg)))