Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
0dd328719d4c175e88cf6d8c071f16b4a0203368
[simgrid.git] / src / plugins / file_system / s4u_FileSystem.cpp
1 /* Copyright (c) 2015-2018. 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/Actor.hpp"
8 #include "src/surf/HostImpl.hpp"
9 #include "xbt/config.hpp"
10
11 #include <algorithm>
12 #include <boost/algorithm/string.hpp>
13 #include <boost/algorithm/string/join.hpp>
14 #include <boost/algorithm/string/split.hpp>
15 #include <fstream>
16 #include <numeric>
17
18 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_file, "S4U files");
19 int sg_storage_max_file_descriptors = 1024;
20
21 namespace simgrid {
22 namespace s4u {
23 simgrid::xbt::Extension<Storage, FileSystemStorageExt> FileSystemStorageExt::EXTENSION_ID;
24 simgrid::xbt::Extension<Host, FileDescriptorHostExt> FileDescriptorHostExt::EXTENSION_ID;
25
26 File::File(std::string fullpath, void* userdata) : File(fullpath, Host::current(), userdata){};
27
28 File::File(std::string fullpath, sg_host_t host, void* userdata) : fullpath_(fullpath), userdata_(userdata)
29 {
30   // this cannot fail because we get a xbt_die if the mountpoint does not exist
31   Storage* st                  = nullptr;
32   size_t longest_prefix_length = 0;
33   XBT_DEBUG("Search for storage name for '%s' on '%s'", fullpath.c_str(), host->get_cname());
34
35   for (auto const& mnt : host->getMountedStorages()) {
36     XBT_DEBUG("See '%s'", mnt.first.c_str());
37     mount_point_ = fullpath.substr(0, mnt.first.length());
38
39     if (mount_point_ == mnt.first && mnt.first.length() > longest_prefix_length) {
40       /* The current mount name is found in the full path and is bigger than the previous*/
41       longest_prefix_length = mnt.first.length();
42       st                    = mnt.second;
43     }
44   }
45   if (longest_prefix_length > 0) { /* Mount point found, split fullpath into mount_name and path+filename*/
46     mount_point_ = fullpath.substr(0, longest_prefix_length);
47     path_        = fullpath.substr(longest_prefix_length, fullpath.length());
48   } else
49     xbt_die("Can't find mount point for '%s' on '%s'", fullpath.c_str(), host->get_cname());
50
51   local_storage_ = st;
52
53   // assign a file descriptor id to the newly opened File
54   FileDescriptorHostExt* ext = host->extension<simgrid::s4u::FileDescriptorHostExt>();
55   if (ext->file_descriptor_table == nullptr) {
56     ext->file_descriptor_table = new std::vector<int>(sg_storage_max_file_descriptors);
57     std::iota(ext->file_descriptor_table->rbegin(), ext->file_descriptor_table->rend(), 0); // Fill with ..., 1, 0.
58   }
59   xbt_assert(not ext->file_descriptor_table->empty(), "Too much files are opened! Some have to be closed.");
60   desc_id = ext->file_descriptor_table->back();
61   ext->file_descriptor_table->pop_back();
62
63   XBT_DEBUG("\tOpen file '%s'", path_.c_str());
64   std::map<std::string, sg_size_t>* content = local_storage_->extension<FileSystemStorageExt>()->get_content();
65   // if file does not exist create an empty file
66   auto sz = content->find(path_);
67   if (sz != content->end()) {
68     size_ = sz->second;
69   } else {
70     size_ = 0;
71     content->insert({path_, size_});
72     XBT_DEBUG("File '%s' was not found, file created.", path_.c_str());
73   }
74 }
75
76 File::~File()
77 {
78   Host::current()->extension<simgrid::s4u::FileDescriptorHostExt>()->file_descriptor_table->push_back(desc_id);
79 }
80
81 void File::dump()
82 {
83   XBT_INFO("File Descriptor information:\n"
84            "\t\tFull path: '%s'\n"
85            "\t\tSize: %llu\n"
86            "\t\tMount point: '%s'\n"
87            "\t\tStorage Id: '%s'\n"
88            "\t\tStorage Type: '%s'\n"
89            "\t\tFile Descriptor Id: %d",
90            get_path(), size_, mount_point_.c_str(), local_storage_->get_cname(), local_storage_->get_type(), desc_id);
91 }
92
93 sg_size_t File::read(sg_size_t size)
94 {
95   if (size_ == 0) /* Nothing to read, return */
96     return 0;
97
98   /* Find the host where the file is physically located and read it */
99   Host* host = local_storage_->get_host();
100   XBT_DEBUG("READ %s on disk '%s'", get_path(), local_storage_->get_cname());
101   // if the current position is close to the end of the file, we may not be able to read the requested size
102   sg_size_t read_size = local_storage_->read(std::min(size, size_ - current_position_));
103   current_position_ += read_size;
104
105   if (strcmp(host->get_cname(), Host::current()->get_cname())) {
106     /* the file is hosted on a remote host, initiate a communication between src and dest hosts for data transfer */
107     XBT_DEBUG("File is on %s remote host, initiate data transfer of %llu bytes.", host->get_cname(), read_size);
108     Host* m_host_list[]  = {Host::current(), host};
109     double* flops_amount = new double[2]{0, 0};
110     double* bytes_amount = new double[4]{0, 0, static_cast<double>(read_size), 0};
111
112     this_actor::parallel_execute(2, m_host_list, flops_amount, bytes_amount);
113   }
114
115   return read_size;
116 }
117
118 /** \brief Write into a file (local or remote)
119  *
120  * \param size of the file to write
121  * \param fd is a the file descriptor
122  * \return the number of bytes successfully write or -1 if an error occurred
123  */
124 sg_size_t File::write(sg_size_t size)
125 {
126   if (size == 0) /* Nothing to write, return */
127     return 0;
128
129   /* Find the host where the file is physically located (remote or local)*/
130   Host* host = local_storage_->get_host();
131
132   if (strcmp(host->get_cname(), Host::current()->get_cname())) {
133     /* the file is hosted on a remote host, initiate a communication between src and dest hosts for data transfer */
134     XBT_DEBUG("File is on %s remote host, initiate data transfer of %llu bytes.", host->get_cname(), size);
135     Host* m_host_list[]  = {Host::current(), host};
136     double* flops_amount = new double[2]{0, 0};
137     double* bytes_amount = new double[4]{0, static_cast<double>(size), 0, 0};
138
139     this_actor::parallel_execute(2, m_host_list, flops_amount, bytes_amount);
140   }
141
142   XBT_DEBUG("WRITE %s on disk '%s'. size '%llu/%llu'", get_path(), local_storage_->get_cname(), size, size_);
143   // If the storage is full before even starting to write
144   if (sg_storage_get_size_used(local_storage_) >= sg_storage_get_size(local_storage_))
145     return 0;
146   /* Substract the part of the file that might disappear from the used sized on the storage element */
147   local_storage_->extension<FileSystemStorageExt>()->decr_used_size(size_ - current_position_);
148
149   sg_size_t write_size = local_storage_->write(size);
150   local_storage_->extension<FileSystemStorageExt>()->incr_used_size(write_size);
151
152   current_position_ += write_size;
153   size_ = current_position_;
154   std::map<std::string, sg_size_t>* content = local_storage_->extension<FileSystemStorageExt>()->get_content();
155
156   content->erase(path_);
157   content->insert({path_, size_});
158
159   return write_size;
160 }
161
162 sg_size_t File::size()
163 {
164   return size_;
165 }
166
167 void File::seek(sg_offset_t offset)
168 {
169   current_position_ = offset;
170 }
171
172 void File::seek(sg_offset_t offset, int origin)
173 {
174   switch (origin) {
175     case SEEK_SET:
176       current_position_ = offset;
177       break;
178     case SEEK_CUR:
179       current_position_ += offset;
180       break;
181     case SEEK_END:
182       current_position_ = size_ + offset;
183       break;
184     default:
185       break;
186   }
187 }
188
189 sg_size_t File::tell()
190 {
191   return current_position_;
192 }
193
194 void File::move(std::string fullpath)
195 {
196   /* Check if the new full path is on the same mount point */
197   if (not strncmp(mount_point_.c_str(), fullpath.c_str(), mount_point_.length())) {
198     std::map<std::string, sg_size_t>* content = local_storage_->extension<FileSystemStorageExt>()->get_content();
199     auto sz = content->find(path_);
200     if (sz != content->end()) { // src file exists
201       sg_size_t new_size = sz->second;
202       content->erase(path_);
203       std::string path = fullpath.substr(mount_point_.length(), fullpath.length());
204       content->insert({path.c_str(), new_size});
205       XBT_DEBUG("Move file from %s to %s, size '%llu'", path_.c_str(), fullpath.c_str(), new_size);
206     } else {
207       XBT_WARN("File %s doesn't exist", path_.c_str());
208     }
209   } else {
210     XBT_WARN("New full path %s is not on the same mount point: %s.", fullpath.c_str(), mount_point_.c_str());
211   }
212 }
213
214 int File::unlink()
215 {
216   /* Check if the file is on local storage */
217   std::map<std::string, sg_size_t>* content = local_storage_->extension<FileSystemStorageExt>()->get_content();
218
219   if (content->find(path_) == content->end()) {
220     XBT_WARN("File %s is not on disk %s. Impossible to unlink", path_.c_str(), local_storage_->get_cname());
221     return -1;
222   } else {
223     XBT_DEBUG("UNLINK %s on disk '%s'", path_.c_str(), local_storage_->get_cname());
224     local_storage_->extension<FileSystemStorageExt>()->decr_used_size(size_);
225
226     // Remove the file from storage
227     content->erase(fullpath_);
228
229     return 0;
230   }
231 }
232
233 int File::remote_copy(sg_host_t host, const char* fullpath)
234 {
235   /* Find the host where the file is physically located and read it */
236   Storage* storage_src = local_storage_;
237   Host* src_host       = storage_src->get_host();
238   seek(0, SEEK_SET);
239   XBT_DEBUG("READ %s on disk '%s'", get_path(), local_storage_->get_cname());
240   // if the current position is close to the end of the file, we may not be able to read the requested size
241   sg_size_t read_size = local_storage_->read(size_);
242   current_position_ += read_size;
243
244   /* Find the host that owns the storage where the file has to be copied */
245   Storage* storage_dest = nullptr;
246   Host* dst_host;
247   size_t longest_prefix_length = 0;
248
249   for (auto const& elm : host->getMountedStorages()) {
250     std::string mount_point = std::string(fullpath).substr(0, elm.first.size());
251     if (mount_point == elm.first && elm.first.length() > longest_prefix_length) {
252       /* The current mount name is found in the full path and is bigger than the previous*/
253       longest_prefix_length = elm.first.length();
254       storage_dest          = elm.second;
255     }
256   }
257
258   if (storage_dest != nullptr) {
259     /* Mount point found, retrieve the host the storage is attached to */
260     dst_host = storage_dest->get_host();
261   } else {
262     XBT_WARN("Can't find mount point for '%s' on destination host '%s'", fullpath, host->get_cname());
263     return -1;
264   }
265
266   XBT_DEBUG("Initiate data transfer of %llu bytes between %s and %s.", read_size, src_host->get_cname(),
267             storage_dest->get_host()->get_cname());
268   Host* m_host_list[]     = {src_host, dst_host};
269   double* flops_amount    = new double[2]{0, 0};
270   double* bytes_amount    = new double[4]{0, static_cast<double>(read_size), 0, 0};
271
272   this_actor::parallel_execute(2, m_host_list, flops_amount, bytes_amount);
273
274   /* Create file on remote host, write it and close it */
275   File* fd = new File(fullpath, dst_host, nullptr);
276   sg_size_t write_size = fd->local_storage_->write(read_size);
277   fd->local_storage_->extension<FileSystemStorageExt>()->incr_used_size(write_size);
278   (*(fd->local_storage_->extension<FileSystemStorageExt>()->get_content()))[path_] = size_;
279   delete fd;
280   return 0;
281 }
282
283 int File::remote_move(sg_host_t host, const char* fullpath)
284 {
285   int res = remote_copy(host, fullpath);
286   unlink();
287   return res;
288 }
289
290 FileSystemStorageExt::FileSystemStorageExt(simgrid::s4u::Storage* ptr)
291 {
292   content_ = parse_content(ptr->get_impl()->content_name);
293   size_    = ptr->get_impl()->size_;
294 }
295
296 FileSystemStorageExt::~FileSystemStorageExt()
297 {
298   delete content_;
299 }
300
301 std::map<std::string, sg_size_t>* FileSystemStorageExt::parse_content(std::string filename)
302 {
303   if (filename.empty())
304     return nullptr;
305
306   std::map<std::string, sg_size_t>* parse_content = new std::map<std::string, sg_size_t>();
307
308   std::ifstream* fs = surf_ifsopen(filename);
309
310   std::string line;
311   std::vector<std::string> tokens;
312   do {
313     std::getline(*fs, line);
314     boost::trim(line);
315     if (line.length() > 0) {
316       boost::split(tokens, line, boost::is_any_of(" \t"), boost::token_compress_on);
317       xbt_assert(tokens.size() == 2, "Parse error in %s: %s", filename.c_str(), line.c_str());
318       sg_size_t size = std::stoull(tokens.at(1));
319
320       used_size_ += size;
321       parse_content->insert({tokens.front(), size});
322     }
323   } while (not fs->eof());
324   delete fs;
325   return parse_content;
326 }
327 }
328 }
329
330 using simgrid::s4u::FileSystemStorageExt;
331 using simgrid::s4u::FileDescriptorHostExt;
332
333 static void on_storage_creation(simgrid::s4u::Storage& st)
334 {
335   st.extension_set(new FileSystemStorageExt(&st));
336 }
337
338 static void on_host_creation(simgrid::s4u::Host& host)
339 {
340   host.extension_set<FileDescriptorHostExt>(new FileDescriptorHostExt());
341 }
342
343 /* **************************** Public interface *************************** */
344 void sg_storage_file_system_init()
345 {
346   sg_storage_max_file_descriptors = 1024;
347   simgrid::config::bind_flag(sg_storage_max_file_descriptors, "storage/max_file_descriptors",
348                              "Maximum number of concurrently opened files per host. Default is 1024");
349
350   if (not FileSystemStorageExt::EXTENSION_ID.valid()) {
351     FileSystemStorageExt::EXTENSION_ID = simgrid::s4u::Storage::extension_create<FileSystemStorageExt>();
352     simgrid::s4u::Storage::on_creation.connect(&on_storage_creation);
353   }
354
355   if (not FileDescriptorHostExt::EXTENSION_ID.valid()) {
356     FileDescriptorHostExt::EXTENSION_ID = simgrid::s4u::Host::extension_create<FileDescriptorHostExt>();
357     simgrid::s4u::Host::on_creation.connect(&on_host_creation);
358   }
359 }
360
361 sg_file_t sg_file_open(const char* fullpath, void* data)
362 {
363   return new simgrid::s4u::File(fullpath, data);
364 }
365
366 sg_size_t sg_file_read(sg_file_t fd, sg_size_t size)
367 {
368   return fd->read(size);
369 }
370
371 sg_size_t sg_file_write(sg_file_t fd, sg_size_t size)
372 {
373   return fd->write(size);
374 }
375
376 void sg_file_close(sg_file_t fd)
377 {
378   delete fd;
379 }
380
381 const char* sg_file_get_name(sg_file_t fd)
382 {
383   xbt_assert((fd != nullptr), "Invalid file descriptor");
384   return fd->get_path();
385 }
386
387 sg_size_t sg_file_get_size(sg_file_t fd)
388 {
389   return fd->size();
390 }
391
392 void sg_file_dump(sg_file_t fd)
393 {
394   fd->dump();
395 }
396
397 void* sg_file_get_data(sg_file_t fd)
398 {
399   return fd->get_userdata();
400 }
401
402 void sg_file_set_data(sg_file_t fd, void* data)
403 {
404   fd->set_userdata(data);
405 }
406
407 /**
408  * \brief Set the file position indicator in the sg_file_t by adding offset bytes
409  * to the position specified by origin (either SEEK_SET, SEEK_CUR, or SEEK_END).
410  *
411  * \param fd : file object that identifies the stream
412  * \param offset : number of bytes to offset from origin
413  * \param origin : Position used as reference for the offset. It is specified by one of the following constants defined
414  *                 in \<stdio.h\> exclusively to be used as arguments for this function (SEEK_SET = beginning of file,
415  *                 SEEK_CUR = current position of the file pointer, SEEK_END = end of file)
416  */
417 void sg_file_seek(sg_file_t fd, sg_offset_t offset, int origin)
418 {
419   fd->seek(offset, origin);
420 }
421
422 sg_size_t sg_file_tell(sg_file_t fd)
423 {
424   return fd->tell();
425 }
426
427 void sg_file_move(sg_file_t fd, const char* fullpath)
428 {
429   fd->move(fullpath);
430 }
431
432 void sg_file_unlink(sg_file_t fd)
433 {
434   fd->unlink();
435   delete fd;
436 }
437
438 /**
439  * \brief Copy a file to another location on a remote host.
440  * \param file : the file to move
441  * \param host : the remote host where the file has to be copied
442  * \param fullpath : the complete path destination on the remote host
443  * \return If successful, the function returns 0. Otherwise, it returns -1.
444  */
445 int sg_file_rcopy(sg_file_t file, sg_host_t host, const char* fullpath)
446 {
447   return file->remote_copy(host, fullpath);
448 }
449
450 /**
451  * \brief Move a file to another location on a remote host.
452  * \param file : the file to move
453  * \param host : the remote host where the file has to be moved
454  * \param fullpath : the complete path destination on the remote host
455  * \return If successful, the function returns 0. Otherwise, it returns -1.
456  */
457 int sg_file_rmove(sg_file_t file, sg_host_t host, const char* fullpath)
458 {
459   return file->remote_move(host, fullpath);
460 }
461
462 sg_size_t sg_storage_get_size_free(sg_storage_t st)
463 {
464   return st->extension<FileSystemStorageExt>()->get_size() - st->extension<FileSystemStorageExt>()->get_used_size();
465 }
466
467 sg_size_t sg_storage_get_size_used(sg_storage_t st)
468 {
469   return st->extension<FileSystemStorageExt>()->get_used_size();
470 }
471
472 sg_size_t sg_storage_get_size(sg_storage_t st)
473 {
474   return st->extension<FileSystemStorageExt>()->get_size();
475 }
476
477 xbt_dict_t sg_storage_get_content(sg_storage_t storage)
478 {
479   std::map<std::string, sg_size_t>* content = storage->extension<simgrid::s4u::FileSystemStorageExt>()->get_content();
480   // Note: ::operator delete is ok here (no destructor called) since the dict elements are of POD type sg_size_t.
481   xbt_dict_t content_as_dict = xbt_dict_new_homogeneous(::operator delete);
482
483   for (auto const& entry : *content) {
484     sg_size_t* psize = new sg_size_t;
485     *psize           = entry.second;
486     xbt_dict_set(content_as_dict, entry.first.c_str(), psize, nullptr);
487   }
488   return content_as_dict;
489 }
490
491 xbt_dict_t sg_host_get_storage_content(sg_host_t host)
492 {
493   xbt_assert((host != nullptr), "Invalid parameters");
494   xbt_dict_t contents = xbt_dict_new_homogeneous(nullptr);
495   for (auto const& elm : host->getMountedStorages())
496     xbt_dict_set(contents, elm.first.c_str(), sg_storage_get_content(elm.second), nullptr);
497
498   return contents;
499 }