Move FileManager code into libpbd. Use it for SMF read/write.
[ardour.git] / libs / pbd / file_manager.cc
1 /*
2     Copyright (C) 2010 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <sys/time.h>
21 #include <sys/resource.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <fcntl.h>
25 #include <cassert>
26 #include <iostream>
27 #include "pbd/compose.h"
28 #include "pbd/file_manager.h"
29 #include "pbd/debug.h"
30
31 using namespace std;
32 using namespace PBD;
33
34 FileManager* FileDescriptor::_manager;
35
36 namespace PBD {
37
38 /** Class to limit the number of files held open */
39 class FileManager
40 {
41 public:
42         FileManager ();
43         
44         void add (FileDescriptor *);
45         void remove (FileDescriptor *);
46
47         void release (FileDescriptor *);
48         bool allocate (FileDescriptor *);
49
50 private:
51         
52         void close (FileDescriptor *);
53
54         std::list<FileDescriptor*> _files; ///< files we know about
55         Glib::Mutex _mutex; ///< mutex for _files, _open and FileDescriptor contents
56         int _open; ///< number of open files
57         int _max_open; ///< maximum number of open files
58 };
59
60 }
61
62 FileManager::FileManager ()
63         : _open (0)
64 {
65         struct rlimit rl;
66         int const r = getrlimit (RLIMIT_NOFILE, &rl);
67         
68         /* XXX: this is a bit arbitrary */
69         if (r == 0) {
70                 _max_open = rl.rlim_cur - 64;
71         } else {
72                 _max_open = 256;
73         }
74
75         DEBUG_TRACE (DEBUG::FileManager, string_compose ("FileManager can open up to %1 files.\n", _max_open));
76 }
77
78 void
79 FileManager::add (FileDescriptor* d)
80 {
81         Glib::Mutex::Lock lm (_mutex);
82         _files.push_back (d);
83 }
84
85 /** @return true on error, otherwise false */
86 bool
87 FileManager::allocate (FileDescriptor* d)
88 {
89         Glib::Mutex::Lock lm (_mutex);
90
91         if (!d->is_open()) {
92                 
93                 /* this file needs to be opened */
94                 
95                 if (_open == _max_open) {
96
97                         /* We already have the maximum allowed number of files opened, so we must try to close one.
98                            Find the unallocated, open file with the lowest last_used time.
99                         */
100
101                         double lowest_last_used = DBL_MAX;
102                         list<FileDescriptor*>::iterator oldest = _files.end ();
103
104                         for (list<FileDescriptor*>::iterator i = _files.begin(); i != _files.end(); ++i) {
105                                 if ((*i)->is_open() && (*i)->_refcount == 0) {
106                                         if ((*i)->_last_used < lowest_last_used) {
107                                                 lowest_last_used = (*i)->_last_used;
108                                                 oldest = i;
109                                         }
110                                 }
111                         }
112
113                         if (oldest == _files.end()) {
114                                 /* no unallocated and open files exist, so there's nothing we can do */
115                                 return true;
116                         }
117
118                         close (*oldest);
119                         DEBUG_TRACE (
120                                 DEBUG::FileManager,
121                                 string_compose (
122                                         "closed file for %1 to release file handle; now have %2 of %3 open\n",
123                                         (*oldest)->_name, _open, _max_open
124                                         )
125                                 );
126                 }
127
128                 if (d->open ()) {
129                         DEBUG_TRACE (DEBUG::FileManager, string_compose ("open of %1 failed.\n", d->_name));
130                         return true;
131                 }
132
133                 _open++;
134
135                 DEBUG_TRACE (DEBUG::FileManager, string_compose ("opened file for %1; now have %2 of %3 open.\n", d->_name, _open, _max_open));
136         }
137
138         struct timespec t;
139         clock_gettime (CLOCK_MONOTONIC, &t);
140         d->_last_used = t.tv_sec + (double) t.tv_nsec / 10e9;
141
142         d->_refcount++;
143         
144         return false;
145 }
146
147 /** Tell FileManager that a FileDescriptor is no longer needed for a given handle */
148 void
149 FileManager::release (FileDescriptor* d)
150 {
151         Glib::Mutex::Lock lm (_mutex);
152
153         d->_refcount--;
154         assert (d->_refcount >= 0);
155 }
156
157 /** Remove a file from our lists.  It will be closed if it is currently open. */
158 void
159 FileManager::remove (FileDescriptor* d)
160 {
161         Glib::Mutex::Lock lm (_mutex);
162
163         if (d->is_open ()) {
164                 close (d);
165                 DEBUG_TRACE (
166                         DEBUG::FileManager,
167                         string_compose ("closed file for %1; file is being removed; now have %2 of %3 open\n", d->_name, _open, _max_open)
168                         );
169         }
170
171         _files.remove (d);
172 }
173
174 void
175 FileManager::close (FileDescriptor* d)
176 {
177         /* we must have a lock on our mutex */
178
179         d->close ();
180         d->Closed (); /* EMIT SIGNAL */
181         _open--;
182 }
183
184 FileDescriptor::FileDescriptor (string const & n, bool w)
185         : _refcount (0)
186         , _last_used (0)
187         , _name (n)
188         , _writeable (w)
189 {
190
191 }
192
193 FileManager*
194 FileDescriptor::manager ()
195 {
196         if (_manager == 0) {
197                 _manager = new FileManager;
198         }
199
200         return _manager;
201 }
202
203 /** Release a previously allocated handle to this file */
204 void
205 FileDescriptor::release ()
206 {
207         manager()->release (this);
208 }
209
210 /** @param n Filename.
211  *  @param w true to open writeable, otherwise false.
212  *  @param i SF_INFO for the file.
213  */
214
215 SndFileDescriptor::SndFileDescriptor (string const & n, bool w, SF_INFO* i)
216         : FileDescriptor (n, w)
217         , _sndfile (0)
218         , _info (i)
219 {
220         manager()->add (this);
221 }
222
223 SndFileDescriptor::~SndFileDescriptor ()
224 {
225         manager()->remove (this);
226 }
227
228 /** @return SNDFILE*, or 0 on error */
229 SNDFILE*
230 SndFileDescriptor::allocate ()
231 {
232         bool const f = manager()->allocate (this);
233         if (f) {
234                 return 0;
235         }
236
237         /* this is ok thread-wise because allocate () has incremented
238            the Descriptor's refcount, so the file will not be closed
239         */
240         return _sndfile;
241 }
242
243 void
244 SndFileDescriptor::close ()
245 {
246         /* we must have a lock on the FileManager's mutex */
247
248         sf_close (_sndfile);
249         _sndfile = 0;
250 }
251
252 bool
253 SndFileDescriptor::is_open () const
254 {
255         /* we must have a lock on the FileManager's mutex */
256
257         return _sndfile != 0;
258 }
259
260 bool
261 SndFileDescriptor::open ()
262 {
263         /* we must have a lock on the FileManager's mutex */
264         
265         _sndfile = sf_open (_name.c_str(), _writeable ? SFM_RDWR : SFM_READ, _info);
266         return (_sndfile == 0);
267 }
268
269
270 /** @param n Filename.
271  *  @param w true to open writeable, otherwise false.
272  *  @param m Open mode for the file.
273  */
274
275 FdFileDescriptor::FdFileDescriptor (string const & n, bool w, mode_t m)
276         : FileDescriptor (n, w)
277         , _fd (-1)
278         , _mode (m)
279 {
280         manager()->add (this);
281 }
282
283 FdFileDescriptor::~FdFileDescriptor ()
284 {
285         manager()->remove (this);
286 }
287
288 bool
289 FdFileDescriptor::is_open () const
290 {
291         /* we must have a lock on the FileManager's mutex */
292
293         return _fd != -1;
294 }
295
296 bool
297 FdFileDescriptor::open ()
298 {
299         /* we must have a lock on the FileManager's mutex */
300         
301         _fd = ::open (_name.c_str(), _writeable ? (O_RDWR | O_CREAT) : O_RDONLY, _mode);
302         return (_fd == -1);
303 }
304
305 void
306 FdFileDescriptor::close ()
307 {
308         /* we must have a lock on the FileManager's mutex */
309
310         ::close (_fd);
311         _fd = -1;
312 }
313
314 /** @return fd, or -1 on error */
315 int
316 FdFileDescriptor::allocate ()
317 {
318         bool const f = manager()->allocate (this);
319         if (f) {
320                 return -1;
321         }
322
323         /* this is ok thread-wise because allocate () has incremented
324            the Descriptor's refcount, so the file will not be closed
325         */
326         return _fd;
327 }
328
329
330 /** @param n Filename.
331  *  @param w true to open writeable, otherwise false.
332  */
333
334 StdioFileDescriptor::StdioFileDescriptor (string const & n, std::string const & m)
335         : FileDescriptor (n, false)
336         , _file (0)
337         , _mode (m)
338 {
339         manager()->add (this);
340 }
341
342 StdioFileDescriptor::~StdioFileDescriptor ()
343 {
344         manager()->remove (this);
345 }
346
347 bool
348 StdioFileDescriptor::is_open () const
349 {
350         /* we must have a lock on the FileManager's mutex */
351
352         return _file != 0;
353 }
354
355 bool
356 StdioFileDescriptor::open ()
357 {
358         /* we must have a lock on the FileManager's mutex */
359         
360         _file = fopen (_name.c_str(), _mode.c_str());
361         return (_file == 0);
362 }
363
364 void
365 StdioFileDescriptor::close ()
366 {
367         /* we must have a lock on the FileManager's mutex */
368
369         fclose (_file);
370         _file = 0;
371 }
372
373 /** @return FILE*, or 0 on error */
374 FILE*
375 StdioFileDescriptor::allocate ()
376 {
377         bool const f = manager()->allocate (this);
378         if (f) {
379                 return 0;
380         }
381
382         /* this is ok thread-wise because allocate () has incremented
383            the Descriptor's refcount, so the file will not be closed
384         */
385         return _file;
386 }