redo exception handling for uploaded files
[qcg-portal.git] / filex / ftp.py
1 from datetime import datetime
2 from Queue import Queue, Empty
3 from itertools import chain
4 import os
5 import re
6 from threading import Event
7 from django.utils.http import urlunquote
8
9 from django.utils.timezone import localtime, UTC
10 from gridftp import FTPClient, Buffer, HandleAttr, OperationAttr
11
12
13 class FTPError(Exception):
14     pass
15
16
17 class FTPOperation:
18     def __init__(self, proxy=None, buffer_size=4096):
19         self._end = Event()
20         self._error = None
21         self._buffer = Buffer(buffer_size)
22
23         self.attr = HandleAttr()
24         self.op_attr = OperationAttr()
25
26         if proxy is not None:
27             self.op_attr.set_authorization(proxy)
28
29         self.cli = FTPClient(self.attr)
30
31         # limit size of a queue to 4 MB
32         self.stream = Queue((4 * 2**20) / buffer_size or 1)
33
34     def __del__(self):
35         self.attr.destroy()
36         self.op_attr.destroy()
37         self.cli.destroy()
38
39     def _read(self, arg, handle, error, buff, length, offset, eof):
40         if not error:
41             self.stream.put(str(buff))
42
43             if not eof:
44                 self.cli.register_read(self._buffer, self._read, None)
45
46     def _write(self, arg, handle, error, buff, length, offset, eof):
47         if eof or error:
48             return
49
50         chunk = self.stream.get()
51
52         if chunk is None:
53             size = 0
54             eof = True
55         else:
56             size = len(chunk)
57             self._buffer.fill(chunk)
58
59         self.cli.register_write(self._buffer, size, offset, eof, self._write, None)
60
61     def _done(self, arg, handle, error):
62         self._error = error
63         self._end.set()
64
65     def wait(self):
66         self._end.wait()
67         self._end.clear()
68
69         if self._error is not None:
70             # TODO logging
71             print 'GridFTP ERROR:', self._error
72
73             match = re.search(r'A system call failed: (.*)$', self._error.replace('\r\n', '\n'), re.MULTILINE)
74
75             msg = match.groups()[0] if match else "Unknown error"
76
77             raise FTPError(msg)
78
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)
82
83         self.wait()
84
85         result = ''
86         while not self.stream.empty():
87             result += self.stream.get()
88
89         return self._parse_mlst(result)
90
91     @staticmethod
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
95             if item:
96                 attrs, name = item.split(' ', 1)
97
98                 attrs_dict = {}
99                 for attr in attrs.split(';'):
100                     try:
101                         key, value = attr.split('=', 1)
102                         attrs_dict[key] = value
103                     except ValueError:
104                         pass
105
106                 yield {
107                     'name': name,
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())),
111                 }
112
113     def get(self, url):
114         self.cli.get(url, self._done, None, self.op_attr)
115         self.cli.register_read(self._buffer, self._read, None)
116
117         while True:
118             try:
119                 yield self.stream.get(timeout=0.1)
120             except Empty:
121                 if self._end.wait(0):
122                     break
123
124         self.wait()
125
126     def put(self, url):
127         self.cli.put(url, self._done, None, self.op_attr)
128         self.cli.register_write(self._buffer, 0, 0, False, self._write, None)
129
130     def move(self, src, dst):
131         self.cli.move(src, dst, self._done, None, self.op_attr)
132
133         self.wait()
134
135     def info(self, url):
136         data = self.listing(url).next()
137
138         if data['name'] == '.':
139             data['name'] = os.path.basename(os.path.normpath(url))
140
141         return data
142
143     def delete(self, url):
144         self.cli.delete(url, self._done, None, self.op_attr)
145
146         self.wait()
147
148     def rmdir(self, url):
149         self.cli.rmdir(url, self._done, None, self.op_attr)
150
151         self.wait()
152
153     def mkdir(self, url):
154         self.cli.mkdir(url, self._done, None, self.op_attr)
155
156         self.wait()
157
158     @staticmethod
159     def match_ext(archive, *extensions):
160         for ext in extensions:
161             if archive.endswith(ext):
162                 return True
163         return False
164
165     def compress(self, server, path, files, archive):
166         self._check_disk_stack_args(*([path, archive] + files))
167
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)))
174         else:
175             raise ValueError('Unknown archive type: {}'.format(archive))
176
177         self.op_attr.set_disk_stack('#'.join(["popen:argv=", cmd] + args))
178
179         return self.get(server)
180
181     def extract(self, server, archive, dst):
182         self._check_disk_stack_args(*[archive, dst])
183
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)
190         else:
191             raise ValueError('Unknown archive type: {}'.format(archive))
192
193         self.op_attr.set_disk_stack('#'.join(("popen:argv=", cmd) + args))
194
195         return self.get(server)
196
197     @staticmethod
198     def _check_disk_stack_args(*args):
199         for char in ['#', ',', ';', '%23', '%3B']:
200             for arg in args:
201                 if char in arg:
202                     raise ValueError('Unsupported character `{}` in `{}`!'.format(urlunquote(char), urlunquote(arg)))