d92384243997d242e59f6b342544f114d5c708e5
1 # Copyright 2019 Canonical
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
15 # For those usages not covered by the Apache License, Version 2.0 please
16 # contact: eduardo.sousa@canonical.com
20 from http
import HTTPStatus
21 from io
import BytesIO
, StringIO
28 from gridfs
import GridFSBucket
, errors
29 from osm_common
.fsbase
import FsBase
, FsException
30 from pymongo
import MongoClient
33 __author__
= "Eduardo Sousa <eduardo.sousa@canonical.com>"
36 class GridByteStream(BytesIO
):
37 def __init__(self
, filename
, fs
, mode
):
38 BytesIO
.__init
__(self
)
40 self
.filename
= filename
43 self
.file_type
= "file" # Set "file" as default file_type
47 def __initialize__(self
):
50 cursor
= self
.fs
.find({"filename": self
.filename
})
52 for requested_file
in cursor
:
53 exception_file
= next(cursor
, None)
57 "Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
60 if requested_file
.metadata
["type"] in ("file", "sym"):
61 grid_file
= requested_file
62 self
.file_type
= requested_file
.metadata
["type"]
65 "Type isn't file", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
69 self
._id
= grid_file
._id
70 self
.fs
.download_to_stream(self
._id
, self
)
77 super(GridByteStream
, self
).close()
81 self
.fs
.delete(self
._id
)
83 cursor
= self
.fs
.find(
84 {"filename": self
.filename
.split("/")[0], "metadata": {"type": "dir"}}
87 parent_dir
= next(cursor
, None)
90 parent_dir_name
= self
.filename
.split("/")[0]
91 self
.filename
= self
.filename
.replace(
92 parent_dir_name
, parent_dir_name
[:-1], 1
97 self
.fs
.upload_from_stream_with_id(
98 self
._id
, self
.filename
, self
, metadata
={"type": self
.file_type
}
101 self
.fs
.upload_from_stream(
102 self
.filename
, self
, metadata
={"type": self
.file_type
}
104 super(GridByteStream
, self
).close()
109 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
113 class GridStringStream(StringIO
):
114 def __init__(self
, filename
, fs
, mode
):
115 StringIO
.__init
__(self
)
117 self
.filename
= filename
120 self
.file_type
= "file" # Set "file" as default file_type
122 self
.__initialize
__()
124 def __initialize__(self
):
127 cursor
= self
.fs
.find({"filename": self
.filename
})
129 for requested_file
in cursor
:
130 exception_file
= next(cursor
, None)
134 "Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
137 if requested_file
.metadata
["type"] in ("file", "dir"):
138 grid_file
= requested_file
139 self
.file_type
= requested_file
.metadata
["type"]
142 "File type isn't file", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
147 self
._id
= grid_file
._id
148 self
.fs
.download_to_stream(self
._id
, stream
)
150 self
.write(stream
.read().decode("utf-8"))
158 super(GridStringStream
, self
).close()
162 self
.fs
.delete(self
._id
)
164 cursor
= self
.fs
.find(
165 {"filename": self
.filename
.split("/")[0], "metadata": {"type": "dir"}}
168 parent_dir
= next(cursor
, None)
171 parent_dir_name
= self
.filename
.split("/")[0]
172 self
.filename
= self
.filename
.replace(
173 parent_dir_name
, parent_dir_name
[:-1], 1
178 stream
.write(self
.read().encode("utf-8"))
181 self
.fs
.upload_from_stream_with_id(
182 self
._id
, self
.filename
, stream
, metadata
={"type": self
.file_type
}
185 self
.fs
.upload_from_stream(
186 self
.filename
, stream
, metadata
={"type": self
.file_type
}
189 super(GridStringStream
, self
).close()
194 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
198 class FsMongo(FsBase
):
199 def __init__(self
, logger_name
="fs", lock
=False):
200 super().__init
__(logger_name
, lock
)
205 def __update_local_fs(self
, from_path
=None):
206 dir_cursor
= self
.fs
.find({"metadata.type": "dir"}, no_cursor_timeout
=True)
210 for directory
in dir_cursor
:
211 if from_path
and not directory
.filename
.startswith(from_path
):
213 self
.logger
.debug("Making dir {}".format(self
.path
+ directory
.filename
))
214 os
.makedirs(self
.path
+ directory
.filename
, exist_ok
=True)
215 valid_paths
.append(self
.path
+ directory
.filename
)
217 file_cursor
= self
.fs
.find(
218 {"metadata.type": {"$in": ["file", "sym"]}}, no_cursor_timeout
=True
221 for writing_file
in file_cursor
:
222 if from_path
and not writing_file
.filename
.startswith(from_path
):
224 file_path
= self
.path
+ writing_file
.filename
226 if writing_file
.metadata
["type"] == "sym":
228 self
.fs
.download_to_stream(writing_file
._id
, b
)
230 link
= b
.read().decode("utf-8")
233 self
.logger
.debug("Sync removing {}".format(file_path
))
236 if e
.errno
!= errno
.ENOENT
:
237 # This is probably permission denied or worse
239 os
.symlink(link
, file_path
)
241 folder
= os
.path
.dirname(file_path
)
242 if folder
not in valid_paths
:
243 self
.logger
.debug("Sync local directory {}".format(file_path
))
244 os
.makedirs(folder
, exist_ok
=True)
245 with
open(file_path
, "wb+") as file_stream
:
246 self
.logger
.debug("Sync download {}".format(file_path
))
247 self
.fs
.download_to_stream(writing_file
._id
, file_stream
)
248 if "permissions" in writing_file
.metadata
:
249 os
.chmod(file_path
, writing_file
.metadata
["permissions"])
251 def get_params(self
):
252 return {"fs": "mongo", "path": self
.path
}
254 def fs_connect(self
, config
):
256 if "logger_name" in config
:
257 self
.logger
= logging
.getLogger(config
["logger_name"])
259 self
.path
= config
["path"]
261 raise FsException('Missing parameter "path"')
262 if not self
.path
.endswith("/"):
264 if not os
.path
.exists(self
.path
):
266 "Invalid configuration param at '[storage]': path '{}' does not exist".format(
270 elif not os
.access(self
.path
, os
.W_OK
):
272 "Invalid configuration param at '[storage]': path '{}' is not writable".format(
276 if all(key
in config
.keys() for key
in ["uri", "collection"]):
277 self
.client
= MongoClient(config
["uri"])
278 self
.fs
= GridFSBucket(self
.client
[config
["collection"]])
279 elif all(key
in config
.keys() for key
in ["host", "port", "collection"]):
280 self
.client
= MongoClient(config
["host"], config
["port"])
281 self
.fs
= GridFSBucket(self
.client
[config
["collection"]])
283 if "collection" not in config
.keys():
284 raise FsException('Missing parameter "collection"')
286 raise FsException('Missing parameters: "uri" or "host" + "port"')
289 except Exception as e
: # TODO refine
290 raise FsException(str(e
))
292 def fs_disconnect(self
):
295 def mkdir(self
, folder
):
297 Creates a folder or parent object location
299 :return: None or raises an exception
301 folder
= folder
.rstrip("/")
303 self
.fs
.upload_from_stream(folder
, BytesIO(), metadata
={"type": "dir"})
304 except errors
.FileExists
: # make it idempotent
306 except Exception as e
:
307 raise FsException(str(e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
309 def dir_rename(self
, src
, dst
):
311 Rename one directory name. If dst exist, it replaces (deletes) existing directory
312 :param src: source directory
313 :param dst: destination directory
314 :return: None or raises and exception
316 dst
= dst
.rstrip("/")
317 src
= src
.rstrip("/")
320 dst_cursor
= self
.fs
.find(
321 {"filename": {"$regex": "^{}(/|$)".format(dst
)}}, no_cursor_timeout
=True
324 for dst_file
in dst_cursor
:
325 self
.fs
.delete(dst_file
._id
)
327 src_cursor
= self
.fs
.find(
328 {"filename": {"$regex": "^{}(/|$)".format(src
)}}, no_cursor_timeout
=True
331 for src_file
in src_cursor
:
332 self
.fs
.rename(src_file
._id
, src_file
.filename
.replace(src
, dst
, 1))
333 except Exception as e
:
334 raise FsException(str(e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
336 def file_exists(self
, storage
, mode
=None):
338 Indicates if "storage" file exist
339 :param storage: can be a str or a str list
340 :param mode: can be 'file' exist as a regular file; 'dir' exists as a directory or; 'None' just exists
343 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
346 cursor
= self
.fs
.find({"filename": f
})
348 for requested_file
in cursor
:
349 exception_file
= next(cursor
, None)
353 "Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
356 self
.logger
.debug("Entry {} metadata {}".format(f
, requested_file
.metadata
))
358 # if no special mode is required just check it does exists
362 if requested_file
.metadata
["type"] == mode
:
365 if requested_file
.metadata
["type"] == "sym" and mode
== "file":
370 def file_size(self
, storage
):
373 :param storage: can be a str or a str list
376 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
379 cursor
= self
.fs
.find({"filename": f
})
381 for requested_file
in cursor
:
382 exception_file
= next(cursor
, None)
386 "Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
389 return requested_file
.length
391 def file_extract(self
, compressed_object
, path
):
394 :param compressed_object: object of type tar or zip
395 :param path: can be a str or a str list, or a tar object where to extract the tar_object
398 f
= path
if isinstance(path
, str) else "/".join(path
)
401 if type(compressed_object
) is tarfile
.TarFile
:
402 for member
in compressed_object
.getmembers():
404 stream
= compressed_object
.extractfile(member
)
406 stream
= BytesIO(member
.linkname
.encode("utf-8"))
417 metadata
= {"type": file_type
, "permissions": member
.mode
}
418 member
.name
= member
.name
.rstrip("/")
420 self
.logger
.debug("Uploading {}/{}".format(f
, member
.name
))
421 self
.fs
.upload_from_stream(
422 f
+ "/" + member
.name
, stream
, metadata
=metadata
426 elif type(compressed_object
) is zipfile
.ZipFile
:
427 for member
in compressed_object
.infolist():
431 stream
= compressed_object
.read(member
)
438 metadata
= {"type": file_type
}
439 member
.filename
= member
.filename
.rstrip("/")
441 self
.logger
.debug("Uploading {}/{}".format(f
, member
.filename
))
442 self
.fs
.upload_from_stream(
443 f
+ "/" + member
.filename
, stream
, metadata
=metadata
449 def file_open(self
, storage
, mode
):
452 :param storage: can be a str or list of str
453 :param mode: file mode
457 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
461 return GridByteStream(f
, self
.fs
, mode
)
463 return GridStringStream(f
, self
.fs
, mode
)
464 except errors
.NoFile
:
466 "File {} does not exist".format(f
), http_code
=HTTPStatus
.NOT_FOUND
470 "File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
473 def dir_ls(self
, storage
):
475 return folder content
476 :param storage: can be a str or list of str
477 :return: folder content
480 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
484 dir_cursor
= self
.fs
.find({"filename": f
})
485 for requested_dir
in dir_cursor
:
486 exception_dir
= next(dir_cursor
, None)
490 "Multiple directories found",
491 http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
,
494 if requested_dir
.metadata
["type"] != "dir":
496 "File {} does not exist".format(f
),
497 http_code
=HTTPStatus
.NOT_FOUND
,
503 files_cursor
= self
.fs
.find(
504 {"filename": {"$regex": "^{}/([^/])*".format(f
)}}
506 for children_file
in files_cursor
:
507 files
+= [children_file
.filename
.replace(f
+ "/", "", 1)]
512 "File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
515 def file_delete(self
, storage
, ignore_non_exist
=False):
517 Delete storage content recursively
518 :param storage: can be a str or list of str
519 :param ignore_non_exist: not raise exception if storage does not exist
523 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
526 file_cursor
= self
.fs
.find({"filename": f
})
528 for requested_file
in file_cursor
:
530 exception_file
= next(file_cursor
, None)
534 "Cannot delete duplicate file: {} and {}".format(
535 requested_file
.filename
, exception_file
.filename
539 "Multiple files found",
540 http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
,
543 if requested_file
.metadata
["type"] == "dir":
544 dir_cursor
= self
.fs
.find(
545 {"filename": {"$regex": "^{}/".format(f
)}}
548 for tmp
in dir_cursor
:
549 self
.logger
.debug("Deleting {}".format(tmp
.filename
))
550 self
.fs
.delete(tmp
._id
)
552 self
.logger
.debug("Deleting {}".format(requested_file
.filename
))
553 self
.fs
.delete(requested_file
._id
)
554 if not found
and not ignore_non_exist
:
556 "File {} does not exist".format(storage
),
557 http_code
=HTTPStatus
.NOT_FOUND
,
561 "File {} cannot be deleted: {}".format(f
, e
),
562 http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
,
565 def sync(self
, from_path
=None):
567 Sync from FSMongo to local storage
568 :param from_path: if supplied, only copy content from this path, not all
572 if os
.path
.isabs(from_path
):
573 from_path
= os
.path
.relpath(from_path
, self
.path
)
574 self
.__update
_local
_fs
(from_path
=from_path
)
576 def _update_mongo_fs(self
, from_path
):
578 os_path
= self
.path
+ from_path
580 # Obtain list of files and dirs in filesystem
582 for root
, dirs
, files
in os
.walk(os_path
):
584 member
= {"filename": os
.path
.join(root
, folder
), "type": "dir"}
585 if os
.path
.islink(member
["filename"]):
586 member
["type"] = "sym"
587 members
.append(member
)
589 filename
= os
.path
.join(root
, file)
590 if os
.path
.islink(filename
):
594 member
= {"filename": os
.path
.join(root
, file), "type": file_type
}
595 members
.append(member
)
597 # Obtain files in mongo dict
598 remote_files
= self
._get
_mongo
_files
(from_path
)
600 # Upload members if they do not exists or have been modified
601 # We will do this for performance (avoid updating unmodified files) and to avoid
602 # updating a file with an older one in case there are two sources for synchronization
603 # in high availability scenarios
604 for member
in members
:
606 mask
= int(oct(os
.stat(member
["filename"]).st_mode
)[-3:], 8)
608 # convert to relative path
609 rel_filename
= os
.path
.relpath(member
["filename"], self
.path
)
610 last_modified_date
= datetime
.datetime
.fromtimestamp(
611 os
.path
.getmtime(member
["filename"])
614 remote_file
= remote_files
.get(rel_filename
)
616 remote_file
[0].uploadDate
if remote_file
else datetime
.datetime
.min
618 # remove processed files from dict
619 remote_files
.pop(rel_filename
, None)
621 if last_modified_date
>= upload_date
:
626 file_type
= member
["type"]
627 if file_type
== "dir":
629 elif file_type
== "sym":
631 os
.readlink(member
["filename"]).encode("utf-8")
634 fh
= open(member
["filename"], "rb")
635 stream
= BytesIO(fh
.read())
637 metadata
= {"type": file_type
, "permissions": mask
}
639 self
.logger
.debug("Sync upload {}".format(rel_filename
))
640 self
.fs
.upload_from_stream(rel_filename
, stream
, metadata
=metadata
)
644 for file in remote_file
:
645 self
.logger
.debug("Sync deleting {}".format(file.filename
))
646 self
.fs
.delete(file._id
)
653 # delete files that are not any more in local fs
654 for remote_file
in remote_files
.values():
655 for file in remote_file
:
656 self
.fs
.delete(file._id
)
658 def _get_mongo_files(self
, from_path
=None):
661 file_cursor
= self
.fs
.find(no_cursor_timeout
=True, sort
=[("uploadDate", -1)])
662 for file in file_cursor
:
663 if from_path
and not file.filename
.startswith(from_path
):
665 if file.filename
in file_dict
:
666 file_dict
[file.filename
].append(file)
668 file_dict
[file.filename
] = [file]
671 def reverse_sync(self
, from_path
: str):
673 Sync from local storage to FSMongo
674 :param from_path: base directory to upload content to mongo fs
677 if os
.path
.isabs(from_path
):
678 from_path
= os
.path
.relpath(from_path
, self
.path
)
679 self
._update
_mongo
_fs
(from_path
=from_path
)