1 from datetime import datetime
2 from Queue import Queue, Empty
3 from itertools import chain
6 from threading import Event
8 from django.utils.timezone import localtime, UTC
9 from gridftp import FTPClient, Buffer, HandleAttr, OperationAttr
12 class FTPException(Exception):
17 def __init__(self, proxy=None, buffer_size=4096):
20 self._buffer = Buffer(buffer_size)
22 self.attr = HandleAttr()
23 self.op_attr = OperationAttr()
26 self.op_attr.set_authorization(proxy)
28 self.cli = FTPClient(self.attr)
30 # limit size of a queue to 4 MB
31 self.stream = Queue((4 * 2**20) / buffer_size or 1)
35 self.op_attr.destroy()
38 def _read(self, arg, handle, error, buff, length, offset, eof):
40 self.stream.put(str(buff))
43 self.cli.register_read(self._buffer, self._read, None)
45 def _write(self, arg, handle, error, buff, length, offset, eof):
49 chunk = self.stream.get()
56 self._buffer.fill(chunk)
58 self.cli.register_write(self._buffer, size, offset, eof, self._write, None)
60 def _done(self, arg, handle, error):
68 if self._error is not None:
70 print 'GridFTP ERROR:', self._error
72 match = re.search(r'A system call failed: (.*)$', self._error.replace('\r\n', '\n'), re.MULTILINE)
74 msg = match.groups()[0] if match else "Unknown error"
76 raise FTPException(msg)
78 def listing(self, url):
79 self.cli.verbose_list(url, self._done, None, self.op_attr)
80 self.cli.register_read(self._buffer, self._read, None)
85 while not self.stream.empty():
86 result += self.stream.get()
88 return self._parse_mlst(result)
91 def _parse_mlst(listing):
92 for item in listing.strip().splitlines():
93 # we may receive empty string when there are multiple consecutive newlines in listing
95 attrs, name = item.split(' ', 1)
98 for attr in attrs.split(';'):
100 key, value = attr.split('=', 1)
101 attrs_dict[key] = value
107 'type': 'directory' if attrs_dict['Type'] == 'dir' else 'file',
108 'size': int(attrs_dict['Size']),
109 'date': localtime(datetime.strptime(attrs_dict['Modify'], "%Y%m%d%H%M%S").replace(tzinfo=UTC())),
113 self.cli.get(url, self._done, None, self.op_attr)
114 self.cli.register_read(self._buffer, self._read, None)
118 yield self.stream.get(timeout=0.1)
120 if self._end.wait(0):
126 self.cli.put(url, self._done, None, self.op_attr)
127 self.cli.register_write(self._buffer, 0, 0, False, self._write, None)
129 def move(self, src, dst):
130 self.cli.move(src, dst, self._done, None, self.op_attr)
135 data = self.listing(url).next()
137 if data['name'] == '.':
138 data['name'] = os.path.basename(os.path.normpath(url))
142 def delete(self, url):
143 self.cli.delete(url, self._done, None, self.op_attr)
147 def rmdir(self, url):
148 self.cli.rmdir(url, self._done, None, self.op_attr)
152 def mkdir(self, url):
153 self.cli.mkdir(url, self._done, None, self.op_attr)
158 def match_ext(archive, *extensions):
159 for ext in extensions:
160 if archive.endswith(ext):
164 def compress(self, server, path, files, archive):
165 for value in [path, archive] + files:
167 raise ValueError('Illegal character `#` in {}'.format(value))
169 if self.match_ext(archive, '.tar.gz', '.tgz'):
170 cmd, args = 'tar', ['cvzf', archive, '-C', path] + files
171 elif self.match_ext(archive, '.tar.bz2', '.tbz'):
172 cmd, args = 'tar', ['cvjf', archive, '-C', path] + files
173 elif self.match_ext(archive, '.zip'):
174 cmd, args = 'jar', (['cvMf', archive] + list(chain.from_iterable(('-C', path, f) for f in files)))
176 raise ValueError('Unknown archive type: {}'.format(archive))
178 self.op_attr.set_disk_stack('#'.join(["popen:argv=", cmd] + args))
180 return self.get(server)
182 def extract(self, server, archive, dst):
183 for value in [archive, dst]:
185 raise ValueError('Illegal character `#` in {}'.format(value))
187 if self.match_ext(archive, '.tar.gz', '.tgz'):
188 cmd, args = 'tar', ('xvzf', archive, '-C', dst)
189 elif self.match_ext(archive, '.tar.bz2', '.tbz'):
190 cmd, args = 'tar', ('xvjf', archive, '-C', dst)
191 elif self.match_ext(archive, '.zip'):
192 cmd, args = 'unzip', (archive, '-d', dst)
194 raise ValueError('Unknown archive type: {}'.format(archive))
196 self.op_attr.set_disk_stack('#'.join(("popen:argv=", cmd) + args))
198 return self.get(server)