Apache Mesos
rename.hpp
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12 
13 #ifndef __STOUT_OS_POSIX_RENAME_HPP__
14 #define __STOUT_OS_POSIX_RENAME_HPP__
15 
16 #include <stdio.h>
17 
18 #include <string>
19 #include <vector>
20 
21 #include <stout/error.hpp>
22 #include <stout/foreach.hpp>
23 #include <stout/nothing.hpp>
24 #include <stout/path.hpp>
25 #include <stout/try.hpp>
26 
27 #include <stout/os/fsync.hpp>
28 
29 namespace os {
30 
31 // Rename a given path to another one. If `sync` is set to true, `fsync()` will
32 // be called on both the source directory and the destination directory to
33 // ensure that the result is committed to their filesystems.
34 //
35 // NOTE: This function can fail with `sync` set to true if either the source
36 // directory or the destination directory gets removed before it returns. If
37 // multiple processes or threads access to the filesystems concurrently, the
38 // caller should either enforce a proper synchronization, or set `sync` to false
39 // and call `fsync()` explicitly on POSIX systems to handle such failures.
41  const std::string& from,
42  const std::string& to,
43  bool sync = false)
44 {
45  if (::rename(from.c_str(), to.c_str()) != 0) {
46  return ErrnoError();
47  }
48 
49  if (sync) {
50  const std::string to_dir = Path(to).dirname();
51  const std::string from_dir = Path(from).dirname();
52 
53  std::vector<std::string> dirs = {to_dir};
54  if (from_dir != to_dir) {
55  dirs.emplace_back(from_dir);
56  }
57 
58  foreach (const std::string& dir, dirs) {
60 
61  if (fsync.isError()) {
62  return Error(
63  "Failed to fsync directory '" + dir + "': " + fsync.error());
64  }
65  }
66  }
67 
68  return Nothing();
69 }
70 
71 } // namespace os {
72 
73 #endif // __STOUT_OS_POSIX_RENAME_HPP__
Definition: nothing.hpp:16
Definition: errorbase.hpp:36
Definition: check.hpp:33
Definition: errorbase.hpp:50
Definition: posix_signalhandler.hpp:23
Represents a POSIX or Windows file system path and offers common path manipulations.
Definition: path.hpp:212
static Try error(const E &e)
Definition: try.hpp:43
std::string dirname() const
Extracts the component up to, but not including, the final &#39;/&#39;.
Definition: path.hpp:308
Try< Nothing > fsync(int fd)
Definition: fsync.hpp:29
Try< Nothing > rename(const std::string &from, const std::string &to, bool sync=false)
Definition: rename.hpp:40
bool isError() const
Definition: try.hpp:78