Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
s4u filesystem: correctly update size of files when changed
[simgrid.git] / src / plugins / file_system / s4u_FileSystem.cpp
1 /* Copyright (c) 2015-2022. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include <simgrid/plugins/file_system.h>
7 #include <simgrid/s4u/Comm.hpp>
8 #include <simgrid/s4u/Disk.hpp>
9 #include <simgrid/s4u/Engine.hpp>
10 #include <simgrid/s4u/Host.hpp>
11 #include <simgrid/simix.hpp>
12 #include <xbt/asserts.h>
13 #include <xbt/config.hpp>
14 #include <xbt/log.h>
15 #include <xbt/parse_units.hpp>
16
17 #include "src/surf/surf_interface.hpp"
18
19 #include <boost/algorithm/string.hpp>
20 #include <boost/algorithm/string/split.hpp>
21 #include <fstream>
22 #include <numeric>
23
24 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(s4u_file, s4u, "S4U files");
25 int sg_storage_max_file_descriptors = 1024;
26
27 /** @defgroup plugin_filesystem Plugin FileSystem
28  *
29  * This adds the notion of Files on top of the storage notion that provided by the core of SimGrid.
30  * Activate this plugin at will.
31  */
32
33 namespace simgrid {
34
35 template class xbt::Extendable<s4u::File>;
36
37 namespace s4u {
38 simgrid::xbt::Extension<Disk, FileSystemDiskExt> FileSystemDiskExt::EXTENSION_ID;
39 simgrid::xbt::Extension<Host, FileDescriptorHostExt> FileDescriptorHostExt::EXTENSION_ID;
40
41 const Disk* File::find_local_disk_on(const Host* host)
42 {
43   const Disk* d                = nullptr;
44   size_t longest_prefix_length = 0;
45   for (auto const& disk : host->get_disks()) {
46     std::string current_mount;
47     if (disk->get_host() != host)
48       current_mount = disk->extension<FileSystemDiskExt>()->get_mount_point(disk->get_host());
49     else
50       current_mount = disk->extension<FileSystemDiskExt>()->get_mount_point();
51     mount_point_ = fullpath_.substr(0, current_mount.length());
52     if (mount_point_ == current_mount && current_mount.length() > longest_prefix_length) {
53       /* The current mount name is found in the full path and is bigger than the previous*/
54       longest_prefix_length = current_mount.length();
55       d                     = disk;
56     }
57     xbt_assert(longest_prefix_length > 0, "Can't find mount point for '%s' on '%s'", fullpath_.c_str(),
58                host->get_cname());
59     /* Mount point found, split fullpath_ into mount_name and path+filename*/
60     mount_point_ = fullpath_.substr(0, longest_prefix_length);
61     if (mount_point_ == std::string("/"))
62       path_ = fullpath_;
63     else
64       path_ = fullpath_.substr(longest_prefix_length, fullpath_.length());
65     XBT_DEBUG("%s + %s", mount_point_.c_str(), path_.c_str());
66   }
67   return d;
68 }
69
70 File::File(const std::string& fullpath, void* userdata) : File(fullpath, Host::current(), userdata) {}
71
72 File::File(const std::string& fullpath, const_sg_host_t host, void* userdata) : fullpath_(fullpath)
73 {
74   kernel::actor::simcall_answered([this, &host, userdata] {
75     this->set_data(userdata);
76     // this cannot fail because we get a xbt_die if the mountpoint does not exist
77     local_disk_ = find_local_disk_on(host);
78
79     // assign a file descriptor id to the newly opened File
80     auto* ext = host->extension<simgrid::s4u::FileDescriptorHostExt>();
81     if (ext->file_descriptor_table == nullptr) {
82       ext->file_descriptor_table = std::make_unique<std::vector<int>>(sg_storage_max_file_descriptors);
83       std::iota(ext->file_descriptor_table->rbegin(), ext->file_descriptor_table->rend(), 0); // Fill with ..., 1, 0.
84     }
85     xbt_assert(not ext->file_descriptor_table->empty(), "Too much files are opened! Some have to be closed.");
86     desc_id = ext->file_descriptor_table->back();
87     ext->file_descriptor_table->pop_back();
88
89     std::map<std::string, sg_size_t, std::less<>>* content = nullptr;
90     content = local_disk_->extension<FileSystemDiskExt>()->get_content();
91
92     // if file does not exist create an empty file
93     if (content) {
94       auto sz = content->find(path_);
95       if (sz != content->end()) {
96         size_ = sz->second;
97         XBT_DEBUG("\tOpen file '%s', size %llu", path_.c_str(), size_);
98       } else {
99         size_ = 0;
100         content->insert({path_, size_});
101         XBT_DEBUG("File '%s' was not found, file created.", path_.c_str());
102       }
103     }
104   });
105 }
106
107 File::~File() = default;
108
109 File* File::open(const std::string& fullpath, void* userdata)
110 {
111   return new File(fullpath, userdata);
112 }
113
114 File* File::open(const std::string& fullpath, const_sg_host_t host, void* userdata)
115 {
116   return new File(fullpath, host, userdata);
117 }
118
119 void File::close()
120 {
121   std::vector<int>* desc_table =
122       Host::current()->extension<simgrid::s4u::FileDescriptorHostExt>()->file_descriptor_table.get();
123   kernel::actor::simcall_answered([this, desc_table] { desc_table->push_back(this->desc_id); });
124   delete this;
125 }
126
127 void File::dump() const
128 {
129   XBT_INFO("File Descriptor information:\n"
130       "\t\tFull path: '%s'\n"
131       "\t\tSize: %llu\n"
132       "\t\tMount point: '%s'\n"
133       "\t\tDisk Id: '%s'\n"
134       "\t\tHost Id: '%s'\n"
135       "\t\tFile Descriptor Id: %d",
136       get_path(), size_, mount_point_.c_str(), local_disk_->get_cname(), local_disk_->get_host()->get_cname(),
137       desc_id);
138 }
139
140 sg_size_t File::read(sg_size_t size)
141 {
142   if (size_ == 0) /* Nothing to read, return */
143     return 0;
144   Host* host          = nullptr;
145   // if the current position is close to the end of the file, we may not be able to read the requested size
146   sg_size_t to_read   = std::min(size, size_ - current_position_);
147   sg_size_t read_size = 0;
148
149   /* Find the host where the file is physically located and read it */
150   host = local_disk_->get_host();
151   XBT_DEBUG("READ %s on disk '%s'", get_path(), local_disk_->get_cname());
152   read_size = local_disk_->read(to_read);
153
154   current_position_ += read_size;
155
156   if (host && host->get_name() != Host::current()->get_name() && read_size > 0) {
157     /* the file is hosted on a remote host, initiate a communication between src and dest hosts for data transfer */
158     XBT_DEBUG("File is on %s remote host, initiate data transfer of %llu bytes.", host->get_cname(), read_size);
159     Comm::sendto(host, Host::current(), read_size);
160   }
161
162   return read_size;
163 }
164
165 /** @brief Write into a file (local or remote)
166  * @ingroup plugin_filesystem
167  *
168  * @param size of the file to write
169  * @param write_inside
170  * @return the number of bytes successfully write or -1 if an error occurred
171  */
172 sg_size_t File::write(sg_size_t size, bool write_inside)
173 {
174   if (size == 0) /* Nothing to write, return */
175     return 0;
176
177   sg_size_t write_size = 0;
178   /* Find the host where the file is physically located (remote or local)*/
179   if (Host* host = local_disk_->get_host(); host && host->get_name() != Host::current()->get_name()) {
180     /* the file is hosted on a remote host, initiate a communication between src and dest hosts for data transfer */
181     XBT_DEBUG("File is on %s remote host, initiate data transfer of %llu bytes.", host->get_cname(), size);
182     Comm::sendto(Host::current(), host, size);
183   }
184   XBT_DEBUG("WRITE %s on disk '%s'. size '%llu/%llu' '%llu:%llu'", get_path(), local_disk_->get_cname(), size, size_,
185             sg_disk_get_size_used(local_disk_), sg_disk_get_size(local_disk_));
186   // If the disk is full before even starting to write
187   if (sg_disk_get_size_used(local_disk_) >= sg_disk_get_size(local_disk_))
188     return 0;
189   if (not write_inside)
190     /* Subtract the part of the file that might disappear from the used sized on the storage element */
191     local_disk_->extension<FileSystemDiskExt>()->decr_used_size(size_ - current_position_);
192   write_size = local_disk_->write(size);
193   update_position(current_position_ + write_size);
194
195   return write_size;
196 }
197
198 sg_size_t File::size() const
199 {
200   return size_;
201 }
202
203 void File::seek(sg_offset_t offset)
204 {
205   current_position_ = offset;
206 }
207
208 void File::seek(sg_offset_t offset, int origin)
209 {
210   switch (origin) {
211     case SEEK_SET:
212       update_position(offset);
213      break;
214     case SEEK_CUR:
215       update_position(current_position_ + offset);
216       break;
217     case SEEK_END:
218       update_position(size_ + offset);
219       break;
220     default:
221       break;
222   }
223 }
224
225 void File::update_position(sg_offset_t position)
226 {
227   xbt_assert(position >= 0, "Error in seek, cannot seek before file %s", get_path());
228   current_position_ = position;
229   if(current_position_>size_){
230     XBT_DEBUG("Updating size of file %s from %llu to %llu", path_.c_str(), size_, position);
231     local_disk_->extension<FileSystemDiskExt>()->incr_used_size(current_position_-size_);
232     size_ = current_position_;
233
234     kernel::actor::simcall_answered([this] {
235     std::map<std::string, sg_size_t, std::less<>>* content = local_disk_->extension<FileSystemDiskExt>()->get_content();
236     content->erase(path_);
237     content->insert({path_, size_});
238   });
239   }
240 }
241
242 sg_size_t File::tell() const
243 {
244   return current_position_;
245 }
246
247 void File::move(const std::string& fullpath) const
248 {
249   /* Check if the new full path is on the same mount point */
250   if (fullpath.compare(0, mount_point_.length(), mount_point_) == 0) {
251     std::map<std::string, sg_size_t, std::less<>>* content = nullptr;
252     content = local_disk_->extension<FileSystemDiskExt>()->get_content();
253     if (content) {
254       auto sz = content->find(path_);
255       if (sz != content->end()) { // src file exists
256         sg_size_t new_size = sz->second;
257         content->erase(path_);
258         std::string path = fullpath.substr(mount_point_.length(), fullpath.length());
259         content->insert({path.c_str(), new_size});
260         XBT_DEBUG("Move file from %s to %s, size '%llu'", path_.c_str(), fullpath.c_str(), new_size);
261       } else {
262         XBT_WARN("File %s doesn't exist", path_.c_str());
263       }
264     }
265   } else {
266     XBT_WARN("New full path %s is not on the same mount point: %s.", fullpath.c_str(), mount_point_.c_str());
267   }
268 }
269
270 int File::unlink() const
271 {
272   /* Check if the file is on local storage */
273   auto* content    = local_disk_->extension<FileSystemDiskExt>()->get_content();
274   const char* name = local_disk_->get_cname();
275
276   if (not content || content->find(path_) == content->end()) {
277     XBT_WARN("File %s is not on disk %s. Impossible to unlink", path_.c_str(), name);
278     return -1;
279   } else {
280     XBT_DEBUG("UNLINK %s of size %llu on disk '%s'", path_.c_str(), size_, name);
281
282     local_disk_->extension<FileSystemDiskExt>()->decr_used_size(size_);
283     // Remove the file from storage
284     content->erase(path_);
285
286     return 0;
287   }
288 }
289
290 int File::remote_copy(sg_host_t host, const std::string& fullpath)
291 {
292   /* Find the host where the file is physically located and read it */
293   Host* src_host      = nullptr;
294   sg_size_t read_size = 0;
295
296   Host* dst_host = host;
297   size_t longest_prefix_length = 0;
298
299   seek(0, SEEK_SET);
300
301   src_host = local_disk_->get_host();
302   XBT_DEBUG("READ %s on disk '%s'", get_path(), local_disk_->get_cname());
303   read_size = local_disk_->read(size_);
304   current_position_ += read_size;
305
306   const Disk* dst_disk = nullptr;
307
308   for (auto const& disk : host->get_disks()) {
309     std::string current_mount = disk->extension<FileSystemDiskExt>()->get_mount_point();
310     std::string mount_point   = std::string(fullpath).substr(0, current_mount.length());
311     if (mount_point == current_mount && current_mount.length() > longest_prefix_length) {
312       /* The current mount name is found in the full path and is bigger than the previous*/
313       longest_prefix_length = current_mount.length();
314       dst_disk              = disk;
315     }
316   }
317
318   if (dst_disk == nullptr) {
319     XBT_WARN("Can't find mount point for '%s' on destination host '%s'", fullpath.c_str(), host->get_cname());
320     return -1;
321   }
322
323   if (src_host) {
324     XBT_DEBUG("Initiate data transfer of %llu bytes between %s and %s.", read_size, src_host->get_cname(),
325               dst_host->get_cname());
326     Comm::sendto(src_host, dst_host, read_size);
327   }
328
329   /* Create file on remote host, write it and close it */
330   auto* fd = File::open(fullpath, dst_host, nullptr);
331   fd->write(read_size);
332   fd->close();
333   return 0;
334 }
335
336 int File::remote_move(sg_host_t host, const std::string& fullpath)
337 {
338   int res = remote_copy(host, fullpath);
339   unlink();
340   return res;
341 }
342
343 FileSystemDiskExt::FileSystemDiskExt(const Disk* ptr)
344 {
345   if (const char* size_str = ptr->get_property("size")) {
346     std::string dummyfile;
347     size_ = xbt_parse_get_size(dummyfile, -1, size_str, "disk size " + ptr->get_name());
348   }
349
350   if (const char* current_mount_str = ptr->get_property("mount"))
351     mount_point_ = std::string(current_mount_str);
352   else
353     mount_point_ = std::string("/");
354
355   if (const char* content_str = ptr->get_property("content"))
356     content_.reset(parse_content(content_str));
357 }
358
359 std::map<std::string, sg_size_t, std::less<>>* FileSystemDiskExt::parse_content(const std::string& filename)
360 {
361   if (filename.empty())
362     return nullptr;
363
364   auto* parse_content = new std::map<std::string, sg_size_t, std::less<>>();
365
366   auto fs = std::unique_ptr<std::ifstream>(surf_ifsopen(filename));
367   xbt_assert(not fs->fail(), "Cannot open file '%s' (path=%s)", filename.c_str(),
368              (boost::join(surf_path, ":")).c_str());
369
370   std::string line;
371   std::vector<std::string> tokens;
372   do {
373     std::getline(*fs, line);
374     boost::trim(line);
375     if (line.length() > 0) {
376       boost::split(tokens, line, boost::is_any_of(" \t"), boost::token_compress_on);
377       xbt_assert(tokens.size() == 2, "Parse error in %s: %s", filename.c_str(), line.c_str());
378       sg_size_t size = std::stoull(tokens.at(1));
379
380       used_size_ += size;
381       parse_content->insert({tokens.front(), size});
382     }
383   } while (not fs->eof());
384   return parse_content;
385 }
386
387 void FileSystemDiskExt::add_remote_mount(Host* host, const std::string& mount_point)
388 {
389   remote_mount_points_.try_emplace(host, mount_point);
390 }
391
392 void FileSystemDiskExt::decr_used_size(sg_size_t size)
393 {
394   simgrid::kernel::actor::simcall_answered([this, size] { used_size_ -= size; });
395 }
396
397 void FileSystemDiskExt::incr_used_size(sg_size_t size)
398 {
399   simgrid::kernel::actor::simcall_answered([this, size] { used_size_ += size; });
400 }
401 }
402 }
403
404 using simgrid::s4u::FileDescriptorHostExt;
405 using simgrid::s4u::FileSystemDiskExt;
406
407 static void on_disk_creation(simgrid::s4u::Disk& d)
408 {
409   d.extension_set(new FileSystemDiskExt(&d));
410 }
411
412 static void on_host_creation(simgrid::s4u::Host& host)
413 {
414   host.extension_set<FileDescriptorHostExt>(new FileDescriptorHostExt());
415 }
416
417 static void on_platform_created()
418 {
419   for (auto const& host : simgrid::s4u::Engine::get_instance()->get_all_hosts()) {
420     const char* remote_disk_str = host->get_property("remote_disk");
421     if (remote_disk_str) {
422       std::vector<std::string> tokens;
423       boost::split(tokens, remote_disk_str, boost::is_any_of(":"));
424       std::string mount_point         = tokens[0];
425       simgrid::s4u::Host* remote_host = simgrid::s4u::Host::by_name_or_null(tokens[2]);
426       xbt_assert(remote_host, "You're trying to access a host that does not exist. Please check your platform file");
427
428       const simgrid::s4u::Disk* disk = nullptr;
429       for (auto const& d : remote_host->get_disks())
430         if (d->get_name() == tokens[1]) {
431           disk = d;
432           break;
433         }
434
435       xbt_assert(disk, "You're trying to mount a disk that does not exist. Please check your platform file");
436       disk->extension<FileSystemDiskExt>()->add_remote_mount(remote_host, mount_point);
437       host->add_disk(disk);
438
439       XBT_DEBUG("Host '%s' wants to mount a remote disk: %s of %s mounted on %s", host->get_cname(), disk->get_cname(),
440                 remote_host->get_cname(), mount_point.c_str());
441       XBT_DEBUG("Host '%s' now has %zu disks", host->get_cname(), host->get_disks().size());
442     }
443   }
444 }
445
446 static void on_simulation_end()
447 {
448   XBT_DEBUG("Simulation is over, time to unregister remote disks if any");
449   for (auto const& host : simgrid::s4u::Engine::get_instance()->get_all_hosts()) {
450     const char* remote_disk_str = host->get_property("remote_disk");
451     if (remote_disk_str) {
452       std::vector<std::string> tokens;
453       boost::split(tokens, remote_disk_str, boost::is_any_of(":"));
454       XBT_DEBUG("Host '%s' wants to unmount a remote disk: %s of %s mounted on %s", host->get_cname(),
455                 tokens[1].c_str(), tokens[2].c_str(), tokens[0].c_str());
456       host->remove_disk(tokens[1]);
457       XBT_DEBUG("Host '%s' now has %zu disks", host->get_cname(), host->get_disks().size());
458     }
459   }
460 }
461
462 /* **************************** Public interface *************************** */
463 /** @brief Initialize the file system plugin.
464     @ingroup plugin_filesystem
465
466     @beginrst
467     See the examples in :ref:`s4u_ex_disk_io`.
468     @endrst
469  */
470 void sg_storage_file_system_init()
471 {
472   sg_storage_max_file_descriptors = 1024;
473   simgrid::config::bind_flag(sg_storage_max_file_descriptors, "storage/max_file_descriptors",
474                              "Maximum number of concurrently opened files per host. Default is 1024");
475
476   if (not FileSystemDiskExt::EXTENSION_ID.valid()) {
477     FileSystemDiskExt::EXTENSION_ID = simgrid::s4u::Disk::extension_create<FileSystemDiskExt>();
478     simgrid::s4u::Disk::on_creation_cb(&on_disk_creation);
479   }
480
481   if (not FileDescriptorHostExt::EXTENSION_ID.valid()) {
482     FileDescriptorHostExt::EXTENSION_ID = simgrid::s4u::Host::extension_create<FileDescriptorHostExt>();
483     simgrid::s4u::Host::on_creation_cb(&on_host_creation);
484   }
485   simgrid::s4u::Engine::on_platform_created_cb(&on_platform_created);
486   simgrid::s4u::Engine::on_simulation_end_cb(&on_simulation_end);
487 }
488
489 sg_file_t sg_file_open(const char* fullpath, void* data)
490 {
491   return simgrid::s4u::File::open(fullpath, data);
492 }
493
494 sg_size_t sg_file_read(sg_file_t fd, sg_size_t size)
495 {
496   return fd->read(size);
497 }
498
499 sg_size_t sg_file_write(sg_file_t fd, sg_size_t size)
500 {
501   return fd->write(size);
502 }
503
504 void sg_file_close(sg_file_t fd)
505 {
506   fd->close();
507 }
508
509 /** Retrieves the path to the file
510  * @ingroup plugin_filesystem
511  */
512 const char* sg_file_get_name(const_sg_file_t fd)
513 {
514   xbt_assert((fd != nullptr), "Invalid file descriptor");
515   return fd->get_path();
516 }
517
518 /** Retrieves the size of the file
519  * @ingroup plugin_filesystem
520  */
521 sg_size_t sg_file_get_size(const_sg_file_t fd)
522 {
523   return fd->size();
524 }
525
526 void sg_file_dump(const_sg_file_t fd)
527 {
528   fd->dump();
529 }
530
531 /** Retrieves the user data associated with the file
532  * @ingroup plugin_filesystem
533  */
534 void* sg_file_get_data(const_sg_file_t fd)
535 {
536   return fd->get_data<void>();
537 }
538
539 /** Changes the user data associated with the file
540  * @ingroup plugin_filesystem
541  */
542 void sg_file_set_data(sg_file_t fd, void* data)
543 {
544   fd->set_data(data);
545 }
546
547 /**
548  * @brief Set the file position indicator in the sg_file_t by adding offset bytes to the position specified by origin (either SEEK_SET, SEEK_CUR, or SEEK_END).
549  * @ingroup plugin_filesystem
550  *
551  * @param fd : file object that identifies the stream
552  * @param offset : number of bytes to offset from origin
553  * @param origin : Position used as reference for the offset. It is specified by one of the following constants defined
554  *                 in \<stdio.h\> exclusively to be used as arguments for this function (SEEK_SET = beginning of file,
555  *                 SEEK_CUR = current position of the file pointer, SEEK_END = end of file)
556  */
557 void sg_file_seek(sg_file_t fd, sg_offset_t offset, int origin)
558 {
559   fd->seek(offset, origin);
560 }
561
562 sg_size_t sg_file_tell(const_sg_file_t fd)
563 {
564   return fd->tell();
565 }
566
567 void sg_file_move(const_sg_file_t fd, const char* fullpath)
568 {
569   fd->move(fullpath);
570 }
571
572 void sg_file_unlink(sg_file_t fd)
573 {
574   fd->unlink();
575   fd->close();
576 }
577
578 /**
579  * @brief Copy a file to another location on a remote host.
580  * @ingroup plugin_filesystem
581  *
582  * @param file : the file to move
583  * @param host : the remote host where the file has to be copied
584  * @param fullpath : the complete path destination on the remote host
585  * @return If successful, the function returns 0. Otherwise, it returns -1.
586  */
587 int sg_file_rcopy(sg_file_t file, sg_host_t host, const char* fullpath)
588 {
589   return file->remote_copy(host, fullpath);
590 }
591
592 /**
593  * @brief Move a file to another location on a remote host.
594  * @ingroup plugin_filesystem
595  *
596  * @param file : the file to move
597  * @param host : the remote host where the file has to be moved
598  * @param fullpath : the complete path destination on the remote host
599  * @return If successful, the function returns 0. Otherwise, it returns -1.
600  */
601 int sg_file_rmove(sg_file_t file, sg_host_t host, const char* fullpath)
602 {
603   return file->remote_move(host, fullpath);
604 }
605
606 sg_size_t sg_disk_get_size_free(const_sg_disk_t d)
607 {
608   return d->extension<FileSystemDiskExt>()->get_size() - d->extension<FileSystemDiskExt>()->get_used_size();
609 }
610
611 sg_size_t sg_disk_get_size_used(const_sg_disk_t d)
612 {
613   return d->extension<FileSystemDiskExt>()->get_used_size();
614 }
615
616 sg_size_t sg_disk_get_size(const_sg_disk_t d)
617 {
618   return d->extension<FileSystemDiskExt>()->get_size();
619 }
620
621 const char* sg_disk_get_mount_point(const_sg_disk_t d)
622 {
623   return d->extension<FileSystemDiskExt>()->get_mount_point();
624 }