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
26 from osm_common
.fsbase
import FsBase
, FsException
28 __author__
= "Eduardo Sousa <eduardo.sousa@canonical.com>"
31 class GridByteStream(BytesIO
):
32 def __init__(self
, filename
, fs
, mode
):
33 BytesIO
.__init
__(self
)
35 self
.filename
= filename
38 self
.file_type
= "file" # Set "file" as default file_type
42 def __initialize__(self
):
45 cursor
= self
.fs
.find({"filename": self
.filename
})
47 for requested_file
in cursor
:
48 exception_file
= next(cursor
, None)
51 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
53 if requested_file
.metadata
["type"] in ("file", "sym"):
54 grid_file
= requested_file
55 self
.file_type
= requested_file
.metadata
["type"]
57 raise FsException("Type isn't file", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
60 self
._id
= grid_file
._id
61 self
.fs
.download_to_stream(self
._id
, self
)
68 super(GridByteStream
, self
).close()
72 self
.fs
.delete(self
._id
)
74 cursor
= self
.fs
.find({
75 "filename": self
.filename
.split("/")[0],
76 "metadata": {"type": "dir"}})
78 parent_dir
= next(cursor
, None)
81 parent_dir_name
= self
.filename
.split("/")[0]
82 self
.filename
= self
.filename
.replace(parent_dir_name
, parent_dir_name
[:-1], 1)
86 self
.fs
.upload_from_stream_with_id(
90 metadata
={"type": self
.file_type
}
93 self
.fs
.upload_from_stream(
96 metadata
={"type": self
.file_type
}
98 super(GridByteStream
, self
).close()
103 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
107 class GridStringStream(StringIO
):
108 def __init__(self
, filename
, fs
, mode
):
109 StringIO
.__init
__(self
)
111 self
.filename
= filename
114 self
.file_type
= "file" # Set "file" as default file_type
116 self
.__initialize
__()
118 def __initialize__(self
):
121 cursor
= self
.fs
.find({"filename": self
.filename
})
123 for requested_file
in cursor
:
124 exception_file
= next(cursor
, None)
127 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
129 if requested_file
.metadata
["type"] in ("file", "dir"):
130 grid_file
= requested_file
131 self
.file_type
= requested_file
.metadata
["type"]
133 raise FsException("File type isn't file", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
137 self
._id
= grid_file
._id
138 self
.fs
.download_to_stream(self
._id
, stream
)
140 self
.write(stream
.read().decode("utf-8"))
148 super(GridStringStream
, self
).close()
152 self
.fs
.delete(self
._id
)
154 cursor
= self
.fs
.find({
155 "filename": self
.filename
.split("/")[0],
156 "metadata": {"type": "dir"}})
158 parent_dir
= next(cursor
, None)
161 parent_dir_name
= self
.filename
.split("/")[0]
162 self
.filename
= self
.filename
.replace(parent_dir_name
, parent_dir_name
[:-1], 1)
166 stream
.write(self
.read().encode("utf-8"))
169 self
.fs
.upload_from_stream_with_id(
173 metadata
={"type": self
.file_type
}
176 self
.fs
.upload_from_stream(
179 metadata
={"type": self
.file_type
}
182 super(GridStringStream
, self
).close()
187 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
191 class FsMongo(FsBase
):
193 def __init__(self
, logger_name
='fs', lock
=False):
194 super().__init
__(logger_name
, lock
)
199 def __update_local_fs(self
):
200 dir_cursor
= self
.fs
.find({"metadata.type": "dir"}, no_cursor_timeout
=True)
202 for directory
in dir_cursor
:
203 os
.makedirs(self
.path
+ directory
.filename
, exist_ok
=True)
205 file_cursor
= self
.fs
.find({"metadata.type": {"$in": ["file", "sym"]}}, no_cursor_timeout
=True)
207 for writing_file
in file_cursor
:
208 file_path
= self
.path
+ writing_file
.filename
209 file_stream
= open(file_path
, 'wb+')
210 self
.fs
.download_to_stream(writing_file
._id
, file_stream
)
212 if "permissions" in writing_file
.metadata
:
213 if writing_file
.metadata
["type"] == "sym":
216 writing_file
.metadata
["permissions"] | stat
.S_IFLNK
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
)
364 "permissions": member
.mode
367 self
.fs
.upload_from_stream(
368 f
+ "/" + member
.name
,
375 def file_open(self
, storage
, mode
):
378 :param storage: can be a str or list of str
379 :param mode: file mode
383 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
386 return GridByteStream(f
, self
.fs
, mode
)
388 return GridStringStream(f
, self
.fs
, mode
)
389 except errors
.NoFile
:
390 raise FsException("File {} does not exist".format(f
), http_code
=HTTPStatus
.NOT_FOUND
)
392 raise FsException("File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
)
394 def dir_ls(self
, storage
):
396 return folder content
397 :param storage: can be a str or list of str
398 :return: folder content
401 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
404 dir_cursor
= self
.fs
.find({"filename": f
})
405 for requested_dir
in dir_cursor
:
406 exception_dir
= next(dir_cursor
, None)
409 raise FsException("Multiple directories found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
411 if requested_dir
.metadata
["type"] != "dir":
412 raise FsException("File {} does not exist".format(f
), http_code
=HTTPStatus
.NOT_FOUND
)
414 files_cursor
= self
.fs
.find({"filename": {"$regex": "^{}/([^/])*".format(f
)}})
415 for children_file
in files_cursor
:
416 files
+= [children_file
.filename
.replace(f
+ '/', '', 1)]
420 raise FsException("File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
)
422 def file_delete(self
, storage
, ignore_non_exist
=False):
424 Delete storage content recursively
425 :param storage: can be a str or list of str
426 :param ignore_non_exist: not raise exception if storage does not exist
430 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
432 file_cursor
= self
.fs
.find({"filename": f
})
434 for requested_file
in file_cursor
:
436 exception_file
= next(file_cursor
, None)
439 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
441 if requested_file
.metadata
["type"] == "dir":
442 dir_cursor
= self
.fs
.find({"filename": {"$regex": "^{}".format(f
)}})
444 for tmp
in dir_cursor
:
445 self
.fs
.delete(tmp
._id
)
447 self
.fs
.delete(requested_file
._id
)
448 if not found
and not ignore_non_exist
:
449 raise FsException("File {} does not exist".format(storage
), http_code
=HTTPStatus
.NOT_FOUND
)
451 raise FsException("File {} cannot be deleted: {}".format(f
, e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
455 Sync from FSMongo to local storage
457 self
.__update
_local
_fs
()