07d4821e942e0df0eb85bbbfb01e4a98b47e5043
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
19 from io
import BytesIO
, StringIO
20 from pymongo
import MongoClient
21 from gridfs
import GridFSBucket
, errors
23 from http
import HTTPStatus
25 from osm_common
.fsbase
import FsBase
, FsException
27 __author__
= "Eduardo Sousa <eduardo.sousa@canonical.com>"
30 class GridByteStream(BytesIO
):
31 def __init__(self
, filename
, fs
, mode
):
32 BytesIO
.__init
__(self
)
34 self
.filename
= filename
37 self
.file_type
= "file" # Set "file" as default file_type
41 def __initialize__(self
):
44 cursor
= self
.fs
.find({"filename": self
.filename
})
46 for requested_file
in cursor
:
47 exception_file
= next(cursor
, None)
50 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
52 if requested_file
.metadata
["type"] in ("file", "sym"):
53 grid_file
= requested_file
54 self
.file_type
= requested_file
.metadata
["type"]
56 raise FsException("Type isn't file", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
59 self
._id
= grid_file
._id
60 self
.fs
.download_to_stream(self
._id
, self
)
67 super(GridByteStream
, self
).close()
71 self
.fs
.delete(self
._id
)
73 cursor
= self
.fs
.find({
74 "filename": self
.filename
.split("/")[0],
75 "metadata": {"type": "dir"}})
77 parent_dir
= next(cursor
, None)
80 parent_dir_name
= self
.filename
.split("/")[0]
81 self
.filename
= self
.filename
.replace(parent_dir_name
, parent_dir_name
[:-1], 1)
85 self
.fs
.upload_from_stream_with_id(
89 metadata
={"type": self
.file_type
}
92 self
.fs
.upload_from_stream(
95 metadata
={"type": self
.file_type
}
97 super(GridByteStream
, self
).close()
102 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
106 class GridStringStream(StringIO
):
107 def __init__(self
, filename
, fs
, mode
):
108 StringIO
.__init
__(self
)
110 self
.filename
= filename
113 self
.file_type
= "file" # Set "file" as default file_type
115 self
.__initialize
__()
117 def __initialize__(self
):
120 cursor
= self
.fs
.find({"filename": self
.filename
})
122 for requested_file
in cursor
:
123 exception_file
= next(cursor
, None)
126 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
128 if requested_file
.metadata
["type"] in ("file", "dir"):
129 grid_file
= requested_file
130 self
.file_type
= requested_file
.metadata
["type"]
132 raise FsException("File type isn't file", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
136 self
._id
= grid_file
._id
137 self
.fs
.download_to_stream(self
._id
, stream
)
139 self
.write(stream
.read().decode("utf-8"))
147 super(GridStringStream
, self
).close()
151 self
.fs
.delete(self
._id
)
153 cursor
= self
.fs
.find({
154 "filename": self
.filename
.split("/")[0],
155 "metadata": {"type": "dir"}})
157 parent_dir
= next(cursor
, None)
160 parent_dir_name
= self
.filename
.split("/")[0]
161 self
.filename
= self
.filename
.replace(parent_dir_name
, parent_dir_name
[:-1], 1)
165 stream
.write(self
.read().encode("utf-8"))
168 self
.fs
.upload_from_stream_with_id(
172 metadata
={"type": self
.file_type
}
175 self
.fs
.upload_from_stream(
178 metadata
={"type": self
.file_type
}
181 super(GridStringStream
, self
).close()
186 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
190 class FsMongo(FsBase
):
192 def __init__(self
, logger_name
='fs', lock
=False):
193 super().__init
__(logger_name
, lock
)
198 def __update_local_fs(self
, from_path
=None):
199 dir_cursor
= self
.fs
.find({"metadata.type": "dir"}, no_cursor_timeout
=True)
201 for directory
in dir_cursor
:
202 if from_path
and not directory
.filename
.startswith(from_path
):
204 os
.makedirs(self
.path
+ directory
.filename
, exist_ok
=True)
206 file_cursor
= self
.fs
.find({"metadata.type": {"$in": ["file", "sym"]}}, no_cursor_timeout
=True)
208 for writing_file
in file_cursor
:
209 if from_path
and not writing_file
.filename
.startswith(from_path
):
211 file_path
= self
.path
+ writing_file
.filename
213 if writing_file
.metadata
["type"] == "sym":
215 self
.fs
.download_to_stream(writing_file
._id
, b
)
217 link
= b
.read().decode("utf-8")
218 os
.symlink(link
, file_path
)
220 with
open(file_path
, 'wb+') as file_stream
:
221 self
.fs
.download_to_stream(writing_file
._id
, file_stream
)
222 if "permissions" in writing_file
.metadata
:
223 os
.chmod(file_path
, writing_file
.metadata
["permissions"])
225 def get_params(self
):
226 return {"fs": "mongo", "path": self
.path
}
228 def fs_connect(self
, config
):
230 if "logger_name" in config
:
231 self
.logger
= logging
.getLogger(config
["logger_name"])
233 self
.path
= config
["path"]
235 raise FsException("Missing parameter \"path\"")
236 if not self
.path
.endswith("/"):
238 if not os
.path
.exists(self
.path
):
239 raise FsException("Invalid configuration param at '[storage]': path '{}' does not exist".format(
241 elif not os
.access(self
.path
, os
.W_OK
):
242 raise FsException("Invalid configuration param at '[storage]': path '{}' is not writable".format(
244 if all(key
in config
.keys() for key
in ["uri", "collection"]):
245 self
.client
= MongoClient(config
["uri"])
246 self
.fs
= GridFSBucket(self
.client
[config
["collection"]])
247 elif all(key
in config
.keys() for key
in ["host", "port", "collection"]):
248 self
.client
= MongoClient(config
["host"], config
["port"])
249 self
.fs
= GridFSBucket(self
.client
[config
["collection"]])
251 if "collection" not in config
.keys():
252 raise FsException("Missing parameter \"collection\"")
254 raise FsException("Missing parameters: \"uri\" or \"host\" + \"port\"")
257 except Exception as e
: # TODO refine
258 raise FsException(str(e
))
260 def fs_disconnect(self
):
263 def mkdir(self
, folder
):
265 Creates a folder or parent object location
267 :return: None or raises an exception
270 self
.fs
.upload_from_stream(
271 folder
, BytesIO(), metadata
={"type": "dir"})
272 except errors
.FileExists
: # make it idempotent
274 except Exception as e
:
275 raise FsException(str(e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
277 def dir_rename(self
, src
, dst
):
279 Rename one directory name. If dst exist, it replaces (deletes) existing directory
280 :param src: source directory
281 :param dst: destination directory
282 :return: None or raises and exception
285 dst_cursor
= self
.fs
.find(
286 {"filename": {"$regex": "^{}(/|$)".format(dst
)}},
287 no_cursor_timeout
=True)
289 for dst_file
in dst_cursor
:
290 self
.fs
.delete(dst_file
._id
)
292 src_cursor
= self
.fs
.find(
293 {"filename": {"$regex": "^{}(/|$)".format(src
)}},
294 no_cursor_timeout
=True)
296 for src_file
in src_cursor
:
297 self
.fs
.rename(src_file
._id
, src_file
.filename
.replace(src
, dst
, 1))
298 except Exception as e
:
299 raise FsException(str(e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
301 def file_exists(self
, storage
, mode
=None):
303 Indicates if "storage" file exist
304 :param storage: can be a str or a str list
305 :param mode: can be 'file' exist as a regular file; 'dir' exists as a directory or; 'None' just exists
308 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
310 cursor
= self
.fs
.find({"filename": f
})
312 for requested_file
in cursor
:
313 exception_file
= next(cursor
, None)
316 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
318 if requested_file
.metadata
["type"] == mode
:
321 if requested_file
.metadata
["type"] == "sym" and mode
== "file":
326 def file_size(self
, storage
):
329 :param storage: can be a str or a str list
332 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
334 cursor
= self
.fs
.find({"filename": f
})
336 for requested_file
in cursor
:
337 exception_file
= next(cursor
, None)
340 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
342 return requested_file
.length
344 def file_extract(self
, tar_object
, path
):
347 :param tar_object: object of type tar
348 :param path: can be a str or a str list, or a tar object where to extract the tar_object
351 f
= path
if isinstance(path
, str) else "/".join(path
)
353 for member
in tar_object
.getmembers():
355 stream
= tar_object
.extractfile(member
)
357 stream
= BytesIO(member
.linkname
.encode("utf-8"))
370 "permissions": member
.mode
373 self
.fs
.upload_from_stream(
374 f
+ "/" + member
.name
,
381 def file_open(self
, storage
, mode
):
384 :param storage: can be a str or list of str
385 :param mode: file mode
389 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
392 return GridByteStream(f
, self
.fs
, mode
)
394 return GridStringStream(f
, self
.fs
, mode
)
395 except errors
.NoFile
:
396 raise FsException("File {} does not exist".format(f
), http_code
=HTTPStatus
.NOT_FOUND
)
398 raise FsException("File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
)
400 def dir_ls(self
, storage
):
402 return folder content
403 :param storage: can be a str or list of str
404 :return: folder content
407 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
410 dir_cursor
= self
.fs
.find({"filename": f
})
411 for requested_dir
in dir_cursor
:
412 exception_dir
= next(dir_cursor
, None)
415 raise FsException("Multiple directories found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
417 if requested_dir
.metadata
["type"] != "dir":
418 raise FsException("File {} does not exist".format(f
), http_code
=HTTPStatus
.NOT_FOUND
)
420 files_cursor
= self
.fs
.find({"filename": {"$regex": "^{}/([^/])*".format(f
)}})
421 for children_file
in files_cursor
:
422 files
+= [children_file
.filename
.replace(f
+ '/', '', 1)]
426 raise FsException("File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
)
428 def file_delete(self
, storage
, ignore_non_exist
=False):
430 Delete storage content recursively
431 :param storage: can be a str or list of str
432 :param ignore_non_exist: not raise exception if storage does not exist
436 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
438 file_cursor
= self
.fs
.find({"filename": f
})
440 for requested_file
in file_cursor
:
442 exception_file
= next(file_cursor
, None)
445 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
447 if requested_file
.metadata
["type"] == "dir":
448 dir_cursor
= self
.fs
.find({"filename": {"$regex": "^{}".format(f
)}})
450 for tmp
in dir_cursor
:
451 self
.fs
.delete(tmp
._id
)
453 self
.fs
.delete(requested_file
._id
)
454 if not found
and not ignore_non_exist
:
455 raise FsException("File {} does not exist".format(storage
), http_code
=HTTPStatus
.NOT_FOUND
)
457 raise FsException("File {} cannot be deleted: {}".format(f
, e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
459 def sync(self
, from_path
=None):
461 Sync from FSMongo to local storage
462 :param from_path: if supplied, only copy content from this path, not all
465 self
.__update
_local
_fs
(from_path
=from_path
)