Docker Volume and C++ std::filesystem::rename

120 Views Asked by At

I want to serialize game atomically. I use std::filesystem rename for this problem:

void SerializeGameAtomic ( const Game & game , fs::path state_file)
{
  std::cout << " Start Atomic Serialization" << std::endl;
  std::string temporary_path = "TemporaryBackup"s;
  std::ofstream output_file;
  output_file.open(temporary_path.data(), std::ios::out);
  if (output_file.is_open()){
    std::cout << "File was created" << std::endl;
  }
  else {
    std::cout << "File was not created" << std::endl;
  }
  boost::archive::text_oarchive oa{output_file};
  oa << game;
  output_file.close();
  auto state_path = fs::path(state_file);
  fs::create_directories(state_path.parent_path());
  std::cout << "Try Rename" << std::endl;
  fs::rename(fs::path(temporary_path), state_path);
  std::cout << "File was copied" << std::endl;
}

It work correctly at local machine and in docker container. However when i try to use host filesystem in container using volume flag: sudo docker run --rm -p 80:8080 -v /home/work/volume/:tmp/volume:rw game_server

I get exception : filesystem error: cannot rename: Invalid cross-device link [TemporaryBackup] [/tmp/volume/state]'

What may cause this exception ?

1

There are 1 best solutions below

0
Дмитрий Ведерников On

This comment was very useful and solve my problem:

Exactly that: Renames are only atomic between files on the same filesystem. Create output_file under state_path.parent_path() instead of the current working directory. – Botje

Files exactly should be located at the same filesystem. I use state_path.parent_path() for temporary file.