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
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
114 self
.__initialize
__()
116 def __initialize__(self
):
119 cursor
= self
.fs
.find({"filename": self
.filename
})
121 for requested_file
in cursor
:
122 exception_file
= next(cursor
, None)
125 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
127 if requested_file
.metadata
["type"] in ("file", "dir"):
128 grid_file
= requested_file
129 self
.file_type
= requested_file
.metadata
["type"]
131 raise FsException("File type isn't file", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
135 self
._id
= grid_file
._id
136 self
.fs
.download_to_stream(self
._id
, stream
)
138 self
.write(stream
.read().decode("utf-8"))
146 super(GridStringStream
, self
).close()
150 self
.fs
.delete(self
._id
)
152 cursor
= self
.fs
.find({
153 "filename": self
.filename
.split("/")[0],
154 "metadata": {"type": "dir"}})
156 parent_dir
= next(cursor
, None)
159 parent_dir_name
= self
.filename
.split("/")[0]
160 self
.filename
= self
.filename
.replace(parent_dir_name
, parent_dir_name
[:-1], 1)
164 stream
.write(self
.read().encode("utf-8"))
167 self
.fs
.upload_from_stream_with_id(
171 metadata
={"type": self
.file_type
}
174 self
.fs
.upload_from_stream(
177 metadata
={"type": self
.file_type
}
180 super(GridStringStream
, self
).close()
185 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
189 class FsMongo(FsBase
):
191 def __init__(self
, logger_name
='fs', lock
=False):
192 super().__init
__(logger_name
, lock
)
197 def __update_local_fs(self
):
198 dir_cursor
= self
.fs
.find({"metadata.type": "dir"}, no_cursor_timeout
=True)
200 for directory
in dir_cursor
:
201 os
.makedirs(self
.path
+ directory
.filename
, exist_ok
=True)
203 file_cursor
= self
.fs
.find({"metadata.type": {"$elemMatch": ["file", "sym"]}}, no_cursor_timeout
=True)
205 for writing_file
in file_cursor
:
206 file_path
= self
.path
+ writing_file
.filename
207 file_stream
= open(file_path
, 'wb+')
208 self
.fs
.download_to_stream(writing_file
._id
, file_stream
)
210 if "permissions" in writing_file
.metadata
:
211 if writing_file
.metadata
["type"] == "sym":
214 writing_file
.metadata
["permissions"] | stat
.S_IFLNK
217 os
.chmod(file_path
, writing_file
.metadata
["permissions"])
219 def get_params(self
):
220 return {"fs": "mongo", "path": self
.path
}
222 def fs_connect(self
, config
):
224 if "logger_name" in config
:
225 self
.logger
= logging
.getLogger(config
["logger_name"])
227 self
.path
= config
["path"]
229 raise FsException("Missing parameter \"path\"")
230 if not self
.path
.endswith("/"):
232 if not os
.path
.exists(self
.path
):
233 raise FsException("Invalid configuration param at '[storage]': path '{}' does not exist".format(
235 elif not os
.access(self
.path
, os
.W_OK
):
236 raise FsException("Invalid configuration param at '[storage]': path '{}' is not writable".format(
238 if all(key
in config
.keys() for key
in ["uri", "collection"]):
239 self
.client
= MongoClient(config
["uri"])
240 self
.fs
= GridFSBucket(self
.client
[config
["collection"]])
241 elif all(key
in config
.keys() for key
in ["host", "port", "collection"]):
242 self
.client
= MongoClient(config
["host"], config
["port"])
243 self
.fs
= GridFSBucket(self
.client
[config
["collection"]])
245 if "collection" not in config
.keys():
246 raise FsException("Missing parameter \"collection\"")
248 raise FsException("Missing parameters: \"uri\" or \"host\" + \"port\"")
251 except Exception as e
: # TODO refine
252 raise FsException(str(e
))
254 def fs_disconnect(self
):
257 def mkdir(self
, folder
):
259 Creates a folder or parent object location
261 :return: None or raises an exception
264 self
.fs
.upload_from_stream(
265 folder
, BytesIO(), metadata
={"type": "dir"})
266 except errors
.FileExists
: # make it idempotent
268 except Exception as e
:
269 raise FsException(str(e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
271 def dir_rename(self
, src
, dst
):
273 Rename one directory name. If dst exist, it replaces (deletes) existing directory
274 :param src: source directory
275 :param dst: destination directory
276 :return: None or raises and exception
279 dst_cursor
= self
.fs
.find(
280 {"filename": {"$regex": "^{}(/|$)".format(dst
)}},
281 no_cursor_timeout
=True)
283 for dst_file
in dst_cursor
:
284 self
.fs
.delete(dst_file
._id
)
286 src_cursor
= self
.fs
.find(
287 {"filename": {"$regex": "^{}(/|$)".format(src
)}},
288 no_cursor_timeout
=True)
290 for src_file
in src_cursor
:
291 self
.fs
.rename(src_file
._id
, src_file
.filename
.replace(src
, dst
, 1))
292 except Exception as e
:
293 raise FsException(str(e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
295 def file_exists(self
, storage
, mode
=None):
297 Indicates if "storage" file exist
298 :param storage: can be a str or a str list
299 :param mode: can be 'file' exist as a regular file; 'dir' exists as a directory or; 'None' just exists
302 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
304 cursor
= self
.fs
.find({"filename": f
})
306 for requested_file
in cursor
:
307 exception_file
= next(cursor
, None)
310 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
312 if requested_file
.metadata
["type"] == mode
:
315 if requested_file
.metadata
["type"] == "sym" and mode
== "file":
320 def file_size(self
, storage
):
323 :param storage: can be a str or a str list
326 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
328 cursor
= self
.fs
.find({"filename": f
})
330 for requested_file
in cursor
:
331 exception_file
= next(cursor
, None)
334 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
336 return requested_file
.length
338 def file_extract(self
, tar_object
, path
):
341 :param tar_object: object of type tar
342 :param path: can be a str or a str list, or a tar object where to extract the tar_object
345 f
= path
if isinstance(path
, str) else "/".join(path
)
347 for member
in tar_object
.getmembers():
349 stream
= tar_object
.extractfile(member
)
362 "permissions": member
.mode
365 self
.fs
.upload_from_stream(
366 f
+ "/" + member
.name
,
373 def file_open(self
, storage
, mode
):
376 :param storage: can be a str or list of str
377 :param mode: file mode
381 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
384 return GridByteStream(f
, self
.fs
, mode
)
386 return GridStringStream(f
, self
.fs
, mode
)
387 except errors
.NoFile
:
388 raise FsException("File {} does not exist".format(f
), http_code
=HTTPStatus
.NOT_FOUND
)
390 raise FsException("File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
)
392 def dir_ls(self
, storage
):
394 return folder content
395 :param storage: can be a str or list of str
396 :return: folder content
399 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
402 dir_cursor
= self
.fs
.find({"filename": f
})
403 for requested_dir
in dir_cursor
:
404 exception_dir
= next(dir_cursor
, None)
407 raise FsException("Multiple directories found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
409 if requested_dir
.metadata
["type"] != "dir":
410 raise FsException("File {} does not exist".format(f
), http_code
=HTTPStatus
.NOT_FOUND
)
412 files_cursor
= self
.fs
.find({"filename": {"$regex": "^{}/([^/])*".format(f
)}})
413 for children_file
in files_cursor
:
414 files
+= [children_file
.filename
.replace(f
+ '/', '', 1)]
418 raise FsException("File {} cannot be opened".format(f
), http_code
=HTTPStatus
.BAD_REQUEST
)
420 def file_delete(self
, storage
, ignore_non_exist
=False):
422 Delete storage content recursively
423 :param storage: can be a str or list of str
424 :param ignore_non_exist: not raise exception if storage does not exist
428 f
= storage
if isinstance(storage
, str) else "/".join(storage
)
430 file_cursor
= self
.fs
.find({"filename": f
})
432 for requested_file
in file_cursor
:
434 exception_file
= next(file_cursor
, None)
437 raise FsException("Multiple files found", http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
439 if requested_file
.metadata
["type"] == "dir":
440 dir_cursor
= self
.fs
.find({"filename": {"$regex": "^{}".format(f
)}})
442 for tmp
in dir_cursor
:
443 self
.fs
.delete(tmp
._id
)
445 self
.fs
.delete(requested_file
._id
)
446 if not found
and not ignore_non_exist
:
447 raise FsException("File {} does not exist".format(storage
), http_code
=HTTPStatus
.NOT_FOUND
)
449 raise FsException("File {} cannot be deleted: {}".format(f
, e
), http_code
=HTTPStatus
.INTERNAL_SERVER_ERROR
)
453 Sync from FSMongo to local storage
455 self
.__update
_local
_fs
()