Logo AND Algorithmique Numérique Distribuée

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