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