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
):
199 dir_cursor
= self
.fs
.find({"metadata.type": "dir"}, no_cursor_timeout
=True)
201 for directory
in dir_cursor
:
202 os
.makedirs(self
.path
+ directory
.filename
, exist_ok
=True)
204 file_cursor
= self
.fs
.find({"metadata.type": {"$in": ["file", "sym"]}}, no_cursor_timeout
=True)
206 for writing_file
in file_cursor
:
207 file_path
= self
.path
+ writing_file
.filename
209 if writing_file
.metadata
["type"] == "sym":
211 self
.fs
.download_to_stream(writing_file
._id
, b
)
213 link
= b
.read().decode("utf-8")
214 os
.symlink(link
, file_path
)
216 with
open(file_path
, 'wb+') as file_stream
:
217 self
.fs
.download_to_stream(writing_file
._id
, file_stream
)
218 if "permissions" in writing_file
.metadata
:
219 os
.chmod(file_path
, writing_file
.metadata
["permissions"])
221 def get_params(self
):
222 return {"fs": "mongo", "path": self
.path
}
224 def fs_connect(self
, config
):
226 if "logger_name" in config
:
227 self
.logger
= logging
.getLogger(config
["logger_name"])
229 self
.path
= config
["path"]
231 raise FsException("Missing parameter \"path\"")
232 if not self
.path
.endswith("/"):
234 if not os
.path
.exists(self
.path
):
235 raise FsException("Invalid configuration param at '[storage]': path '{}' does not exist".format(
237 elif not os
.access(self
.path
, os
.W_OK
):
238 raise FsException("Invalid configuration param at '[storage]': path '{}' is not writable".format(
240 if all(key
in config
.keys() for key
in ["uri", "collection"]):
241 self
.client
= MongoClient(config
["uri"])
242 self
.fs
= GridFSBucket(self
.client
[config
["collection"]])
243 elif all(key
in config
.keys() for key
in ["host", "port", "collection"]):
244 self
.client
= MongoClient(config
["host"], config
["port"])
245 self
.fs
= GridFSBucket(self
.client
[config
["collection"]])
247 if "collection" not in config
.keys():
248 raise FsException("Missing parameter \"collection\"")
250 raise FsException("Missing parameters: \"uri\" or \"host\" + \"port\"")
253 except Exception as e
: # TODO refine
254 raise FsException(str(e
))
256 def fs_disconnect(self
):
259 def mkdir(self
, folder
):
261 Creates a folder or parent object location
263 :return: None or raises an exception
266 self
.fs
.upload_from_stream(
267 folder
, BytesIO(), metadata
={"type": "dir"})
268 except errors
.FileExists
: # make it idempotent
270 except Exception as e
:
271 raise FsException(str(e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
273 def dir_rename(self
, src
, dst
):
275 Rename one directory name. If dst exist, it replaces (deletes) existing directory
276 :param src: source directory
277 :param dst: destination directory
278 :return: None or raises and exception
281 dst_cursor
= self
.fs
.find(
282 {"filename": {"$regex": "^{}(/|$)".format(dst
)}},
283 no_cursor_timeout
=True)
285 for dst_file
in dst_cursor
:
286 self
.fs
.delete(dst_file
._id
)
288 src_cursor
= self
.fs
.find(
289 {"filename": {"$regex": "^{}(/|$)".format(src
)}},
290 no_cursor_timeout
=True)
292 for src_file
in src_cursor
:
293 self
.fs
.rename(src_file
._id
, src_file
.filename
.replace(src
, dst
, 1))
294 except Exception as e
:
295 raise FsException(str(e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
297 def file_exists(self
, storage
, mode
=None):
299 Indicates if "storage" file exist
300 :param storage: can be a str or a str list
301 :param mode: can be 'file' exist as a regular file; 'dir' exists as a directory or; 'None' just exists
304 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
306 cursor
= self
.fs
.find({"filename": f
})
308 for requested_file
in cursor
:
309 exception_file
= next(cursor
, None)
312 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
314 if requested_file
.metadata
["type"] == mode
:
317 if requested_file
.metadata
["type"] == "sym" and mode
== "file":
322 def file_size(self
, storage
):
325 :param storage: can be a str or a str list
328 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
330 cursor
= self
.fs
.find({"filename": f
})
332 for requested_file
in cursor
:
333 exception_file
= next(cursor
, None)
336 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
338 return requested_file
.length
340 def file_extract(self
, tar_object
, path
):
343 :param tar_object: object of type tar
344 :param path: can be a str or a str list, or a tar object where to extract the tar_object
347 f
= path
if isinstance(path
, str) else "/".join(path
)
349 for member
in tar_object
.getmembers():
351 stream
= tar_object
.extractfile(member
)
353 stream
= BytesIO(member
.linkname
.encode("utf-8"))
366 "permissions": member
.mode
369 self
.fs
.upload_from_stream(
370 f
+ "/" + member
.name
,
377 def file_open(self
, storage
, mode
):
380 :param storage: can be a str or list of str
381 :param mode: file mode
385 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
388 return GridByteStream(f
, self
.fs
, mode
)
390 return GridStringStream(f
, self
.fs
, mode
)
391 except errors
.NoFile
:
392 raise FsException("File {} does not exist".format(f
), http_code
=HTTPStatus
.NOT_FOUND
)
394 raise FsException("File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
)
396 def dir_ls(self
, storage
):
398 return folder content
399 :param storage: can be a str or list of str
400 :return: folder content
403 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
406 dir_cursor
= self
.fs
.find({"filename": f
})
407 for requested_dir
in dir_cursor
:
408 exception_dir
= next(dir_cursor
, None)
411 raise FsException("Multiple directories found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
413 if requested_dir
.metadata
["type"] != "dir":
414 raise FsException("File {} does not exist".format(f
), http_code
=HTTPStatus
.NOT_FOUND
)
416 files_cursor
= self
.fs
.find({"filename": {"$regex": "^{}/([^/])*".format(f
)}})
417 for children_file
in files_cursor
:
418 files
+= [children_file
.filename
.replace(f
+ '/', '', 1)]
422 raise FsException("File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
)
424 def file_delete(self
, storage
, ignore_non_exist
=False):
426 Delete storage content recursively
427 :param storage: can be a str or list of str
428 :param ignore_non_exist: not raise exception if storage does not exist
432 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
434 file_cursor
= self
.fs
.find({"filename": f
})
436 for requested_file
in file_cursor
:
438 exception_file
= next(file_cursor
, None)
441 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
443 if requested_file
.metadata
["type"] == "dir":
444 dir_cursor
= self
.fs
.find({"filename": {"$regex": "^{}".format(f
)}})
446 for tmp
in dir_cursor
:
447 self
.fs
.delete(tmp
._id
)
449 self
.fs
.delete(requested_file
._id
)
450 if not found
and not ignore_non_exist
:
451 raise FsException("File {} does not exist".format(storage
), http_code
=HTTPStatus
.NOT_FOUND
)
453 raise FsException("File {} cannot be deleted: {}".format(f
, e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
457 Sync from FSMongo to local storage
459 self
.__update
_local
_fs
()