Merge branch 'master' into windows
[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/types.h>
22 #include <sys/stat.h>
23 #include <fcntl.h>
24 #include <cassert>
25 #include <cstdio>
26
27 #ifdef __APPLE__
28 #include <mach/mach_time.h>
29 #endif
30
31 #include "pbd/compose.h"
32 #include "pbd/file_manager.h"
33 #include "pbd/resource.h"
34 #include "pbd/debug.h"
35
36 using namespace std;
37 using namespace PBD;
38
39 FileManager* FileDescriptor::_manager;
40
41 FileManager::FileManager ()
42         : _open (0)
43 {
44         struct ResourceLimit rl;
45         
46         /* XXX: this is a bit arbitrary */
47         if (get_resource_limit (OpenFiles, rl)) {
48                 _max_open = rl.current_limit - 64;
49         } else {
50                 _max_open = 256;
51         }
52
53         DEBUG_TRACE (DEBUG::FileManager, string_compose ("FileManager can open up to %1 files.\n", _max_open));
54 }
55
56 void
57 FileManager::add (FileDescriptor* d)
58 {
59         Glib::Threads::Mutex::Lock lm (_mutex);
60         _files.push_back (d);
61 }
62
63 /** @return true on error, otherwise false */
64 bool
65 FileManager::allocate (FileDescriptor* d)
66 {
67         Glib::Threads::Mutex::Lock lm (_mutex);
68
69         if (!d->is_open()) {
70                 
71                 /* this file needs to be opened */
72                 
73                 if (_open == _max_open) {
74
75                         /* We already have the maximum allowed number of files opened, so we must try to close one.
76                            Find the unallocated, open file with the lowest last_used time.
77                         */
78
79                         double lowest_last_used = DBL_MAX;
80                         list<FileDescriptor*>::iterator oldest = _files.end ();
81
82                         for (list<FileDescriptor*>::iterator i = _files.begin(); i != _files.end(); ++i) {
83                                 if ((*i)->is_open() && (*i)->_refcount == 0) {
84                                         if ((*i)->_last_used < lowest_last_used) {
85                                                 lowest_last_used = (*i)->_last_used;
86                                                 oldest = i;
87                                         }
88                                 }
89                         }
90
91                         if (oldest == _files.end()) {
92                                 /* no unallocated and open files exist, so there's nothing we can do */
93                                 return true;
94                         }
95
96                         close (*oldest);
97                         DEBUG_TRACE (
98                                 DEBUG::FileManager,
99                                 string_compose (
100                                         "closed file for %1 to release file handle; now have %2 of %3 open\n",
101                                         (*oldest)->_path, _open, _max_open
102                                         )
103                                 );
104                 }
105
106                 if (d->open ()) {
107                         DEBUG_TRACE (DEBUG::FileManager, string_compose ("open of %1 failed.\n", d->_path));
108                         return true;
109                 }
110
111                 _open++;
112
113                 DEBUG_TRACE (DEBUG::FileManager, string_compose ("opened file for %1; now have %2 of %3 open.\n", d->_path, _open, _max_open));
114         }
115
116 #ifdef __APPLE__
117         d->_last_used = mach_absolute_time();
118 #elif defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK)
119         struct timespec t;
120         clock_gettime (CLOCK_MONOTONIC, &t);
121         d->_last_used = t.tv_sec + (double) t.tv_nsec / 10e9;
122 #else
123         struct timeval now;
124         gettimeofday (&now, NULL);
125         d->_last_used = now.tv_sec + (double) now.tv_usec / 10e6;
126 #endif
127
128         d->_refcount++;
129         
130         return false;
131 }
132
133 /** Tell FileManager that a FileDescriptor is no longer needed for a given handle */
134 void
135 FileManager::release (FileDescriptor* d)
136 {
137         Glib::Threads::Mutex::Lock lm (_mutex);
138
139         d->_refcount--;
140         assert (d->_refcount >= 0);
141 }
142
143 /** Remove a file from our lists.  It will be closed if it is currently open. */
144 void
145 FileManager::remove (FileDescriptor* d)
146 {
147         Glib::Threads::Mutex::Lock lm (_mutex);
148
149         if (d->is_open ()) {
150                 close (d);
151                 DEBUG_TRACE (
152                         DEBUG::FileManager,
153                         string_compose ("closed file for %1; file is being removed; now have %2 of %3 open\n", d->_path, _open, _max_open)
154                         );
155         }
156
157         _files.remove (d);
158 }
159
160 void
161 FileManager::close (FileDescriptor* d)
162 {
163         /* we must have a lock on our mutex */
164
165         d->close ();
166         d->Closed (); /* EMIT SIGNAL */
167         _open--;
168 }
169
170 FileDescriptor::FileDescriptor (string const & n, bool w)
171         : _refcount (0)
172         , _last_used (0)
173         , _path (n)
174         , _writeable (w)
175 {
176
177 }
178
179 FileManager*
180 FileDescriptor::manager ()
181 {
182         if (_manager == 0) {
183                 _manager = new FileManager;
184         }
185
186         return _manager;
187 }
188
189 /** Release a previously allocated handle to this file */
190 void
191 FileDescriptor::release ()
192 {
193         manager()->release (this);
194 }
195
196
197
198 /** @param file_name Filename.
199  *  @param writeable true to open writeable, otherwise false.
200  *  @param mode Open mode for the file.
201  */
202
203 FdFileDescriptor::FdFileDescriptor (string const & file_name, bool writeable, mode_t mode)
204         : FileDescriptor (file_name, writeable)
205         , _fd (-1)
206         , _mode (mode)
207 {
208         manager()->add (this);
209 }
210
211 FdFileDescriptor::~FdFileDescriptor ()
212 {
213         manager()->remove (this);
214 }
215
216 bool
217 FdFileDescriptor::is_open () const
218 {
219         /* we must have a lock on the FileManager's mutex */
220
221         return _fd != -1;
222 }
223
224 bool
225 FdFileDescriptor::open ()
226 {
227         /* we must have a lock on the FileManager's mutex */
228         
229         _fd = ::open (_path.c_str(), _writeable ? (O_RDWR | O_CREAT) : O_RDONLY, _mode);
230         return (_fd == -1);
231 }
232
233 void
234 FdFileDescriptor::close ()
235 {
236         /* we must have a lock on the FileManager's mutex */
237
238         ::close (_fd);
239         _fd = -1;
240 }
241
242 /** @return fd, or -1 on error */
243 int
244 FdFileDescriptor::allocate ()
245 {
246         bool const f = manager()->allocate (this);
247         if (f) {
248                 return -1;
249         }
250
251         /* this is ok thread-wise because allocate () has incremented
252            the Descriptor's refcount, so the file will not be closed
253         */
254         return _fd;
255 }
256
257
258 void
259 FileDescriptor::set_path (const string& p)
260 {
261         _path = p;
262 }
263
264 /** @param file_name Filename.
265  *  @param mode Mode to pass to fopen.
266  */
267
268 StdioFileDescriptor::StdioFileDescriptor (string const & file_name, std::string const & mode)
269         : FileDescriptor (file_name, false)
270         , _file (0)
271         , _mode (mode)
272 {
273         manager()->add (this);
274 }
275
276 StdioFileDescriptor::~StdioFileDescriptor ()
277 {
278         manager()->remove (this);
279 }
280
281 bool
282 StdioFileDescriptor::is_open () const
283 {
284         /* we must have a lock on the FileManager's mutex */
285
286         return _file != 0;
287 }
288
289 bool
290 StdioFileDescriptor::open ()
291 {
292         /* we must have a lock on the FileManager's mutex */
293         
294         _file = fopen (_path.c_str(), _mode.c_str());
295         return (_file == 0);
296 }
297
298 void
299 StdioFileDescriptor::close ()
300 {
301         /* we must have a lock on the FileManager's mutex */
302
303         fclose (_file);
304         _file = 0;
305 }
306
307 /** @return FILE*, or 0 on error */
308 FILE*
309 StdioFileDescriptor::allocate ()
310 {
311         bool const f = manager()->allocate (this);
312         if (f) {
313                 return 0;
314         }
315
316         /* this is ok thread-wise because allocate () has incremented
317            the Descriptor's refcount, so the file will not be closed
318         */
319         return _file;
320 }