Logo AND Algorithmique Numérique Distribuée

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