~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/trace.py

updated log file creation to avoid race based on implementation by Martin [gz]
https://code.launchpad.net/~parthm/bzr/no-chown-if-bzrlog-exists/+merge/22197

Show diffs side-by-side

added added

removed removed

Lines of Context:
238
238
    This sets the global _bzr_log_filename.
239
239
    """
240
240
    global _bzr_log_filename
 
241
 
 
242
    def create_log_file(filename):
 
243
        """Create a log file in while avoiding race.
 
244
        """
 
245
        buffering = 0 # unbuffered
 
246
        mode = os.O_WRONLY | os.O_APPEND | osutils.O_TEXT
 
247
        try:
 
248
            fd = os.open(filename, mode)
 
249
            logfile = os.fdopen(fd, 'at', buffering)
 
250
            return logfile
 
251
        except OSError, e:
 
252
            if e.errno != errno.ENOENT:
 
253
                raise
 
254
        try:
 
255
            fd = os.open(filename, mode | os.O_CREAT | os.O_EXCL)
 
256
            logfile = os.fdopen(fd, 'at', buffering)
 
257
        except OSError, e:
 
258
            if e.errno != errno.EEXIST:
 
259
                raise
 
260
        else:
 
261
            # Copy ownership from parent directory
 
262
            osutils.copy_ownership(filename)
 
263
            return logfile
 
264
 
 
265
 
241
266
    _bzr_log_filename = _get_bzr_log_filename()
242
267
    _rollover_trace_maybe(_bzr_log_filename)
243
268
    try:
244
 
        buffering = 0 # unbuffered
245
 
        if os.path.exists(_bzr_log_filename):
246
 
            bzr_log_file = open(_bzr_log_filename, 'at', buffering=buffering)
247
 
        else:
248
 
            # create log file with ownership of containing directory
249
 
            bzr_log_file = osutils.open_with_ownership(_bzr_log_filename,
250
 
                'at', buffering)
251
 
        # bzr_log_file.tell() on windows always return 0 until some writing done
 
269
        bzr_log_file = create_log_file(_bzr_log_filename)
252
270
        bzr_log_file.write('\n')
253
271
        if bzr_log_file.tell() <= 2:
254
272
            bzr_log_file.write("this is a debug log for diagnosing/reporting problems in bzr\n")