b04057e4d6993586ea3edf2f2dc7cce73ff2bd66
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 os
.makedirs(self
.path
+ directory
.filename
, exist_ok
=True)
214 valid_paths
.append(self
.path
+ directory
.filename
)
216 file_cursor
= self
.fs
.find(
217 {"metadata.type": {"$in": ["file", "sym"]}}, no_cursor_timeout
=True
220 for writing_file
in file_cursor
:
221 if from_path
and not writing_file
.filename
.startswith(from_path
):
223 file_path
= self
.path
+ writing_file
.filename
225 if writing_file
.metadata
["type"] == "sym":
227 self
.fs
.download_to_stream(writing_file
._id
, b
)
229 link
= b
.read().decode("utf-8")
234 if e
.errno
!= errno
.ENOENT
:
235 # This is probably permission denied or worse
237 os
.symlink(link
, file_path
)
239 folder
= os
.path
.dirname(file_path
)
240 if folder
not in valid_paths
:
241 os
.makedirs(folder
, exist_ok
=True)
242 with
open(file_path
, "wb+") as file_stream
:
243 self
.fs
.download_to_stream(writing_file
._id
, file_stream
)
244 if "permissions" in writing_file
.metadata
:
245 os
.chmod(file_path
, writing_file
.metadata
["permissions"])
247 def get_params(self
):
248 return {"fs": "mongo", "path": self
.path
}
250 def fs_connect(self
, config
):
252 if "logger_name" in config
:
253 self
.logger
= logging
.getLogger(config
["logger_name"])
255 self
.path
= config
["path"]
257 raise FsException('Missing parameter "path"')
258 if not self
.path
.endswith("/"):
260 if not os
.path
.exists(self
.path
):
262 "Invalid configuration param at '[storage]': path '{}' does not exist".format(
266 elif not os
.access(self
.path
, os
.W_OK
):
268 "Invalid configuration param at '[storage]': path '{}' is not writable".format(
272 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"]])
279 if "collection" not in config
.keys():
280 raise FsException('Missing parameter "collection"')
282 raise FsException('Missing parameters: "uri" or "host" + "port"')
285 except Exception as e
: # TODO refine
286 raise FsException(str(e
))
288 def fs_disconnect(self
):
291 def mkdir(self
, folder
):
293 Creates a folder or parent object location
295 :return: None or raises an exception
298 self
.fs
.upload_from_stream(folder
, BytesIO(), metadata
={"type": "dir"})
299 except errors
.FileExists
: # make it idempotent
301 except Exception as e
:
302 raise FsException(str(e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
304 def dir_rename(self
, src
, dst
):
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
312 dst_cursor
= self
.fs
.find(
313 {"filename": {"$regex": "^{}(/|$)".format(dst
)}}, no_cursor_timeout
=True
316 for dst_file
in dst_cursor
:
317 self
.fs
.delete(dst_file
._id
)
319 src_cursor
= self
.fs
.find(
320 {"filename": {"$regex": "^{}(/|$)".format(src
)}}, no_cursor_timeout
=True
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
)
328 def file_exists(self
, storage
, mode
=None):
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
335 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
337 cursor
= self
.fs
.find({"filename": f
})
339 for requested_file
in cursor
:
340 exception_file
= next(cursor
, None)
344 "Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
347 print(requested_file
.metadata
)
349 # if no special mode is required just check it does exists
353 if requested_file
.metadata
["type"] == mode
:
356 if requested_file
.metadata
["type"] == "sym" and mode
== "file":
361 def file_size(self
, storage
):
364 :param storage: can be a str or a str list
367 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
369 cursor
= self
.fs
.find({"filename": f
})
371 for requested_file
in cursor
:
372 exception_file
= next(cursor
, None)
376 "Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
379 return requested_file
.length
381 def file_extract(self
, compressed_object
, path
):
384 :param compressed_object: object of type tar or zip
385 :param path: can be a str or a str list, or a tar object where to extract the tar_object
388 f
= path
if isinstance(path
, str) else "/".join(path
)
390 if type(compressed_object
) is tarfile
.TarFile
:
391 for member
in compressed_object
.getmembers():
393 stream
= compressed_object
.extractfile(member
)
395 stream
= BytesIO(member
.linkname
.encode("utf-8"))
406 metadata
= {"type": file_type
, "permissions": member
.mode
}
408 self
.fs
.upload_from_stream(
409 f
+ "/" + member
.name
, stream
, metadata
=metadata
413 elif type(compressed_object
) is zipfile
.ZipFile
:
414 for member
in compressed_object
.infolist():
418 stream
= compressed_object
.read(member
)
425 metadata
= {"type": file_type
}
427 print("Now uploading...")
428 print(f
+ "/" + member
.filename
)
429 self
.fs
.upload_from_stream(
430 f
+ "/" + member
.filename
, stream
, metadata
=metadata
436 def file_open(self
, storage
, mode
):
439 :param storage: can be a str or list of str
440 :param mode: file mode
444 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
447 return GridByteStream(f
, self
.fs
, mode
)
449 return GridStringStream(f
, self
.fs
, mode
)
450 except errors
.NoFile
:
452 "File {} does not exist".format(f
), http_code
=HTTPStatus
.NOT_FOUND
456 "File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
459 def dir_ls(self
, storage
):
461 return folder content
462 :param storage: can be a str or list of str
463 :return: folder content
466 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
469 dir_cursor
= self
.fs
.find({"filename": f
})
470 for requested_dir
in dir_cursor
:
471 exception_dir
= next(dir_cursor
, None)
475 "Multiple directories found",
476 http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
,
479 if requested_dir
.metadata
["type"] != "dir":
481 "File {} does not exist".format(f
),
482 http_code
=HTTPStatus
.NOT_FOUND
,
488 files_cursor
= self
.fs
.find(
489 {"filename": {"$regex": "^{}/([^/])*".format(f
)}}
491 for children_file
in files_cursor
:
492 files
+= [children_file
.filename
.replace(f
+ "/", "", 1)]
497 "File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
500 def file_delete(self
, storage
, ignore_non_exist
=False):
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
508 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
510 file_cursor
= self
.fs
.find({"filename": f
})
512 for requested_file
in file_cursor
:
514 exception_file
= next(file_cursor
, None)
518 "Multiple files found",
519 http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
,
522 if requested_file
.metadata
["type"] == "dir":
523 dir_cursor
= self
.fs
.find({"filename": {"$regex": "^{}".format(f
)}})
525 for tmp
in dir_cursor
:
526 self
.fs
.delete(tmp
._id
)
528 self
.fs
.delete(requested_file
._id
)
529 if not found
and not ignore_non_exist
:
531 "File {} does not exist".format(storage
),
532 http_code
=HTTPStatus
.NOT_FOUND
,
536 "File {} cannot be deleted: {}".format(f
, e
),
537 http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
,
540 def sync(self
, from_path
=None):
542 Sync from FSMongo to local storage
543 :param from_path: if supplied, only copy content from this path, not all
547 if os
.path
.isabs(from_path
):
548 from_path
= os
.path
.relpath(from_path
, self
.path
)
549 self
.__update
_local
_fs
(from_path
=from_path
)
551 def _update_mongo_fs(self
, from_path
):
553 os_path
= self
.path
+ from_path
555 # Obtain list of files and dirs in filesystem
557 for root
, dirs
, files
in os
.walk(os_path
):
559 member
= {"filename": os
.path
.join(root
, folder
), "type": "dir"}
560 members
.append(member
)
562 filename
= os
.path
.join(root
, file)
563 if os
.path
.islink(filename
):
567 member
= {"filename": os
.path
.join(root
, file), "type": file_type
}
568 members
.append(member
)
570 # Obtain files in mongo dict
571 remote_files
= self
._get
_mongo
_files
(from_path
)
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
:
579 mask
= int(oct(os
.stat(member
["filename"]).st_mode
)[-3:], 8)
581 # convert to relative path
582 rel_filename
= os
.path
.relpath(member
["filename"], self
.path
)
583 last_modified_date
= datetime
.datetime
.fromtimestamp(
584 os
.path
.getmtime(member
["filename"])
587 remote_file
= remote_files
.get(rel_filename
)
589 remote_file
[0].uploadDate
if remote_file
else datetime
.datetime
.min
591 # remove processed files from dict
592 remote_files
.pop(rel_filename
, None)
594 if last_modified_date
>= upload_date
:
599 file_type
= member
["type"]
600 if file_type
== "dir":
602 elif file_type
== "sym":
604 os
.readlink(member
["filename"]).encode("utf-8")
607 fh
= open(member
["filename"], "rb")
608 stream
= BytesIO(fh
.read())
610 metadata
= {"type": file_type
, "permissions": mask
}
612 self
.fs
.upload_from_stream(rel_filename
, stream
, metadata
=metadata
)
616 for file in remote_file
:
617 self
.fs
.delete(file._id
)
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
)
629 def _get_mongo_files(self
, from_path
=None):
632 file_cursor
= self
.fs
.find(no_cursor_timeout
=True, sort
=[("uploadDate", -1)])
633 for file in file_cursor
:
634 if from_path
and not file.filename
.startswith(from_path
):
636 if file.filename
in file_dict
:
637 file_dict
[file.filename
].append(file)
639 file_dict
[file.filename
] = [file]
642 def reverse_sync(self
, from_path
: str):
644 Sync from local storage to FSMongo
645 :param from_path: base directory to upload content to mongo fs
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
)