Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Hopefully fix build on appveyor (mingw).
[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/Host.hpp"
9 #include "simgrid/s4u/Storage.hpp"
10 #include "simgrid/simix.hpp"
11 #include "src/plugins/file_system/FileSystem.hpp"
12 #include "src/surf/HostImpl.hpp"
13
14 #include <algorithm>
15 #include <boost/algorithm/string.hpp>
16 #include <boost/algorithm/string/join.hpp>
17 #include <boost/algorithm/string/split.hpp>
18 #include <fstream>
19 #include <numeric>
20
21 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_file, "S4U files");
22 int sg_storage_max_file_descriptors = 1024;
23
24 namespace simgrid {
25 namespace s4u {
26 simgrid::xbt::Extension<Storage, FileSystemStorageExt> FileSystemStorageExt::EXTENSION_ID;
27 simgrid::xbt::Extension<Host, FileDescriptorHostExt> FileDescriptorHostExt::EXTENSION_ID;
28
29 File::File(std::string fullpath, void* userdata) : File(fullpath, Host::current(), userdata){};
30
31 File::File(std::string fullpath, sg_host_t host, void* userdata) : fullpath_(fullpath), userdata_(userdata)
32 {
33   // this cannot fail because we get a xbt_die if the mountpoint does not exist
34   Storage* st                  = nullptr;
35   size_t longest_prefix_length = 0;
36   XBT_DEBUG("Search for storage name for '%s' on '%s'", fullpath.c_str(), host->getCname());
37
38   for (auto const& mnt : host->getMountedStorages()) {
39     XBT_DEBUG("See '%s'", mnt.first.c_str());
40     mount_point_ = fullpath.substr(0, mnt.first.length());
41
42     if (mount_point_ == mnt.first && mnt.first.length() > longest_prefix_length) {
43       /* The current mount name is found in the full path and is bigger than the previous*/
44       longest_prefix_length = mnt.first.length();
45       st                    = mnt.second;
46     }
47   }
48   if (longest_prefix_length > 0) { /* Mount point found, split fullpath into mount_name and path+filename*/
49     mount_point_ = fullpath.substr(0, longest_prefix_length);
50     path_        = fullpath.substr(longest_prefix_length, fullpath.length());
51   } else
52     xbt_die("Can't find mount point for '%s' on '%s'", fullpath.c_str(), host->getCname());
53
54   localStorage = st;
55
56   // assign a file descriptor id to the newly opened File
57   FileDescriptorHostExt* ext = host->extension<simgrid::s4u::FileDescriptorHostExt>();
58   if (ext->file_descriptor_table == nullptr) {
59     ext->file_descriptor_table = new std::vector<int>(sg_storage_max_file_descriptors);
60     std::iota(ext->file_descriptor_table->rbegin(), ext->file_descriptor_table->rend(), 0); // Fill with ..., 1, 0.
61   }
62   xbt_assert(not ext->file_descriptor_table->empty(), "Too much files are opened! Some have to be closed.");
63   desc_id = ext->file_descriptor_table->back();
64   ext->file_descriptor_table->pop_back();
65
66   XBT_DEBUG("\tOpen file '%s'", path_.c_str());
67   std::map<std::string, sg_size_t>* content = localStorage->extension<FileSystemStorageExt>()->getContent();
68   // if file does not exist create an empty file
69   auto sz = content->find(path_);
70   if (sz != content->end()) {
71     size_ = sz->second;
72   } else {
73     size_ = 0;
74     content->insert({path_, size_});
75     XBT_DEBUG("File '%s' was not found, file created.", path_.c_str());
76   }
77 }
78
79 File::~File()
80 {
81   Host::current()->extension<simgrid::s4u::FileDescriptorHostExt>()->file_descriptor_table->push_back(desc_id);
82 }
83
84 void File::dump()
85 {
86   XBT_INFO("File Descriptor information:\n"
87            "\t\tFull path: '%s'\n"
88            "\t\tSize: %llu\n"
89            "\t\tMount point: '%s'\n"
90            "\t\tStorage Id: '%s'\n"
91            "\t\tStorage Type: '%s'\n"
92            "\t\tFile Descriptor Id: %d",
93            getPath(), size_, mount_point_.c_str(), localStorage->getCname(), localStorage->getType(), desc_id);
94 }
95
96 sg_size_t File::read(sg_size_t size)
97 {
98   XBT_DEBUG("READ %s on disk '%s'", getPath(), localStorage->getCname());
99   // if the current position is close to the end of the file, we may not be able to read the requested size
100   sg_size_t read_size = localStorage->read(std::min(size, size_ - current_position_));
101   current_position_ += read_size;
102   return read_size;
103 }
104
105 sg_size_t File::write(sg_size_t size)
106 {
107   XBT_DEBUG("WRITE %s on disk '%s'. size '%llu/%llu'", getPath(), localStorage->getCname(), size, size_);
108   // If the storage is full before even starting to write
109   if (sg_storage_get_size_used(localStorage) >= sg_storage_get_size(localStorage))
110     return 0;
111   /* Substract the part of the file that might disappear from the used sized on the storage element */
112   localStorage->extension<FileSystemStorageExt>()->decrUsedSize(size_ - current_position_);
113
114   sg_size_t write_size = localStorage->write(size);
115   localStorage->extension<FileSystemStorageExt>()->incrUsedSize(write_size);
116
117   current_position_ += write_size;
118   size_ = current_position_;
119   std::map<std::string, sg_size_t>* content = localStorage->extension<FileSystemStorageExt>()->getContent();
120
121   content->erase(path_);
122   content->insert({path_, size_});
123
124   return write_size;
125 }
126
127 sg_size_t File::size()
128 {
129   return size_;
130 }
131
132 void File::seek(sg_offset_t offset)
133 {
134   current_position_ = offset;
135 }
136
137 void File::seek(sg_offset_t offset, int origin)
138 {
139   switch (origin) {
140     case SEEK_SET:
141       current_position_ = offset;
142       break;
143     case SEEK_CUR:
144       current_position_ += offset;
145       break;
146     case SEEK_END:
147       current_position_ = size_ + offset;
148       break;
149     default:
150       break;
151   }
152 }
153
154 sg_size_t File::tell()
155 {
156   return current_position_;
157 }
158
159 void File::move(std::string fullpath)
160 {
161   /* Check if the new full path is on the same mount point */
162   if (not strncmp(mount_point_.c_str(), fullpath.c_str(), mount_point_.length())) {
163     std::map<std::string, sg_size_t>* content = localStorage->extension<FileSystemStorageExt>()->getContent();
164     auto sz = content->find(path_);
165     if (sz != content->end()) { // src file exists
166       sg_size_t new_size = sz->second;
167       content->erase(path_);
168       std::string path = fullpath.substr(mount_point_.length(), fullpath.length());
169       content->insert({path.c_str(), new_size});
170       XBT_DEBUG("Move file from %s to %s, size '%llu'", path_.c_str(), fullpath.c_str(), new_size);
171     } else {
172       XBT_WARN("File %s doesn't exist", path_.c_str());
173     }
174   } else {
175     XBT_WARN("New full path %s is not on the same mount point: %s.", fullpath.c_str(), mount_point_.c_str());
176   }
177 }
178
179 int File::unlink()
180 {
181   /* Check if the file is on local storage */
182   std::map<std::string, sg_size_t>* content = localStorage->extension<FileSystemStorageExt>()->getContent();
183
184   if (content->find(path_) == content->end()) {
185     XBT_WARN("File %s is not on disk %s. Impossible to unlink", path_.c_str(), localStorage->getCname());
186     return -1;
187   } else {
188     XBT_DEBUG("UNLINK %s on disk '%s'", path_.c_str(), localStorage->getCname());
189     localStorage->extension<FileSystemStorageExt>()->decrUsedSize(size_);
190
191     // Remove the file from storage
192     content->erase(fullpath_);
193
194     return 0;
195   }
196 }
197
198 FileSystemStorageExt::FileSystemStorageExt(simgrid::s4u::Storage* ptr)
199 {
200   content_ = parseContent(ptr->getImpl()->content_name);
201   size_    = ptr->getImpl()->size_;
202 }
203
204 FileSystemStorageExt::~FileSystemStorageExt()
205 {
206   delete content_;
207 }
208
209 std::map<std::string, sg_size_t>* FileSystemStorageExt::parseContent(std::string filename)
210 {
211   if (filename.empty())
212     return nullptr;
213
214   std::map<std::string, sg_size_t>* parse_content = new std::map<std::string, sg_size_t>();
215
216   std::ifstream* fs = surf_ifsopen(filename);
217
218   std::string line;
219   std::vector<std::string> tokens;
220   do {
221     std::getline(*fs, line);
222     boost::trim(line);
223     if (line.length() > 0) {
224       boost::split(tokens, line, boost::is_any_of(" \t"), boost::token_compress_on);
225       xbt_assert(tokens.size() == 2, "Parse error in %s: %s", filename.c_str(), line.c_str());
226       sg_size_t size = std::stoull(tokens.at(1));
227
228       usedSize_ += size;
229       parse_content->insert({tokens.front(), size});
230     }
231   } while (not fs->eof());
232   delete fs;
233   return parse_content;
234 }
235 }
236 }
237
238 using simgrid::s4u::FileSystemStorageExt;
239 using simgrid::s4u::FileDescriptorHostExt;
240
241 static void onStorageCreation(simgrid::s4u::Storage& st)
242 {
243   st.extension_set(new FileSystemStorageExt(&st));
244 }
245
246 static void onStorageDestruction(simgrid::s4u::Storage& st)
247 {
248   delete st.extension<FileSystemStorageExt>();
249 }
250
251 static void onHostCreation(simgrid::s4u::Host& host)
252 {
253   host.extension_set<FileDescriptorHostExt>(new FileDescriptorHostExt());
254 }
255
256 /* **************************** Public interface *************************** */
257 SG_BEGIN_DECL()
258
259 void sg_storage_file_system_init()
260 {
261   if (not FileSystemStorageExt::EXTENSION_ID.valid()) {
262     FileSystemStorageExt::EXTENSION_ID = simgrid::s4u::Storage::extension_create<FileSystemStorageExt>();
263     simgrid::s4u::Storage::onCreation.connect(&onStorageCreation);
264     simgrid::s4u::Storage::onDestruction.connect(&onStorageDestruction);
265   }
266
267   if (not FileDescriptorHostExt::EXTENSION_ID.valid()) {
268     FileDescriptorHostExt::EXTENSION_ID = simgrid::s4u::Host::extension_create<FileDescriptorHostExt>();
269     simgrid::s4u::Host::onCreation.connect(&onHostCreation);
270   }
271 }
272
273 sg_file_t sg_file_open(const char* fullpath, void* data)
274 {
275   return new simgrid::s4u::File(fullpath, data);
276 }
277
278 void sg_file_close(sg_file_t fd)
279 {
280   delete fd;
281 }
282
283 const char* sg_file_get_name(sg_file_t fd)
284 {
285   xbt_assert((fd != nullptr), "Invalid file descriptor");
286   return fd->getPath();
287 }
288
289 sg_size_t sg_file_get_size(sg_file_t fd)
290 {
291   return fd->size();
292 }
293
294 void sg_file_dump(sg_file_t fd)
295 {
296   fd->dump();
297 }
298
299 void* sg_file_get_data(sg_file_t fd)
300 {
301   return fd->getUserdata();
302 }
303
304 void sg_file_set_data(sg_file_t fd, void* data)
305 {
306   fd->setUserdata(data);
307 }
308
309 /**
310  * \brief Set the file position indicator in the msg_file_t by adding offset bytes
311  * to the position specified by origin (either SEEK_SET, SEEK_CUR, or SEEK_END).
312  *
313  * \param fd : file object that identifies the stream
314  * \param offset : number of bytes to offset from origin
315  * \param origin : Position used as reference for the offset. It is specified by one of the following constants defined
316  *                 in \<stdio.h\> exclusively to be used as arguments for this function (SEEK_SET = beginning of file,
317  *                 SEEK_CUR = current position of the file pointer, SEEK_END = end of file)
318  */
319 void sg_file_seek(sg_file_t fd, sg_offset_t offset, int origin)
320 {
321   fd->seek(offset, origin);
322 }
323
324 sg_size_t sg_file_tell(sg_file_t fd)
325 {
326   return fd->tell();
327 }
328
329 void sg_file_move(sg_file_t fd, const char* fullpath)
330 {
331   fd->move(fullpath);
332 }
333
334 void sg_file_unlink(sg_file_t fd)
335 {
336   fd->unlink();
337   delete fd;
338 }
339
340 sg_size_t sg_storage_get_size_free(sg_storage_t st)
341 {
342   return st->extension<FileSystemStorageExt>()->getSize() - st->extension<FileSystemStorageExt>()->getUsedSize();
343 }
344
345 sg_size_t sg_storage_get_size_used(sg_storage_t st)
346 {
347   return st->extension<FileSystemStorageExt>()->getUsedSize();
348 }
349
350 sg_size_t sg_storage_get_size(sg_storage_t st)
351 {
352   return st->extension<FileSystemStorageExt>()->getSize();
353 }
354
355 xbt_dict_t sg_storage_get_content(sg_storage_t storage)
356 {
357   std::map<std::string, sg_size_t>* content = storage->extension<simgrid::s4u::FileSystemStorageExt>()->getContent();
358   // Note: ::operator delete is ok here (no destructor called) since the dict elements are of POD type sg_size_t.
359   xbt_dict_t content_as_dict = xbt_dict_new_homogeneous(::operator delete);
360
361   for (auto const& entry : *content) {
362     sg_size_t* psize = new sg_size_t;
363     *psize           = entry.second;
364     xbt_dict_set(content_as_dict, entry.first.c_str(), psize, nullptr);
365   }
366   return content_as_dict;
367 }
368
369 xbt_dict_t sg_host_get_storage_content(sg_host_t host)
370 {
371   xbt_assert((host != nullptr), "Invalid parameters");
372   xbt_dict_t contents = xbt_dict_new_homogeneous(nullptr);
373   for (auto const& elm : host->getMountedStorages())
374     xbt_dict_set(contents, elm.first.c_str(), sg_storage_get_content(elm.second), nullptr);
375
376   return contents;
377 }
378
379 SG_END_DECL()