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
26 from gridfs
import GridFSBucket
, errors
27 from osm_common
.fsbase
import FsBase
, FsException
28 from pymongo
import MongoClient
31 __author__
= "Eduardo Sousa <eduardo.sousa@canonical.com>"
34 class GridByteStream(BytesIO
):
35 def __init__(self
, filename
, fs
, mode
):
36 BytesIO
.__init
__(self
)
38 self
.filename
= filename
41 self
.file_type
= "file" # Set "file" as default file_type
45 def __initialize__(self
):
48 cursor
= self
.fs
.find({"filename": self
.filename
})
50 for requested_file
in cursor
:
51 exception_file
= next(cursor
, None)
55 "Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
58 if requested_file
.metadata
["type"] in ("file", "sym"):
59 grid_file
= requested_file
60 self
.file_type
= requested_file
.metadata
["type"]
63 "Type isn't file", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
67 self
._id
= grid_file
._id
68 self
.fs
.download_to_stream(self
._id
, self
)
75 super(GridByteStream
, self
).close()
79 self
.fs
.delete(self
._id
)
81 cursor
= self
.fs
.find(
82 {"filename": self
.filename
.split("/")[0], "metadata": {"type": "dir"}}
85 parent_dir
= next(cursor
, None)
88 parent_dir_name
= self
.filename
.split("/")[0]
89 self
.filename
= self
.filename
.replace(
90 parent_dir_name
, parent_dir_name
[:-1], 1
95 self
.fs
.upload_from_stream_with_id(
96 self
._id
, self
.filename
, self
, metadata
={"type": self
.file_type
}
99 self
.fs
.upload_from_stream(
100 self
.filename
, self
, metadata
={"type": self
.file_type
}
102 super(GridByteStream
, self
).close()
107 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
111 class GridStringStream(StringIO
):
112 def __init__(self
, filename
, fs
, mode
):
113 StringIO
.__init
__(self
)
115 self
.filename
= filename
118 self
.file_type
= "file" # Set "file" as default file_type
120 self
.__initialize
__()
122 def __initialize__(self
):
125 cursor
= self
.fs
.find({"filename": self
.filename
})
127 for requested_file
in cursor
:
128 exception_file
= next(cursor
, None)
132 "Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
135 if requested_file
.metadata
["type"] in ("file", "dir"):
136 grid_file
= requested_file
137 self
.file_type
= requested_file
.metadata
["type"]
140 "File type isn't file", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
145 self
._id
= grid_file
._id
146 self
.fs
.download_to_stream(self
._id
, stream
)
148 self
.write(stream
.read().decode("utf-8"))
156 super(GridStringStream
, self
).close()
160 self
.fs
.delete(self
._id
)
162 cursor
= self
.fs
.find(
163 {"filename": self
.filename
.split("/")[0], "metadata": {"type": "dir"}}
166 parent_dir
= next(cursor
, None)
169 parent_dir_name
= self
.filename
.split("/")[0]
170 self
.filename
= self
.filename
.replace(
171 parent_dir_name
, parent_dir_name
[:-1], 1
176 stream
.write(self
.read().encode("utf-8"))
179 self
.fs
.upload_from_stream_with_id(
180 self
._id
, self
.filename
, stream
, metadata
={"type": self
.file_type
}
183 self
.fs
.upload_from_stream(
184 self
.filename
, stream
, metadata
={"type": self
.file_type
}
187 super(GridStringStream
, self
).close()
192 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
196 class FsMongo(FsBase
):
197 def __init__(self
, logger_name
="fs", lock
=False):
198 super().__init
__(logger_name
, lock
)
203 def __update_local_fs(self
, from_path
=None):
204 dir_cursor
= self
.fs
.find({"metadata.type": "dir"}, no_cursor_timeout
=True)
206 for directory
in dir_cursor
:
207 if from_path
and not directory
.filename
.startswith(from_path
):
209 os
.makedirs(self
.path
+ directory
.filename
, exist_ok
=True)
211 file_cursor
= self
.fs
.find(
212 {"metadata.type": {"$in": ["file", "sym"]}}, no_cursor_timeout
=True
215 for writing_file
in file_cursor
:
216 if from_path
and not writing_file
.filename
.startswith(from_path
):
218 file_path
= self
.path
+ writing_file
.filename
220 if writing_file
.metadata
["type"] == "sym":
222 self
.fs
.download_to_stream(writing_file
._id
, b
)
224 link
= b
.read().decode("utf-8")
229 if e
.errno
!= errno
.ENOENT
:
230 # This is probably permission denied or worse
232 os
.symlink(link
, file_path
)
234 with
open(file_path
, "wb+") as file_stream
:
235 self
.fs
.download_to_stream(writing_file
._id
, file_stream
)
236 if "permissions" in writing_file
.metadata
:
237 os
.chmod(file_path
, writing_file
.metadata
["permissions"])
239 def get_params(self
):
240 return {"fs": "mongo", "path": self
.path
}
242 def fs_connect(self
, config
):
244 if "logger_name" in config
:
245 self
.logger
= logging
.getLogger(config
["logger_name"])
247 self
.path
= config
["path"]
249 raise FsException('Missing parameter "path"')
250 if not self
.path
.endswith("/"):
252 if not os
.path
.exists(self
.path
):
254 "Invalid configuration param at '[storage]': path '{}' does not exist".format(
258 elif not os
.access(self
.path
, os
.W_OK
):
260 "Invalid configuration param at '[storage]': path '{}' is not writable".format(
264 if all(key
in config
.keys() for key
in ["uri", "collection"]):
265 self
.client
= MongoClient(config
["uri"])
266 self
.fs
= GridFSBucket(self
.client
[config
["collection"]])
267 elif all(key
in config
.keys() for key
in ["host", "port", "collection"]):
268 self
.client
= MongoClient(config
["host"], config
["port"])
269 self
.fs
= GridFSBucket(self
.client
[config
["collection"]])
271 if "collection" not in config
.keys():
272 raise FsException('Missing parameter "collection"')
274 raise FsException('Missing parameters: "uri" or "host" + "port"')
277 except Exception as e
: # TODO refine
278 raise FsException(str(e
))
280 def fs_disconnect(self
):
283 def mkdir(self
, folder
):
285 Creates a folder or parent object location
287 :return: None or raises an exception
290 self
.fs
.upload_from_stream(folder
, BytesIO(), metadata
={"type": "dir"})
291 except errors
.FileExists
: # make it idempotent
293 except Exception as e
:
294 raise FsException(str(e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
296 def dir_rename(self
, src
, dst
):
298 Rename one directory name. If dst exist, it replaces (deletes) existing directory
299 :param src: source directory
300 :param dst: destination directory
301 :return: None or raises and exception
304 dst_cursor
= self
.fs
.find(
305 {"filename": {"$regex": "^{}(/|$)".format(dst
)}}, no_cursor_timeout
=True
308 for dst_file
in dst_cursor
:
309 self
.fs
.delete(dst_file
._id
)
311 src_cursor
= self
.fs
.find(
312 {"filename": {"$regex": "^{}(/|$)".format(src
)}}, no_cursor_timeout
=True
315 for src_file
in src_cursor
:
316 self
.fs
.rename(src_file
._id
, src_file
.filename
.replace(src
, dst
, 1))
317 except Exception as e
:
318 raise FsException(str(e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
320 def file_exists(self
, storage
, mode
=None):
322 Indicates if "storage" file exist
323 :param storage: can be a str or a str list
324 :param mode: can be 'file' exist as a regular file; 'dir' exists as a directory or; 'None' just exists
327 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
329 cursor
= self
.fs
.find({"filename": f
})
331 for requested_file
in cursor
:
332 exception_file
= next(cursor
, None)
336 "Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
339 # if no special mode is required just check it does exists
343 if requested_file
.metadata
["type"] == mode
:
346 if requested_file
.metadata
["type"] == "sym" and mode
== "file":
351 def file_size(self
, storage
):
354 :param storage: can be a str or a str list
357 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
359 cursor
= self
.fs
.find({"filename": f
})
361 for requested_file
in cursor
:
362 exception_file
= next(cursor
, None)
366 "Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
369 return requested_file
.length
371 def file_extract(self
, tar_object
, path
):
374 :param tar_object: object of type tar
375 :param path: can be a str or a str list, or a tar object where to extract the tar_object
378 f
= path
if isinstance(path
, str) else "/".join(path
)
380 for member
in tar_object
.getmembers():
382 stream
= tar_object
.extractfile(member
)
384 stream
= BytesIO(member
.linkname
.encode("utf-8"))
395 metadata
= {"type": file_type
, "permissions": member
.mode
}
397 self
.fs
.upload_from_stream(f
+ "/" + member
.name
, stream
, metadata
=metadata
)
401 def file_open(self
, storage
, mode
):
404 :param storage: can be a str or list of str
405 :param mode: file mode
409 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
412 return GridByteStream(f
, self
.fs
, mode
)
414 return GridStringStream(f
, self
.fs
, mode
)
415 except errors
.NoFile
:
417 "File {} does not exist".format(f
), http_code
=HTTPStatus
.NOT_FOUND
421 "File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
424 def dir_ls(self
, storage
):
426 return folder content
427 :param storage: can be a str or list of str
428 :return: folder content
431 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
434 dir_cursor
= self
.fs
.find({"filename": f
})
435 for requested_dir
in dir_cursor
:
436 exception_dir
= next(dir_cursor
, None)
440 "Multiple directories found",
441 http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
,
444 if requested_dir
.metadata
["type"] != "dir":
446 "File {} does not exist".format(f
),
447 http_code
=HTTPStatus
.NOT_FOUND
,
450 files_cursor
= self
.fs
.find(
451 {"filename": {"$regex": "^{}/([^/])*".format(f
)}}
453 for children_file
in files_cursor
:
454 files
+= [children_file
.filename
.replace(f
+ "/", "", 1)]
459 "File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
462 def file_delete(self
, storage
, ignore_non_exist
=False):
464 Delete storage content recursively
465 :param storage: can be a str or list of str
466 :param ignore_non_exist: not raise exception if storage does not exist
470 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
472 file_cursor
= self
.fs
.find({"filename": f
})
474 for requested_file
in file_cursor
:
476 exception_file
= next(file_cursor
, None)
480 "Multiple files found",
481 http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
,
484 if requested_file
.metadata
["type"] == "dir":
485 dir_cursor
= self
.fs
.find({"filename": {"$regex": "^{}".format(f
)}})
487 for tmp
in dir_cursor
:
488 self
.fs
.delete(tmp
._id
)
490 self
.fs
.delete(requested_file
._id
)
491 if not found
and not ignore_non_exist
:
493 "File {} does not exist".format(storage
),
494 http_code
=HTTPStatus
.NOT_FOUND
,
498 "File {} cannot be deleted: {}".format(f
, e
),
499 http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
,
502 def sync(self
, from_path
=None):
504 Sync from FSMongo to local storage
505 :param from_path: if supplied, only copy content from this path, not all
509 if os
.path
.isabs(from_path
):
510 from_path
= os
.path
.relpath(from_path
, self
.path
)
511 self
.__update
_local
_fs
(from_path
=from_path
)
513 def _update_mongo_fs(self
, from_path
):
515 os_path
= self
.path
+ from_path
517 # Obtain list of files and dirs in filesystem
519 for root
, dirs
, files
in os
.walk(os_path
):
521 member
= {"filename": os
.path
.join(root
, folder
), "type": "dir"}
522 members
.append(member
)
524 filename
= os
.path
.join(root
, file)
525 if os
.path
.islink(filename
):
529 member
= {"filename": os
.path
.join(root
, file), "type": file_type
}
530 members
.append(member
)
532 # Obtain files in mongo dict
533 remote_files
= self
._get
_mongo
_files
(from_path
)
535 # Upload members if they do not exists or have been modified
536 # We will do this for performance (avoid updating unmodified files) and to avoid
537 # updating a file with an older one in case there are two sources for synchronization
538 # in high availability scenarios
539 for member
in members
:
541 mask
= int(oct(os
.stat(member
["filename"]).st_mode
)[-3:], 8)
543 # convert to relative path
544 rel_filename
= os
.path
.relpath(member
["filename"], self
.path
)
545 last_modified_date
= datetime
.datetime
.fromtimestamp(
546 os
.path
.getmtime(member
["filename"])
549 remote_file
= remote_files
.get(rel_filename
)
551 remote_file
[0].uploadDate
if remote_file
else datetime
.datetime
.min
553 # remove processed files from dict
554 remote_files
.pop(rel_filename
, None)
556 if last_modified_date
>= upload_date
:
561 file_type
= member
["type"]
562 if file_type
== "dir":
564 elif file_type
== "sym":
566 os
.readlink(member
["filename"]).encode("utf-8")
569 fh
= open(member
["filename"], "rb")
570 stream
= BytesIO(fh
.read())
572 metadata
= {"type": file_type
, "permissions": mask
}
574 self
.fs
.upload_from_stream(rel_filename
, stream
, metadata
=metadata
)
578 for file in remote_file
:
579 self
.fs
.delete(file._id
)
586 # delete files that are not any more in local fs
587 for remote_file
in remote_files
.values():
588 for file in remote_file
:
589 self
.fs
.delete(file._id
)
591 def _get_mongo_files(self
, from_path
=None):
594 file_cursor
= self
.fs
.find(no_cursor_timeout
=True, sort
=[("uploadDate", -1)])
595 for file in file_cursor
:
596 if from_path
and not file.filename
.startswith(from_path
):
598 if file.filename
in file_dict
:
599 file_dict
[file.filename
].append(file)
601 file_dict
[file.filename
] = [file]
604 def reverse_sync(self
, from_path
: str):
606 Sync from local storage to FSMongo
607 :param from_path: base directory to upload content to mongo fs
610 if os
.path
.isabs(from_path
):
611 from_path
= os
.path
.relpath(from_path
, self
.path
)
612 self
._update
_mongo
_fs
(from_path
=from_path
)