blob: b04057e4d6993586ea3edf2f2dc7cce73ff2bd66 [file] [log] [blame]
Eduardo Sousa0593aba2019-06-04 12:55:43 +01001# Copyright 2019 Canonical
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may
4# not use this file except in compliance with the License. You may obtain
5# a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations
13# under the License.
14#
15# For those usages not covered by the Apache License, Version 2.0 please
16# contact: eduardo.sousa@canonical.com
17##
18
beierlmff2e8262020-07-08 16:32:50 -040019import errno
Eduardo Sousa0593aba2019-06-04 12:55:43 +010020from http import HTTPStatus
beierlmff2e8262020-07-08 16:32:50 -040021from io import BytesIO, StringIO
22import logging
Eduardo Sousa0593aba2019-06-04 12:55:43 +010023import os
lloretgallegf296d2a2020-09-02 09:36:24 +000024import datetime
bravof98fc8f02021-11-04 21:16:00 -030025import tarfile
26import zipfile
beierlmff2e8262020-07-08 16:32:50 -040027
28from gridfs import GridFSBucket, errors
Eduardo Sousa0593aba2019-06-04 12:55:43 +010029from osm_common.fsbase import FsBase, FsException
beierlmff2e8262020-07-08 16:32:50 -040030from pymongo import MongoClient
31
Eduardo Sousa0593aba2019-06-04 12:55:43 +010032
33__author__ = "Eduardo Sousa <eduardo.sousa@canonical.com>"
34
35
36class GridByteStream(BytesIO):
37 def __init__(self, filename, fs, mode):
38 BytesIO.__init__(self)
39 self._id = None
40 self.filename = filename
41 self.fs = fs
42 self.mode = mode
David Garcia7982b782020-05-20 12:09:37 +020043 self.file_type = "file" # Set "file" as default file_type
Eduardo Sousa0593aba2019-06-04 12:55:43 +010044
45 self.__initialize__()
46
47 def __initialize__(self):
48 grid_file = None
49
50 cursor = self.fs.find({"filename": self.filename})
51
52 for requested_file in cursor:
53 exception_file = next(cursor, None)
54
55 if exception_file:
garciadeblas2644b762021-03-24 09:21:01 +010056 raise FsException(
57 "Multiple files found", http_code=HTTPStatus.INTERNAL_SERVER_ERROR
58 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +010059
sousaedub95cca62020-03-12 11:12:25 +000060 if requested_file.metadata["type"] in ("file", "sym"):
Eduardo Sousa0593aba2019-06-04 12:55:43 +010061 grid_file = requested_file
sousaedub95cca62020-03-12 11:12:25 +000062 self.file_type = requested_file.metadata["type"]
Eduardo Sousa0593aba2019-06-04 12:55:43 +010063 else:
garciadeblas2644b762021-03-24 09:21:01 +010064 raise FsException(
65 "Type isn't file", http_code=HTTPStatus.INTERNAL_SERVER_ERROR
66 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +010067
68 if grid_file:
69 self._id = grid_file._id
70 self.fs.download_to_stream(self._id, self)
71
72 if "r" in self.mode:
73 self.seek(0, 0)
74
75 def close(self):
76 if "r" in self.mode:
77 super(GridByteStream, self).close()
78 return
79
80 if self._id:
81 self.fs.delete(self._id)
82
garciadeblas2644b762021-03-24 09:21:01 +010083 cursor = self.fs.find(
84 {"filename": self.filename.split("/")[0], "metadata": {"type": "dir"}}
85 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +010086
87 parent_dir = next(cursor, None)
88
89 if not parent_dir:
90 parent_dir_name = self.filename.split("/")[0]
garciadeblas2644b762021-03-24 09:21:01 +010091 self.filename = self.filename.replace(
92 parent_dir_name, parent_dir_name[:-1], 1
93 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +010094
95 self.seek(0, 0)
96 if self._id:
97 self.fs.upload_from_stream_with_id(
garciadeblas2644b762021-03-24 09:21:01 +010098 self._id, self.filename, self, metadata={"type": self.file_type}
Eduardo Sousa0593aba2019-06-04 12:55:43 +010099 )
100 else:
101 self.fs.upload_from_stream(
garciadeblas2644b762021-03-24 09:21:01 +0100102 self.filename, self, metadata={"type": self.file_type}
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100103 )
104 super(GridByteStream, self).close()
105
106 def __enter__(self):
107 return self
108
109 def __exit__(self, exc_type, exc_val, exc_tb):
110 self.close()
111
112
113class GridStringStream(StringIO):
114 def __init__(self, filename, fs, mode):
115 StringIO.__init__(self)
116 self._id = None
117 self.filename = filename
118 self.fs = fs
119 self.mode = mode
David Garcia7982b782020-05-20 12:09:37 +0200120 self.file_type = "file" # Set "file" as default file_type
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100121
122 self.__initialize__()
123
124 def __initialize__(self):
125 grid_file = None
126
127 cursor = self.fs.find({"filename": self.filename})
128
129 for requested_file in cursor:
130 exception_file = next(cursor, None)
131
132 if exception_file:
garciadeblas2644b762021-03-24 09:21:01 +0100133 raise FsException(
134 "Multiple files found", http_code=HTTPStatus.INTERNAL_SERVER_ERROR
135 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100136
sousaedub95cca62020-03-12 11:12:25 +0000137 if requested_file.metadata["type"] in ("file", "dir"):
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100138 grid_file = requested_file
sousaedub95cca62020-03-12 11:12:25 +0000139 self.file_type = requested_file.metadata["type"]
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100140 else:
garciadeblas2644b762021-03-24 09:21:01 +0100141 raise FsException(
142 "File type isn't file", http_code=HTTPStatus.INTERNAL_SERVER_ERROR
143 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100144
145 if grid_file:
146 stream = BytesIO()
147 self._id = grid_file._id
148 self.fs.download_to_stream(self._id, stream)
149 stream.seek(0)
150 self.write(stream.read().decode("utf-8"))
151 stream.close()
152
153 if "r" in self.mode:
154 self.seek(0, 0)
155
156 def close(self):
157 if "r" in self.mode:
158 super(GridStringStream, self).close()
159 return
160
161 if self._id:
162 self.fs.delete(self._id)
163
garciadeblas2644b762021-03-24 09:21:01 +0100164 cursor = self.fs.find(
165 {"filename": self.filename.split("/")[0], "metadata": {"type": "dir"}}
166 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100167
168 parent_dir = next(cursor, None)
169
170 if not parent_dir:
171 parent_dir_name = self.filename.split("/")[0]
garciadeblas2644b762021-03-24 09:21:01 +0100172 self.filename = self.filename.replace(
173 parent_dir_name, parent_dir_name[:-1], 1
174 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100175
176 self.seek(0, 0)
177 stream = BytesIO()
178 stream.write(self.read().encode("utf-8"))
179 stream.seek(0, 0)
180 if self._id:
181 self.fs.upload_from_stream_with_id(
garciadeblas2644b762021-03-24 09:21:01 +0100182 self._id, self.filename, stream, metadata={"type": self.file_type}
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100183 )
184 else:
185 self.fs.upload_from_stream(
garciadeblas2644b762021-03-24 09:21:01 +0100186 self.filename, stream, metadata={"type": self.file_type}
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100187 )
188 stream.close()
189 super(GridStringStream, self).close()
190
191 def __enter__(self):
192 return self
193
194 def __exit__(self, exc_type, exc_val, exc_tb):
195 self.close()
196
197
198class FsMongo(FsBase):
garciadeblas2644b762021-03-24 09:21:01 +0100199 def __init__(self, logger_name="fs", lock=False):
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100200 super().__init__(logger_name, lock)
201 self.path = None
202 self.client = None
203 self.fs = None
204
tiernob07e4ef2020-05-06 14:22:48 +0000205 def __update_local_fs(self, from_path=None):
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100206 dir_cursor = self.fs.find({"metadata.type": "dir"}, no_cursor_timeout=True)
207
bravoff73a9002021-11-23 10:34:43 -0300208 valid_paths = []
209
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100210 for directory in dir_cursor:
tiernob07e4ef2020-05-06 14:22:48 +0000211 if from_path and not directory.filename.startswith(from_path):
212 continue
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100213 os.makedirs(self.path + directory.filename, exist_ok=True)
bravoff73a9002021-11-23 10:34:43 -0300214 valid_paths.append(self.path + directory.filename)
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100215
garciadeblas2644b762021-03-24 09:21:01 +0100216 file_cursor = self.fs.find(
217 {"metadata.type": {"$in": ["file", "sym"]}}, no_cursor_timeout=True
218 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100219
220 for writing_file in file_cursor:
tiernob07e4ef2020-05-06 14:22:48 +0000221 if from_path and not writing_file.filename.startswith(from_path):
222 continue
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100223 file_path = self.path + writing_file.filename
David Garcia8ab6cc62020-06-26 17:04:37 +0200224
225 if writing_file.metadata["type"] == "sym":
226 with BytesIO() as b:
227 self.fs.download_to_stream(writing_file._id, b)
228 b.seek(0)
229 link = b.read().decode("utf-8")
beierlmff2e8262020-07-08 16:32:50 -0400230
231 try:
232 os.remove(file_path)
233 except OSError as e:
234 if e.errno != errno.ENOENT:
235 # This is probably permission denied or worse
236 raise
David Garcia8ab6cc62020-06-26 17:04:37 +0200237 os.symlink(link, file_path)
238 else:
bravoff73a9002021-11-23 10:34:43 -0300239 folder = os.path.dirname(file_path)
240 if folder not in valid_paths:
241 os.makedirs(folder, exist_ok=True)
garciadeblas2644b762021-03-24 09:21:01 +0100242 with open(file_path, "wb+") as file_stream:
David Garcia8ab6cc62020-06-26 17:04:37 +0200243 self.fs.download_to_stream(writing_file._id, file_stream)
244 if "permissions" in writing_file.metadata:
sousaedub95cca62020-03-12 11:12:25 +0000245 os.chmod(file_path, writing_file.metadata["permissions"])
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100246
247 def get_params(self):
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100248 return {"fs": "mongo", "path": self.path}
249
250 def fs_connect(self, config):
251 try:
252 if "logger_name" in config:
253 self.logger = logging.getLogger(config["logger_name"])
254 if "path" in config:
255 self.path = config["path"]
256 else:
garciadeblas2644b762021-03-24 09:21:01 +0100257 raise FsException('Missing parameter "path"')
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100258 if not self.path.endswith("/"):
259 self.path += "/"
260 if not os.path.exists(self.path):
garciadeblas2644b762021-03-24 09:21:01 +0100261 raise FsException(
262 "Invalid configuration param at '[storage]': path '{}' does not exist".format(
263 config["path"]
264 )
265 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100266 elif not os.access(self.path, os.W_OK):
garciadeblas2644b762021-03-24 09:21:01 +0100267 raise FsException(
268 "Invalid configuration param at '[storage]': path '{}' is not writable".format(
269 config["path"]
270 )
271 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100272 if all(key in config.keys() for key in ["uri", "collection"]):
273 self.client = MongoClient(config["uri"])
274 self.fs = GridFSBucket(self.client[config["collection"]])
275 elif all(key in config.keys() for key in ["host", "port", "collection"]):
276 self.client = MongoClient(config["host"], config["port"])
277 self.fs = GridFSBucket(self.client[config["collection"]])
278 else:
279 if "collection" not in config.keys():
garciadeblas2644b762021-03-24 09:21:01 +0100280 raise FsException('Missing parameter "collection"')
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100281 else:
garciadeblas2644b762021-03-24 09:21:01 +0100282 raise FsException('Missing parameters: "uri" or "host" + "port"')
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100283 except FsException:
284 raise
285 except Exception as e: # TODO refine
286 raise FsException(str(e))
287
288 def fs_disconnect(self):
289 pass # TODO
290
291 def mkdir(self, folder):
292 """
293 Creates a folder or parent object location
294 :param folder:
295 :return: None or raises an exception
296 """
297 try:
garciadeblas2644b762021-03-24 09:21:01 +0100298 self.fs.upload_from_stream(folder, BytesIO(), metadata={"type": "dir"})
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100299 except errors.FileExists: # make it idempotent
300 pass
301 except Exception as e:
302 raise FsException(str(e), http_code=HTTPStatus.INTERNAL_SERVER_ERROR)
303
304 def dir_rename(self, src, dst):
305 """
306 Rename one directory name. If dst exist, it replaces (deletes) existing directory
307 :param src: source directory
308 :param dst: destination directory
309 :return: None or raises and exception
310 """
311 try:
312 dst_cursor = self.fs.find(
garciadeblas2644b762021-03-24 09:21:01 +0100313 {"filename": {"$regex": "^{}(/|$)".format(dst)}}, no_cursor_timeout=True
314 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100315
316 for dst_file in dst_cursor:
317 self.fs.delete(dst_file._id)
318
319 src_cursor = self.fs.find(
garciadeblas2644b762021-03-24 09:21:01 +0100320 {"filename": {"$regex": "^{}(/|$)".format(src)}}, no_cursor_timeout=True
321 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100322
323 for src_file in src_cursor:
324 self.fs.rename(src_file._id, src_file.filename.replace(src, dst, 1))
325 except Exception as e:
326 raise FsException(str(e), http_code=HTTPStatus.INTERNAL_SERVER_ERROR)
327
328 def file_exists(self, storage, mode=None):
329 """
330 Indicates if "storage" file exist
331 :param storage: can be a str or a str list
332 :param mode: can be 'file' exist as a regular file; 'dir' exists as a directory or; 'None' just exists
333 :return: True, False
334 """
335 f = storage if isinstance(storage, str) else "/".join(storage)
336
337 cursor = self.fs.find({"filename": f})
338
339 for requested_file in cursor:
340 exception_file = next(cursor, None)
341
342 if exception_file:
garciadeblas2644b762021-03-24 09:21:01 +0100343 raise FsException(
344 "Multiple files found", http_code=HTTPStatus.INTERNAL_SERVER_ERROR
345 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100346
bravof98fc8f02021-11-04 21:16:00 -0300347 print(requested_file.metadata)
348
lloretgallegf296d2a2020-09-02 09:36:24 +0000349 # if no special mode is required just check it does exists
350 if not mode:
351 return True
352
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100353 if requested_file.metadata["type"] == mode:
354 return True
beierlmff2e8262020-07-08 16:32:50 -0400355
sousaedub95cca62020-03-12 11:12:25 +0000356 if requested_file.metadata["type"] == "sym" and mode == "file":
357 return True
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100358
359 return False
360
361 def file_size(self, storage):
362 """
363 return file size
364 :param storage: can be a str or a str list
365 :return: file size
366 """
367 f = storage if isinstance(storage, str) else "/".join(storage)
368
369 cursor = self.fs.find({"filename": f})
370
371 for requested_file in cursor:
372 exception_file = next(cursor, None)
373
374 if exception_file:
garciadeblas2644b762021-03-24 09:21:01 +0100375 raise FsException(
376 "Multiple files found", http_code=HTTPStatus.INTERNAL_SERVER_ERROR
377 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100378
379 return requested_file.length
380
bravof98fc8f02021-11-04 21:16:00 -0300381 def file_extract(self, compressed_object, path):
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100382 """
383 extract a tar file
bravof98fc8f02021-11-04 21:16:00 -0300384 :param compressed_object: object of type tar or zip
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100385 :param path: can be a str or a str list, or a tar object where to extract the tar_object
386 :return: None
387 """
388 f = path if isinstance(path, str) else "/".join(path)
389
bravof98fc8f02021-11-04 21:16:00 -0300390 if type(compressed_object) is tarfile.TarFile:
391 for member in compressed_object.getmembers():
392 if member.isfile():
393 stream = compressed_object.extractfile(member)
394 elif member.issym():
395 stream = BytesIO(member.linkname.encode("utf-8"))
396 else:
397 stream = BytesIO()
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100398
bravof98fc8f02021-11-04 21:16:00 -0300399 if member.isfile():
400 file_type = "file"
401 elif member.issym():
402 file_type = "sym"
403 else:
404 file_type = "dir"
sousaedub95cca62020-03-12 11:12:25 +0000405
bravof98fc8f02021-11-04 21:16:00 -0300406 metadata = {"type": file_type, "permissions": member.mode}
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100407
bravof98fc8f02021-11-04 21:16:00 -0300408 self.fs.upload_from_stream(
409 f + "/" + member.name, stream, metadata=metadata
410 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100411
bravof98fc8f02021-11-04 21:16:00 -0300412 stream.close()
413 elif type(compressed_object) is zipfile.ZipFile:
414 for member in compressed_object.infolist():
415 if member.is_dir():
416 stream = BytesIO()
417 else:
418 stream = compressed_object.read(member)
419
420 if member.is_dir():
421 file_type = "dir"
422 else:
423 file_type = "file"
424
425 metadata = {"type": file_type}
426
427 print("Now uploading...")
428 print(f + "/" + member.filename)
429 self.fs.upload_from_stream(
430 f + "/" + member.filename, stream, metadata=metadata
431 )
432
433 if member.is_dir():
434 stream.close()
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100435
436 def file_open(self, storage, mode):
437 """
438 Open a file
439 :param storage: can be a str or list of str
440 :param mode: file mode
441 :return: file object
442 """
443 try:
444 f = storage if isinstance(storage, str) else "/".join(storage)
445
446 if "b" in mode:
447 return GridByteStream(f, self.fs, mode)
448 else:
449 return GridStringStream(f, self.fs, mode)
450 except errors.NoFile:
garciadeblas2644b762021-03-24 09:21:01 +0100451 raise FsException(
452 "File {} does not exist".format(f), http_code=HTTPStatus.NOT_FOUND
453 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100454 except IOError:
garciadeblas2644b762021-03-24 09:21:01 +0100455 raise FsException(
456 "File {} cannot be opened".format(f), http_code=HTTPStatus.BAD_REQUEST
457 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100458
459 def dir_ls(self, storage):
460 """
461 return folder content
462 :param storage: can be a str or list of str
463 :return: folder content
464 """
465 try:
466 f = storage if isinstance(storage, str) else "/".join(storage)
467
468 files = []
469 dir_cursor = self.fs.find({"filename": f})
470 for requested_dir in dir_cursor:
471 exception_dir = next(dir_cursor, None)
472
473 if exception_dir:
garciadeblas2644b762021-03-24 09:21:01 +0100474 raise FsException(
475 "Multiple directories found",
476 http_code=HTTPStatus.INTERNAL_SERVER_ERROR,
477 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100478
479 if requested_dir.metadata["type"] != "dir":
garciadeblas2644b762021-03-24 09:21:01 +0100480 raise FsException(
481 "File {} does not exist".format(f),
482 http_code=HTTPStatus.NOT_FOUND,
483 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100484
bravof98fc8f02021-11-04 21:16:00 -0300485 if f.endswith("/"):
486 f = f[:-1]
487
garciadeblas2644b762021-03-24 09:21:01 +0100488 files_cursor = self.fs.find(
489 {"filename": {"$regex": "^{}/([^/])*".format(f)}}
490 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100491 for children_file in files_cursor:
garciadeblas2644b762021-03-24 09:21:01 +0100492 files += [children_file.filename.replace(f + "/", "", 1)]
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100493
494 return files
495 except IOError:
garciadeblas2644b762021-03-24 09:21:01 +0100496 raise FsException(
497 "File {} cannot be opened".format(f), http_code=HTTPStatus.BAD_REQUEST
498 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100499
500 def file_delete(self, storage, ignore_non_exist=False):
501 """
502 Delete storage content recursively
503 :param storage: can be a str or list of str
504 :param ignore_non_exist: not raise exception if storage does not exist
505 :return: None
506 """
507 try:
508 f = storage if isinstance(storage, str) else "/".join(storage)
509
510 file_cursor = self.fs.find({"filename": f})
511 found = False
512 for requested_file in file_cursor:
513 found = True
514 exception_file = next(file_cursor, None)
515
516 if exception_file:
garciadeblas2644b762021-03-24 09:21:01 +0100517 raise FsException(
518 "Multiple files found",
519 http_code=HTTPStatus.INTERNAL_SERVER_ERROR,
520 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100521
522 if requested_file.metadata["type"] == "dir":
523 dir_cursor = self.fs.find({"filename": {"$regex": "^{}".format(f)}})
524
525 for tmp in dir_cursor:
526 self.fs.delete(tmp._id)
527 else:
528 self.fs.delete(requested_file._id)
529 if not found and not ignore_non_exist:
garciadeblas2644b762021-03-24 09:21:01 +0100530 raise FsException(
531 "File {} does not exist".format(storage),
532 http_code=HTTPStatus.NOT_FOUND,
533 )
Eduardo Sousa0593aba2019-06-04 12:55:43 +0100534 except IOError as e:
garciadeblas2644b762021-03-24 09:21:01 +0100535 raise FsException(
536 "File {} cannot be deleted: {}".format(f, e),
537 http_code=HTTPStatus.INTERNAL_SERVER_ERROR,
538 )
David Garcia788b9d62020-01-20 13:21:06 +0100539
tiernob07e4ef2020-05-06 14:22:48 +0000540 def sync(self, from_path=None):
David Garcia788b9d62020-01-20 13:21:06 +0100541 """
542 Sync from FSMongo to local storage
tiernob07e4ef2020-05-06 14:22:48 +0000543 :param from_path: if supplied, only copy content from this path, not all
544 :return: None
David Garcia788b9d62020-01-20 13:21:06 +0100545 """
lloretgallegf296d2a2020-09-02 09:36:24 +0000546 if from_path:
547 if os.path.isabs(from_path):
548 from_path = os.path.relpath(from_path, self.path)
tiernob07e4ef2020-05-06 14:22:48 +0000549 self.__update_local_fs(from_path=from_path)
lloretgallegf296d2a2020-09-02 09:36:24 +0000550
551 def _update_mongo_fs(self, from_path):
552
553 os_path = self.path + from_path
554
555 # Obtain list of files and dirs in filesystem
556 members = []
557 for root, dirs, files in os.walk(os_path):
558 for folder in dirs:
garciadeblas2644b762021-03-24 09:21:01 +0100559 member = {"filename": os.path.join(root, folder), "type": "dir"}
lloretgallegf296d2a2020-09-02 09:36:24 +0000560 members.append(member)
561 for file in files:
562 filename = os.path.join(root, file)
563 if os.path.islink(filename):
564 file_type = "sym"
565 else:
566 file_type = "file"
garciadeblas2644b762021-03-24 09:21:01 +0100567 member = {"filename": os.path.join(root, file), "type": file_type}
lloretgallegf296d2a2020-09-02 09:36:24 +0000568 members.append(member)
569
570 # Obtain files in mongo dict
571 remote_files = self._get_mongo_files(from_path)
572
573 # Upload members if they do not exists or have been modified
574 # We will do this for performance (avoid updating unmodified files) and to avoid
575 # updating a file with an older one in case there are two sources for synchronization
576 # in high availability scenarios
577 for member in members:
578 # obtain permission
579 mask = int(oct(os.stat(member["filename"]).st_mode)[-3:], 8)
580
581 # convert to relative path
582 rel_filename = os.path.relpath(member["filename"], self.path)
garciadeblas2644b762021-03-24 09:21:01 +0100583 last_modified_date = datetime.datetime.fromtimestamp(
584 os.path.getmtime(member["filename"])
585 )
lloretgallegf296d2a2020-09-02 09:36:24 +0000586
587 remote_file = remote_files.get(rel_filename)
garciadeblas2644b762021-03-24 09:21:01 +0100588 upload_date = (
589 remote_file[0].uploadDate if remote_file else datetime.datetime.min
590 )
lloretgallegf296d2a2020-09-02 09:36:24 +0000591 # remove processed files from dict
592 remote_files.pop(rel_filename, None)
593
594 if last_modified_date >= upload_date:
595
596 stream = None
597 fh = None
598 try:
599 file_type = member["type"]
600 if file_type == "dir":
601 stream = BytesIO()
602 elif file_type == "sym":
garciadeblas2644b762021-03-24 09:21:01 +0100603 stream = BytesIO(
604 os.readlink(member["filename"]).encode("utf-8")
605 )
lloretgallegf296d2a2020-09-02 09:36:24 +0000606 else:
607 fh = open(member["filename"], "rb")
608 stream = BytesIO(fh.read())
609
garciadeblas2644b762021-03-24 09:21:01 +0100610 metadata = {"type": file_type, "permissions": mask}
lloretgallegf296d2a2020-09-02 09:36:24 +0000611
garciadeblas2644b762021-03-24 09:21:01 +0100612 self.fs.upload_from_stream(rel_filename, stream, metadata=metadata)
lloretgallegf296d2a2020-09-02 09:36:24 +0000613
614 # delete old files
615 if remote_file:
616 for file in remote_file:
617 self.fs.delete(file._id)
618 finally:
619 if fh:
620 fh.close()
621 if stream:
622 stream.close()
623
624 # delete files that are not any more in local fs
625 for remote_file in remote_files.values():
626 for file in remote_file:
627 self.fs.delete(file._id)
628
629 def _get_mongo_files(self, from_path=None):
630
631 file_dict = {}
garciadeblas2644b762021-03-24 09:21:01 +0100632 file_cursor = self.fs.find(no_cursor_timeout=True, sort=[("uploadDate", -1)])
lloretgallegf296d2a2020-09-02 09:36:24 +0000633 for file in file_cursor:
634 if from_path and not file.filename.startswith(from_path):
635 continue
636 if file.filename in file_dict:
637 file_dict[file.filename].append(file)
638 else:
639 file_dict[file.filename] = [file]
640 return file_dict
641
642 def reverse_sync(self, from_path: str):
643 """
644 Sync from local storage to FSMongo
645 :param from_path: base directory to upload content to mongo fs
646 :return: None
647 """
648 if os.path.isabs(from_path):
649 from_path = os.path.relpath(from_path, self.path)
650 self._update_mongo_fs(from_path=from_path)