Commit Graph

188 Commits

Author SHA1 Message Date
Matthias Sohn 838b5a84b5 Store filesystem timestamp resolution in extra jgit config
This avoids polluting hand-crafted user level config with
auto-configured options which might disturb in environments where
the user level config is replicated between different machines.

Add a jgit config as parent of the system level config. Persist
measured timestamp resolutions always in this jgit config and read it
via the user global config. This has the effect that auto-configured
timestamp resolution will be used by default and can be overridden in
either the system level or user level config.

Store the jgit config under the XDG_CONFIG_HOME directory following the
XDG base directory specification [1] in order to ensure that we have
write permissions to persist the file. This has the effect that each OS
user will use its jgit config since they typically use different
XDG_CONFIG_HOME directories.

If the environment variable XDG_CONFIG_HOME is defined the jgit config
file is located at $XDG_CONFIG_HOME/jgit/config otherwise the default is
~/.config/jgit/config.

If you want to avoid redundant measurement for different OS users
manually copy the values measured and auto-configured for one OS user to
the system level git config.

[1] https://wiki.archlinux.org/index.php/XDG_Base_Directory

Bug: 551850
Change-Id: I0022bd40ae62f82e5b964c2ea25822eb55d94687
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-11-09 18:01:19 +01:00
Matthias Sohn 5625f70d25 [errorprone] Don't throw exception in finally
Instead log the problem. There is no reason to panic when we fail to
delete a single temporary file in java.io.tmpdir.

Change-Id: Idb867b3f07b090c7453ccd3688e94097df3b2672
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-10-25 15:27:36 +02:00
Matthias Sohn 6ba8f37ab7 [errorprone] Add parenthesis to clarify operator precedence
This fixes OperatorPrecedence error raised by errorprone on FS#findHook.

Change-Id: Ia15f61902c7deff7328c1afa066fc53152949bbf
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-10-25 15:27:36 +02:00
Thomas Wolf 385b503ae8 Support for core.hooksPath
Support the core.hooksPath git config. This can be an absolute or
relative path of a directory where to find git hooks; a relative
path is resolved relative to the directory the hook will run in.

Bug: 500266
Change-Id: I671999a6386a837e897c31718583c91d8035f3ba
Signed-off-by: Thomas Wolf <thomas.wolf@paranor.ch>
2019-10-21 18:05:31 -04:00
David Pursehouse 98cdca9b5a Enable and fix "Statement unnecessarily nested within else clause" warnings
Since [1] the gerrit project includes jgit as a submodule, and has this
warning enabled, resulting in 100s of warnings in the console.

Also enable the warning here, and fix them.

At the same time, add missing braces around adjacent and nearby one-line
blocks.

[1] https://gerrit-review.googlesource.com/c/gerrit/+/227897

Change-Id: I81df3fc7ed6eedf6874ce1a3bedfa727a1897e4c
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2019-10-17 10:20:14 +09:00
Nail Samatov b9d2926df4 Fix error occurring when SecurityManager is enabled
It's expected that jgit should work without native git installation.
In such case Security Manager can be configured to deny access to the
files outside of git repository. JGit tries to find cygwin
installation. If Security manager restricts access to some folders
in PATH, it should be considered that those folders are absent
for jgit.
Also JGit tries to detect if symbolic links are supported by OS. If
security manager forbids creation of symlinks, it should be assumed
that symlinks aren't supported.

Bug: 550115
Change-Id: Ic4b243cada604bc1090db6cc1cfd74f0fa324b98
Signed-off-by: Nail Samatov <sanail@yandex.ru>
2019-08-23 20:38:26 +03:00
Matthias Sohn 35d99477b8 Merge branch 'stable-5.3' into stable-5.4
* stable-5.3:
  Fix NPE in RebaseTodoFile#parseComments
  Fix NPE in ObjectIdOwnerMap#get
  Fix NPE in CommitOnlyTest#getHead
  FileUtils#lastModifiedInstant should not log error if path doesn't exist
  Cache user global and system-wide git configurations
  Avoid setup and saving FileStoreAttributes compete for ~/.gitconfig lock
  Add missing dependencies for running FS_POSIXTest in Eclipse
  Fix javadoc for SystemReader#getInstance
  Improve retry handling when saving FileStoreAttributes fails
  Ensure FSTest uses MockSystemReader
  Make supportsAtomicCreateNewFile return true as default
  Update orbit to R20190602212107-2019-06 to enable backports from master
  Handle InvalidPathException in FS_POSIX#createNewFileAtomic
  Ensure root cause of lock creation failures is logged
  Implement toString in MockSystemReader and MockConfig
  LocalDiskRefTreeDatabaseTest shall use MockSystemReader
  Ensure LocalDiskRepositoryTestCase#setup fully uses MockSystemReader
  Ensure we use MockSystemReader in tests
  Override FileBasedConfig's save method in MockConfig
  Remove FileBasedConfig.load(boolean) introduced in d45219ba
  Disable debug log for FS in org.eclipse.jgit.test
  Bazel: enable logging for tests in org.eclipse.jgit.test
  LockFile: log exception if creation of lock file failed
  Stop using deprecated Constants.CHARACTER_ENCODING

Change-Id: I43c2ab8b44c3e87d48e4072907ad169c81e3ffe0
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-08-20 00:10:15 +02:00
Matthias Sohn 0eea7368e2 Merge branch 'stable-5.1' into stable-5.2
* stable-5.1:
  Fix NPE in RebaseTodoFile#parseComments
  Fix NPE in ObjectIdOwnerMap#get
  Fix NPE in CommitOnlyTest#getHead
  FileUtils#lastModifiedInstant should not log error if path doesn't exist
  Cache user global and system-wide git configurations
  Avoid setup and saving FileStoreAttributes compete for ~/.gitconfig lock
  Add missing dependencies for running FS_POSIXTest in Eclipse
  Fix javadoc for SystemReader#getInstance
  Improve retry handling when saving FileStoreAttributes fails
  Ensure FSTest uses MockSystemReader
  Make supportsAtomicCreateNewFile return true as default
  Update orbit to R20190602212107-2019-06 to enable backports from master
  Handle InvalidPathException in FS_POSIX#createNewFileAtomic
  Ensure root cause of lock creation failures is logged
  Implement toString in MockSystemReader and MockConfig
  LocalDiskRefTreeDatabaseTest shall use MockSystemReader
  Ensure LocalDiskRepositoryTestCase#setup fully uses MockSystemReader
  Ensure we use MockSystemReader in tests
  Override FileBasedConfig's save method in MockConfig
  Remove FileBasedConfig.load(boolean) introduced in d45219ba
  Disable debug log for FS in org.eclipse.jgit.test
  Bazel: enable logging for tests in org.eclipse.jgit.test
  LockFile: log exception if creation of lock file failed
  Stop using deprecated Constants.CHARACTER_ENCODING

Change-Id: I48c585f3c9287be7d6ddb6b01a1955444e13fa31
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-08-19 18:30:35 +02:00
Matthias Sohn f383206ace Cache user global and system-wide git configurations
So far the git configuration and the system wide git configuration were
always reloaded when jgit accessed these global configuration files to
access global configuration options which are not in the context of a
single git repository. Cache these configurations in SystemReader and
only reload them if their file metadata observed using FileSnapshot
indicates a modification.

Change-Id: I092fe11a5d95f1c5799273cacfc7a415d0b7786c
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
Signed-off-by: Thomas Wolf <thomas.wolf@paranor.ch>
2019-08-18 11:47:26 +02:00
Matthias Sohn 2d84bb4341 Improve retry handling when saving FileStoreAttributes fails
- fix handling of interrupts in FileStoreAttributes#saveToConfig
- increase retry wait time to 100ms
- don't wait after last retry
- dont retry if failure is caused by another exception than
LockFailedException

Change-Id: I108c012717d2bcce71f2c6cb9cf0879de704ebc2
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-08-13 08:33:32 +02:00
Matthias Sohn a7338dd1e5 Remove FileBasedConfig.load(boolean) introduced in d45219ba
We can't add this method to the super class StoredConfig since that
abstracts from filesystem storage. MockSystemReader.MockConfig is a
StoredConfig and is also used by tests for dfs based storage. Hence
remove this leaky abstraction.

This implies we always use the fallback FileStoreAttributes which means
a config file modification is considered racy within the first 2
seconds. This should not be an issue since typically configs change
rarely and re-reading a config within the racy period is relatively
cheap since configs are small.

Change-Id: Ia2615addc24a7cadf3c566ee842c6f4f07e159a5
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-08-10 23:57:21 +02:00
Matthias Sohn 2f8911181b [error prone] fix "FutureReturnValueIgnored" error in FS
Change-Id: I53731091b3e34ac2e93a18f0ad6dd04dc56f8177
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-08-08 14:42:25 +02:00
Matthias Sohn f54db4a857 Merge branch 'stable-5.3' into stable-5.4
* stable-5.3:
  Fix OpenSshConfigTest#config
  FileSnapshot: fix bug with timestamp thresholding
  In LockFile#waitForStatChange wait in units of file time resolution
  Cache FileStoreAttributeCache per directory
  Fix FileSnapshot#save(long) and FileSnapshot#save(Instant)
  Persist minimal racy threshold and allow manual configuration
  Measure minimum racy interval to auto-configure FileSnapshot
  Reuse FileUtils to recursively delete files created by tests
  Fix FileAttributeCache.toString()
  Add test for racy git detection in FileSnapshot
  Repeat RefDirectoryTest.testGetRef_DiscoversModifiedLoose 100 times
  Fix org.eclipse.jdt.core.prefs of org.eclipse.jgit.junit
  Add missing javadoc in org.eclipse.jgit.junit
  Enhance RepeatRule to report number of failures at the end
  Fix FileSnapshotTests for filesystem with high timestamp resolution
  Retry deleting test files in FileBasedConfigTest
  Measure filesystem timestamp resolution already in test setup
  Refactor FileSnapshotTest to use NIO APIs
  Measure stored timestamp resolution instead of time to touch file
  Handle CancellationException in FileStoreAttributeCache
  Fix FileSnapshot#saveNoConfig
  Use Instant for smudge time in DirCache and DirCacheEntry
  Use Instant instead of milliseconds for filesystem timestamp handling
  Workaround SecurityException in FS#getFsTimestampResolution
  Fix NPE in FS$FileStoreAttributeCache.getFsTimestampResolution
  FS: ignore AccessDeniedException when measuring timestamp resolution
  Add debug trace for FileSnapshot
  Use FileChannel.open to touch file and set mtime to now
  Persist filesystem timestamp resolution and allow manual configuration
  Increase bazel timeout for long running tests
  Bazel: Fix lint warning flagged by buildifier
  Update bazlets to latest version
  Bazel: Add missing dependencies for ArchiveCommandTest
  Bazel: Remove FileTreeIteratorWithTimeControl from BUILD file
  Add support for nanoseconds and microseconds for Config#getTimeUnit
  Optionally measure filesystem timestamp resolution asynchronously
  Delete unused FileTreeIteratorWithTimeControl
  FileSnapshot#equals: consider UNKNOWN_SIZE
  Timeout measuring file timestamp resolution after 2 seconds
  Fix RacyGitTests#testRacyGitDetection
  Change RacyGitTests to create a racy git situation in a stable way
  Deprecate Constants.CHARACTER_ENCODING in favor of StandardCharsets.UTF_8
  Fix non-deterministic hash of archives created by ArchiveCommand
  Update Maven plugins ecj, plexus, error-prone
  Update Maven plugins and cleanup Maven warnings
  Make inner classes static where possible
  Fix API problem filters

Change-Id: Iec3ad6ccc194582cb844310dc172c3103dae4457
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-08-08 13:24:14 +02:00
Matthias Sohn 0046b2a8fe Merge branch 'stable-5.1' into stable-5.2
* stable-5.1:
  Fix OpenSshConfigTest#config
  FileSnapshot: fix bug with timestamp thresholding
  In LockFile#waitForStatChange wait in units of file time resolution
  Cache FileStoreAttributeCache per directory
  Fix FileSnapshot#save(long) and FileSnapshot#save(Instant)
  Persist minimal racy threshold and allow manual configuration
  Measure minimum racy interval to auto-configure FileSnapshot
  Reuse FileUtils to recursively delete files created by tests
  Fix FileAttributeCache.toString()
  Add test for racy git detection in FileSnapshot
  Repeat RefDirectoryTest.testGetRef_DiscoversModifiedLoose 100 times
  Fix org.eclipse.jdt.core.prefs of org.eclipse.jgit.junit
  Add missing javadoc in org.eclipse.jgit.junit
  Enhance RepeatRule to report number of failures at the end
  Fix FileSnapshotTests for filesystem with high timestamp resolution
  Retry deleting test files in FileBasedConfigTest
  Measure filesystem timestamp resolution already in test setup
  Refactor FileSnapshotTest to use NIO APIs
  Measure stored timestamp resolution instead of time to touch file
  Handle CancellationException in FileStoreAttributeCache
  Fix FileSnapshot#saveNoConfig
  Use Instant for smudge time in DirCache and DirCacheEntry
  Use Instant instead of milliseconds for filesystem timestamp handling
  Workaround SecurityException in FS#getFsTimestampResolution
  Fix NPE in FS$FileStoreAttributeCache.getFsTimestampResolution
  FS: ignore AccessDeniedException when measuring timestamp resolution
  Add debug trace for FileSnapshot
  Use FileChannel.open to touch file and set mtime to now
  Persist filesystem timestamp resolution and allow manual configuration
  Increase bazel timeout for long running tests
  Bazel: Fix lint warning flagged by buildifier
  Update bazlets to latest version
  Bazel: Add missing dependencies for ArchiveCommandTest
  Bazel: Remove FileTreeIteratorWithTimeControl from BUILD file
  Add support for nanoseconds and microseconds for Config#getTimeUnit
  Optionally measure filesystem timestamp resolution asynchronously
  Delete unused FileTreeIteratorWithTimeControl
  FileSnapshot#equals: consider UNKNOWN_SIZE
  Timeout measuring file timestamp resolution after 2 seconds
  Fix RacyGitTests#testRacyGitDetection
  Change RacyGitTests to create a racy git situation in a stable way
  Deprecate Constants.CHARACTER_ENCODING in favor of StandardCharsets.UTF_8
  Fix non-deterministic hash of archives created by ArchiveCommand
  Update Maven plugins ecj, plexus, error-prone
  Update Maven plugins and cleanup Maven warnings
  Make inner classes static where possible
  Fix API problem filters

Change-Id: Ia57385b2a60f48a5317c8d723721c235d7043a84
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-08-08 11:54:56 +02:00
Matthias Sohn 6857138e19 Cache FileStoreAttributeCache per directory
Cache FileStoreAttributeCache entries since looking up FileStore for a
file may be expensive on some platforms.

Implement a simple LRU cache based on ConcurrentHashMap using a simple
long counter to order access to cache entries.

Change-Id: I4881fa938ad2f17712c05da857838073a2fc4ddb
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
Signed-off-by: Marc Strapetz <marc.strapetz@syntevo.com>
Also-By: Marc Strapetz <marc.strapetz@syntevo.com>
2019-08-06 14:54:39 +02:00
Matthias Sohn 275f3da783 Fix FileSnapshot#save(long) and FileSnapshot#save(Instant)
Use the fallback timestamp resolution as already described in the
javadoc of these methods. Using zero file timestamp resolution doesn't
make sense.

Change-Id: Iaad2a0f99c3be3678e94980a0a368181b6aed38c
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-08-06 14:54:39 +02:00
Matthias Sohn d45219baac Persist minimal racy threshold and allow manual configuration
To enable persisting the minimal racy threshold per FileStore add a
new config option to the user global git configuration:

- Config section is "filesystem"
- Config subsection is concatenation of
  - Java vendor (system property "java.vendor")
  - Java version (system property "java.version")
  - FileStore's name, on Windows we use the attribute volume:vsn instead
    since  the name is not necessarily unique.
  - separated by '|'
  e.g.
    "AdoptOpenJDK|1.8.0_212-b03|/dev/disk1s1"
  The same prefix is used as for filesystem timestamp resolution, so
  both values are stored in the same config section
- The config key for minmal racy threshold is "minRacyThreshold" as a
  time value, supported time units are those supported by
  DefaultTypedConfigGetter#getTimeUnit
- measure for 3 seconds to limit runtime which depends on hardware, OS
  and Java version being used

If the minimal racy threshold is configured for a given FileStore the
configured value is used instead of measuring it.

When the minimal racy threshold was measured it is persisted in the user
global git configuration.

Rename FileStoreAttributeCache to FileStoreAttributes since this class
is now declared public in order to enable exposing all attributes in one
object.

Example:

[filesystem "AdoptOpenJDK|11.0.3|/dev/disk1s1"]
	timestampResolution = 7000 nanoseconds
	minRacyThreshold = 3440 microseconds

Change-Id: I22195e488453aae8d011b0a8e3276fe3d99deaea
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
Also-By: Marc Strapetz <marc.strapetz@syntevo.com>
2019-08-06 14:54:39 +02:00
Matthias Sohn 5911521ba6 Measure minimum racy interval to auto-configure FileSnapshot
By running FileSnapshotTest#detectFileModified we found that the sum of
measured filesystem timestamp resolution and measured clock resolution
may yield a too small interval after a file has been modified which we
need to consider racily clean. In our tests we didn't find this behavior
on all systems we tested on, e.g. on MacOS using APFS and Java 8 and 11
this effect was not observed.

On Linux (SLES 15, kernel 4.12.14-150.22-default) we collected the
following test results using Java 8 and 11:

In 23-98% of 10000 test runs (depending on filesystem type and Java
version) the test failed, which means the effective interval which needs
to be considered racily clean after a file was modified is larger than
the measured file timestamp resolution.

"delta" is the observed interval after a file has been modified but
FileSnapshot did not yet detect the modification:

"resolution" is the measured sum of file timestamp resolution and clock
resolution seen in Java.

Java version    filesystem  failures resolution  min delta   max delta
1.8.0_212-b04   btrfs	    98.6%       1 ms        3.6 ms      6.6 ms
1.8.0_212-b04   ext4        82.6%       3 ms        1.1 ms      4.1 ms
1.8.0_212-b04   xfs         23.8%       4 ms        3.7 ms      3.9 ms
1.8.0_212-b04   zfs         23.1%       3 ms        4.8 ms      5.0 ms
11.0.3+7        btrfs       98.1%       3 us        0.7 ms      4.7 ms
11.0.3+7        ext4        98.1%       6 us        0.7 ms      4.7 ms
11.0.3+7        xfs         98.5%       7 us        0.1 ms      8.0 ms
11.0.3+7        zfs         98.4%       7 us        0.7 ms      5.2 ms

Mac OS
1.8.0_212       APFS        0%          1 s
11.0.3+7        APFS        0%          6 us

The observed delta is not distributed according to a normal gaussian
distribution but rather random in the observed range between "min delta"
and "max delta".

Run this test after measuring file timestamp resolution in
FS.FileAttributeCache to auto-configure JGit since it's unclear what
mechanism is causing this effect.

In FileSnapshot#isRacyClean use the maximum of the measured timestamp
resolution and the measured "delta" as explained above to decide if a
given FileSnapshot is to be considered racily clean. Add a 30% safety
margin to ensure we are on the safe side.

Change-Id: I1c8bb59f6486f174b7bbdc63072777ddbe06694d
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-08-06 14:54:35 +02:00
Matthias Sohn d17efe880d Fix FileAttributeCache.toString()
We should not list the complete cache but only show the cache entry at
hand.

Change-Id: I22be2a4dcbf0145155e23f2389bfcf5662cf23a6
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-07-26 15:53:29 +02:00
Matthias Sohn 99d351d0cb Measure stored timestamp resolution instead of time to touch file
Measure granularity of timestamps stored in the filesystem by setting
and then getting lastModified timestamp until the read value changed.
Increase increment exponentially to limit number of iterations starting
with 1 microsecond since Java's FileTime (up to Java 12) truncates
timestamps to 1 microsecond resolution. The chosen algorithm yields 2000
steps between 1 ms and 2.5 s.

Also measure clock resolution and add that for the total timestamp
resolution. This avoids systematic measurement errors introduced by
doing IO to touch a file.

Change-Id: I9b37138619422452373e298d9d8c7cb2c384db3f
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-07-19 14:45:55 +02:00
Matthias Sohn 37f7679fc9 Handle CancellationException in FileStoreAttributeCache
Change-Id: If5985fbf04f630b1d72a1bafd508e0e15e1436be
2019-07-19 14:45:55 +02:00
Matthias Sohn 95e8264cc8 Use Instant instead of milliseconds for filesystem timestamp handling
This enables higher file timestamp resolution on filesystems like ext4,
Mac APFS (1ns) or NTFS (100ns) providing high timestamp resolution on
filesystem level.

Note:
- on some OSes Java 8,9 truncate milliseconds, see
https://bugs.openjdk.java.net/browse/JDK-8177809, fixed in Java 10
- UnixFileAttributes truncates timestamp resolution to microseconds when
converting the internal representation to FileTime exposed in the API,
see https://bugs.openjdk.java.net/browse/JDK-8181493
- WindowsFileAttributes also provides only microsecond resolution

Change-Id: I25ffff31a3c6f725fc345d4ddc2f26da3b88f6f2
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-07-18 03:27:52 +02:00
Matthias Sohn 4db39f5074 Workaround SecurityException in FS#getFsTimestampResolution
On Android FS#getFsTimestampResolution always throws a
SecurityException, handle this by falling back to the fallback timestamp
resolution.

Bug: 548947
Change-Id: I0ee6cb3c20e189bdc8d488434a930427ad6f2df2
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-07-17 09:42:15 +02:00
Matthias Sohn 79ede0c322 Fix NPE in FS$FileStoreAttributeCache.getFsTimestampResolution
Bug: 548682
Change-Id: I48840d3a68cf1db92c056d218a0d5ed0b9ea4c45
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-07-17 09:42:14 +02:00
Matthias Sohn be66222d1a FS: ignore AccessDeniedException when measuring timestamp resolution
It seems on cygwin creating a file under a writable directory can fail
with AccessDeniedException. Log a warning in this case and fallback to
worst case timestamp resolution of 2 seconds.

Bug: 548648
Change-Id: Ic50c31ce9dc9ccadd4db5247df929418ac62d45c
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-07-17 09:42:14 +02:00
Matthias Sohn 8a0ed8a004 Use FileChannel.open to touch file and set mtime to now
Use options
- StandardOpenOption.CREATE to create touched file if not existing
- StandardOpenOption.SYNC to enforce synch of data and meta data changes
- StandardOpenOption.WRITE

Also set mtime explicitly in FileUtils#touch to the current system time.
This should fix that the previous implementation didn't work on
- locally cached Windows network share (CSC-CACHE filesystem) mapped as
a drive
- nfsv4 mounts on Linux
and that it didn't create unborn file like Linux command "touch".
Apache common's and Guava's touch() use the same approach.

Immediately after creating the probe file used to measure timestamp
resolution touch it. This ensures we always use the local system clock
when measuring filesystem timestamp resolution. This should prevent that
clock skew could influence the measured timestamp resolution in case of
a mounted network filesystem.

Bug: 548598
Change-Id: Iaeaf5967963f582395a195aa637b8188bfadac60
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-07-17 09:42:14 +02:00
Matthias Sohn 16760c3e9a Persist filesystem timestamp resolution and allow manual configuration
To enable persisting filesystem timestamp resolution per FileStore add a
new config section to the user global git configuration:

- Config section is "filesystem"
- Config subsection is concatenation of
  - Java vendor (system property "java.vm.vendor")
  - runtime version (system property "java.vm.version")
  - FileStore's name
  - separated by '|'
  e.g.
    "AdoptOpenJDK|1.8.0_212-b03|/dev/disk1s1"
  The prefix is needed since some Java versions do not expose the full
  timestamp resolution of the underlying filesystem. This may also
  depend on the underlying operating system hence concrete key values
  may not be portable.
- Config key for timestamp resolution is "timestampResolution" as a time
  value, supported time units are those supported by
  DefaultTypedConfigGetter#getTimeUnit

If timestamp resolution is already configured for a given FileStore
the configured value is used instead of measuring the resolution.

When timestamp resolution was measured it is persisted in the user
global git configuration.

Example:

[filesystem "AdoptOpenJDK|1.8.0_212-b03|/dev/disk1s1"]
	timestampResolution = 1 seconds

If locking the git config file fails retry saving the resolution up to 5
times in order to workaround races with another thread.

In order to avoid stack overflow use the fallback filesystem timestamp
resolution when loading FileBasedConfig which creates itself a
FileSnapshot to help checking if the config changed.

Note:
- on some OSes Java 8,9 truncate to milliseconds or seconds, see
https://bugs.openjdk.java.net/browse/JDK-8177809, fixed in Java 10
- UnixFileAttributes up to Java 12 truncates timestamp resolution to
microseconds when converting the internal representation to FileTime
exposed in the API, see https://bugs.openjdk.java.net/browse/JDK-8181493
- WindowsFileAttributes also provides only microsecond resolution up to
Java 12

Hence do not attempt to manually configure a higher timestamp resolution
than supported by the Java version being used at runtime.

Bug: 546891
Bug: 548188
Change-Id: Iff91b8f9e6e5e2295e1463f87c8e95edf4abbcf8
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-07-17 09:42:14 +02:00
Matthias Sohn a950eac23b Optionally measure filesystem timestamp resolution asynchronously
In order to avoid blocking on the main thread during measurement
interactive applications like EGit may want to measure the filesystem
timestamp resolution asynchronously.

In order to enable measurement in the background call
FileStoreAttributeCache.setAsyncfileStoreAttrCache(true)
before the first access to cached FileStore attributes.

Bug: 548188
Change-Id: I8c9a2dbfc3f1d33441edea18b90e36b1dc0156c7
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-07-11 10:12:04 +02:00
Matthias Sohn 850b9d7540 Timeout measuring file timestamp resolution after 2 seconds
It was reported that measuring file timestamp resolution may hang
indefinitely on nfs. Hence timeout this measurement at the known worst
filesystem timestamp resolution (FAT) of 2 seconds.

Bug: 548188
Change-Id: I17004b0aa49d5b0e76360a008af3adb911b289c0
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-07-03 21:34:29 +02:00
David Pursehouse f18b5010fc Deprecate Constants.CHARACTER_ENCODING in favor of StandardCharsets.UTF_8
Change-Id: I621ba174235a6fb56236e54d24bce704bb5afb28
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2019-06-19 10:43:01 +02:00
Matthias Sohn d9c569b747 Merge branch 'stable-5.3' into stable-5.4
* stable-5.3:
  Prepare 5.3.3-SNAPSHOT builds
  JGit v5.3.2.201906051522-r
  Prepare 5.1.9-SNAPSHOT builds
  JGit v5.1.8.201906050907-r
  Test detecting modified packfiles
  Enhance fsTick() to use filesystem timer resolution
  Add debug trace to measure time needed to open pack index
  Extend FileSnapshot for packfiles to also use checksum to detect changes
  Wait opening new packfile until it can't be racy anymore
  Avoid null PackConfig in GC
  Add FileSnapshot test testing recognition of file size changes
  Capture reason for result of FileSnapshot#isModified
  Skip FileSnapshotTest#testSimulatePackfileReplacement on Windows
  Tune max heap size for tests
  Fix FileSnapshotTest.testNewFileNoWait() to match its javadoc
  ObjectDirectory: fix closing of obsolete packs
  Update API filters for methods added to fix bugs
  Bazel: Increase severity of most error-prone checks to ERROR
  Enable error-prone checks by default
  Add bazel options to align with gerrit's
  Include filekey file attribute when comparing FileSnapshots
  Measure file timestamp resolution used in FileSnapshot
  Fix FileSnapshot's consideration of file size
  Fix API problem filters
  Fix API problem filters

Change-Id: Ie1c7e4752661aec9e1754660934921224e2408eb
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-06-06 17:14:31 +02:00
Matthias Sohn 4018709eb9 Merge branch 'stable-5.1' into stable-5.2
* stable-5.1:
  Prepare 5.1.9-SNAPSHOT builds
  JGit v5.1.8.201906050907-r
  Test detecting modified packfiles
  Enhance fsTick() to use filesystem timer resolution
  Add debug trace to measure time needed to open pack index
  Extend FileSnapshot for packfiles to also use checksum to detect changes
  Wait opening new packfile until it can't be racy anymore
  Avoid null PackConfig in GC
  Add FileSnapshot test testing recognition of file size changes
  Capture reason for result of FileSnapshot#isModified
  Skip FileSnapshotTest#testSimulatePackfileReplacement on Windows
  Tune max heap size for tests
  Fix FileSnapshotTest.testNewFileNoWait() to match its javadoc
  ObjectDirectory: fix closing of obsolete packs
  Include filekey file attribute when comparing FileSnapshots
  Measure file timestamp resolution used in FileSnapshot
  Fix FileSnapshot's consideration of file size
  Fix API problem filters

Change-Id: I3ac77bfa03f7436de12ab86e1bba29afee5ccd01
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-06-05 20:58:16 +02:00
Matthias Sohn b513b77477 Measure file timestamp resolution used in FileSnapshot
FileSnapshot.notRacyClean() assumed a worst case filesystem timestamp
resolution of 2.5 sec (FAT has a resolution of 2 sec). Instead measure
timestamp resolution to avoid unnecessary IO caused by false positives
in detecting the racy git problem caused by finite filesystem timestamp
resolution [1].

Cache the measured resolution per FileStore since timestamp resolution
depends on the respective filesystem type. If timestamp resolution
cannot be measured or fails due to an exception fallback to the worst
case FAT timestamp resolution and avoid caching this value.

Add a 10% safety margin in FileSnapshot.notRacyClean(), though running
FsTest.testFsTimestampResolution() 1000 times which is not using a
safety margin didn't fail on Mac using APFS and Java 8, 11, 12.

Measured Java file timestamp resolution: [2]

[1] https://github.com/git/git/blob/master/Documentation/technical/racy-git.txt
[2] https://docs.google.com/spreadsheets/d/1imy0y6WmRqBf0kjCxzxj2X7M50eIVfa7oaUIzEOHmjo

Bug: 546891
Change-Id: I493f3b57b6b306285ffa7d392339d253e5966ab8
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-05-22 08:13:22 +02:00
Carsten Hammer 84fc5c908d Convert to lambda or member reference
Convert anonymous inner classes to lambda expressions or member
references

Bug: 545856
CQ: 19537
Change-Id: I621431c178e8b99316314602f7c66c9a36f9ae98
Signed-off-by: Carsten Hammer <carsten.hammer@t-online.de>
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-05-16 02:58:43 -04:00
Matthias Sohn 6a7a265b4d Merge branch 'stable-5.1' into stable-5.2
* stable-5.1:
  Prepare 5.1.7-SNAPSHOT builds
  JGit v5.1.6.201903130242-r
  Prepare 4.11.8-SNAPSHOT builds
  JGit v4.11.7.201903122105-r
  Prepare 4.9.10-SNAPSHOT builds
  JGit v4.9.9.201903122025-r
  Prepare 4.7.9-SNAPSHOT builds
  JGit v4.7.8.201903121755-r
  Prepare 4.5.7-SNAPSHOT builds
  JGit v4.5.6.201903121547-r
  Check for packfile validity and fd before reading
  Move throw of PackInvalidException outside the catch
  Use FileSnapshot to get lastModified on PackFile
  Include size when comparing FileSnapshot
  Do not reuse packfiles when changed on filesystem
  Silence API warnings for new API introduced for fixes

Change-Id: I8da2761ed27ff2817a4136f843b9b293e3c0f4e6
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-03-13 07:56:47 +01:00
Matthias Sohn b0d27cdae9 Merge branch 'stable-5.0' into stable-5.1
* stable-5.0:
  Prepare 4.11.8-SNAPSHOT builds
  JGit v4.11.7.201903122105-r
  Prepare 4.9.10-SNAPSHOT builds
  JGit v4.9.9.201903122025-r
  Prepare 4.7.9-SNAPSHOT builds
  JGit v4.7.8.201903121755-r
  Prepare 4.5.7-SNAPSHOT builds
  JGit v4.5.6.201903121547-r
  Check for packfile validity and fd before reading
  Move throw of PackInvalidException outside the catch
  Use FileSnapshot to get lastModified on PackFile
  Include size when comparing FileSnapshot
  Do not reuse packfiles when changed on filesystem
  Silence API warnings for new API introduced for fixes

Change-Id: I71771dcc086a9a0097bad74d65ec71ad97106a38
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-03-13 07:38:38 +01:00
Matthias Sohn 7480737aac Merge branch 'stable-4.11' into stable-5.0
* stable-4.11:
  Prepare 4.11.8-SNAPSHOT builds
  JGit v4.11.7.201903122105-r
  Prepare 4.9.10-SNAPSHOT builds
  JGit v4.9.9.201903122025-r
  Prepare 4.7.9-SNAPSHOT builds
  JGit v4.7.8.201903121755-r
  Prepare 4.5.7-SNAPSHOT builds
  JGit v4.5.6.201903121547-r
  Check for packfile validity and fd before reading
  Move throw of PackInvalidException outside the catch
  Use FileSnapshot to get lastModified on PackFile
  Include size when comparing FileSnapshot
  Do not reuse packfiles when changed on filesystem
  Silence API warnings for new API introduced for fixes

Change-Id: I04c70f66c6f1e53bdc199fb5b24c9136c9a8e4f7
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-03-13 02:21:54 +01:00
Matthias Sohn 7204e35f93 Merge branch 'stable-4.10' into stable-4.11
* stable-4.10:
  Prepare 4.9.10-SNAPSHOT builds
  JGit v4.9.9.201903122025-r
  Prepare 4.7.9-SNAPSHOT builds
  JGit v4.7.8.201903121755-r
  Prepare 4.5.7-SNAPSHOT builds
  JGit v4.5.6.201903121547-r
  Check for packfile validity and fd before reading
  Move throw of PackInvalidException outside the catch
  Use FileSnapshot to get lastModified on PackFile
  Include size when comparing FileSnapshot
  Do not reuse packfiles when changed on filesystem
  Silence API warnings for new API introduced for fixes

Change-Id: Ic66dc00455c05f7627919f682a7221ffeef1629d
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-03-13 01:55:24 +01:00
Matthias Sohn f53c2d11af Merge branch 'stable-4.9' into stable-4.10
* stable-4.9:
  Prepare 4.9.10-SNAPSHOT builds
  JGit v4.9.9.201903122025-r
  Prepare 4.7.9-SNAPSHOT builds
  JGit v4.7.8.201903121755-r
  Prepare 4.5.7-SNAPSHOT builds
  JGit v4.5.6.201903121547-r
  Check for packfile validity and fd before reading
  Move throw of PackInvalidException outside the catch
  Use FileSnapshot to get lastModified on PackFile
  Include size when comparing FileSnapshot
  Do not reuse packfiles when changed on filesystem
  Silence API warnings for new API introduced for fixes

Change-Id: Ifcd8ea6a2b59f6f8e9d896d8407cfcaef0a9375d
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-03-13 01:48:06 +01:00
Matthias Sohn c452c007ce Merge branch 'stable-4.8' into stable-4.9
* stable-4.8:
  Prepare 4.7.9-SNAPSHOT builds
  JGit v4.7.8.201903121755-r
  Prepare 4.5.7-SNAPSHOT builds
  JGit v4.5.6.201903121547-r
  Check for packfile validity and fd before reading
  Move throw of PackInvalidException outside the catch
  Use FileSnapshot to get lastModified on PackFile
  Include size when comparing FileSnapshot
  Do not reuse packfiles when changed on filesystem
  Silence API warnings for new API introduced for fixes

Change-Id: I9a47153831f8eb10d3cd91b4157cf45385e5b13a
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-03-13 01:18:01 +01:00
Matthias Sohn 2bf3cc56db Merge branch 'stable-4.7' into stable-4.8
* stable-4.7:
  Prepare 4.7.9-SNAPSHOT builds
  JGit v4.7.8.201903121755-r
  Prepare 4.5.7-SNAPSHOT builds
  JGit v4.5.6.201903121547-r
  Check for packfile validity and fd before reading
  Move throw of PackInvalidException outside the catch
  Use FileSnapshot to get lastModified on PackFile
  Include size when comparing FileSnapshot
  Do not reuse packfiles when changed on filesystem
  Silence API warnings for new API introduced for fixes

Change-Id: I1136eaa1590b225ceaf16ba7552af0374253a74e
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-03-13 01:16:28 +01:00
Matthias Sohn 92525b584a Merge branch 'stable-4.6' into stable-4.7
* stable-4.6:
  Prepare 4.5.7-SNAPSHOT builds
  JGit v4.5.6.201903121547-r
  Check for packfile validity and fd before reading
  Move throw of PackInvalidException outside the catch
  Use FileSnapshot to get lastModified on PackFile
  Include size when comparing FileSnapshot
  Do not reuse packfiles when changed on filesystem
  Silence API warnings for new API introduced for fixes

Change-Id: I3d1544d034783fe0fa1385dfe9b03ad8e9247c63
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-03-12 22:39:53 +01:00
Matthias Sohn d96eb8b3e6 Merge branch 'stable-4.5' into stable-4.6
* stable-4.5:
  Prepare 4.5.7-SNAPSHOT builds
  JGit v4.5.6.201903121547-r
  Check for packfile validity and fd before reading
  Move throw of PackInvalidException outside the catch
  Use FileSnapshot to get lastModified on PackFile
  Include size when comparing FileSnapshot
  Do not reuse packfiles when changed on filesystem
  Silence API warnings for new API introduced for fixes

Change-Id: I029e1797447e6729de68bd89d4d69b324dbb3f5f
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-03-12 22:26:58 +01:00
Luca Milanesio 2dc572df24 Include size when comparing FileSnapshot
Due to finite filesystem timestamp resolution the last modified
timestamp of files cannot detect file changes which happened in the
immediate past (less than one filesystem timer tick ago).

Read and consider file size also, so that differing file size can help
to more accurately detect file changes without reading the file content.
Use bulk read to avoid multiple stat calls to retrieve file attributes.

Change-Id: I974288fff78ac78c52245d9218b5639603f67a46
Signed-off-by: Luca Milanesio <luca.milanesio@gmail.com>
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2019-03-12 14:39:14 +01:00
Thomas Wolf 9c755c9e7c Set git environment variables for hooks
Set GIT_DIR and GIT_WORK_TREE when calling hooks.

Bug: 541622
Change-Id: I6153d8a6a934ec37a3a5e7319c2d0e516f539ab7
Signed-off-by: Thomas Wolf <thomas.wolf@paranor.ch>
2018-11-30 00:37:03 +01:00
David Pursehouse fbf6ce65ba Deprecate Constants.CHARACTER_ENCODING in favor of StandardCharsets.UTF_8
Change-Id: I621ba174235a6fb56236e54d24bce704bb5afb28
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2018-09-30 14:34:14 +09:00
David Pursehouse 1cfb4241de Merge branch 'stable-5.0' into stable-5.1
* stable-5.0:
  Fix ObjectUploadListener#close
  Fix error handling in FileLfsServlet
  ObjectDownloadListener#onWritePossible: Make code spec compatible
  ObjectDownloadListener: Return from onWritePossible when data is written
  Fix IOException when LockToken#close fails

Change-Id: Ib7a63b5144a89c213aff3b32c30a2a6526355e64
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2018-09-18 09:19:18 +09:00
David Pursehouse ca922217e2 Merge branch 'stable-4.11' into stable-5.0
* stable-4.11:
  Fix ObjectUploadListener#close
  Fix error handling in FileLfsServlet
  ObjectDownloadListener#onWritePossible: Make code spec compatible
  ObjectDownloadListener: Return from onWritePossible when data is written
  Fix IOException when LockToken#close fails

Change-Id: Iffe202a412b3bca1c8d8d7dc5dfd646c49838de9
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2018-09-18 09:18:40 +09:00
David Pursehouse 1e170b16a4 Merge branch 'stable-4.10' into stable-4.11
* stable-4.10:
  Fix ObjectUploadListener#close
  Fix error handling in FileLfsServlet
  ObjectDownloadListener#onWritePossible: Make code spec compatible
  ObjectDownloadListener: Return from onWritePossible when data is written
  Fix IOException when LockToken#close fails

Change-Id: I28ebf6138ccd9425fc05319de78c7716f0bdd199
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2018-09-18 09:17:02 +09:00
David Pursehouse ecf3227d32 Merge branch 'stable-4.9' into stable-4.10
* stable-4.9:
  Fix ObjectUploadListener#close
  Fix error handling in FileLfsServlet
  ObjectDownloadListener#onWritePossible: Make code spec compatible
  ObjectDownloadListener: Return from onWritePossible when data is written
  Fix IOException when LockToken#close fails

Change-Id: Ib7d01cb0ece8b259156855045a53b8baf3fa2968
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2018-09-18 09:16:29 +09:00
David Pursehouse 1780a12e20 Merge branch 'stable-4.8' into stable-4.9
* stable-4.8:
  Fix ObjectUploadListener#close
  Fix error handling in FileLfsServlet
  ObjectDownloadListener#onWritePossible: Make code spec compatible
  ObjectDownloadListener: Return from onWritePossible when data is written
  Fix IOException when LockToken#close fails

Change-Id: Id8eb635094336567d9f3c28ec985cd5127d31632
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2018-09-18 09:16:01 +09:00
David Pursehouse 531da4e5e9 Merge branch 'stable-4.7' into stable-4.8
* stable-4.7:
  Fix ObjectUploadListener#close
  Fix error handling in FileLfsServlet
  ObjectDownloadListener#onWritePossible: Make code spec compatible
  ObjectDownloadListener: Return from onWritePossible when data is written
  Fix IOException when LockToken#close fails

Change-Id: Iad9836811be034cf992ea25dad4409addba75115
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2018-09-18 09:15:24 +09:00
Matthias Sohn e6e9073fc7 Fix IOException when LockToken#close fails
This happened if the LockTokens hard link was already deleted earlier.

Bug: 531759
Change-Id: Idc84bd695fac1a763b3cbb797c9c4c636a16e329
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2018-09-15 09:11:17 +02:00
Cliffred van Velzen 0c8200b27b Fix logging null if called process fails
If some process executed by FS#readPipe ends in an error,
the error stream is never set as errorMessage because
FS#GobblerThread#waitForProcessCompletion always returned true.
This caused LOG#warn to be called with null.

Return false whenever FS#GobblerThread#waitForProcessCompletion fails.

Bug: 538723
Change-Id: Ic9492bd688431d52c8665f7a2efec2989e95a4ce
Signed-off-by: Cliffred van Velzen <cliffred@cliffred.nl>
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2018-09-12 23:42:35 +02:00
Matthias Sohn 155dd1c5be Merge branch 'stable-4.11' into stable-5.0
* stable-4.11:
  Fix atomic lock file creation on NFS
  Use constant for ".lock"
  Fix handling of option core.supportsAtomicCreateNewFile
  GC: Avoid logging errors when deleting non-empty folders

Change-Id: Ifcc8bfab4fd05c18a08dd82588860dffd0e6d726
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2018-09-08 11:09:27 +02:00
Matthias Sohn 5a583ef393 Merge branch 'stable-4.10' into stable-4.11
* stable-4.10:
  Fix atomic lock file creation on NFS
  Use constant for ".lock"
  Fix handling of option core.supportsAtomicCreateNewFile
  GC: Avoid logging errors when deleting non-empty folders

Change-Id: Ie86079d9ad76972306bc80e63d8bfe18ae06a0da
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2018-09-08 10:12:48 +02:00
Matthias Sohn 9e26cb106f Merge branch 'stable-4.9' into stable-4.10
* stable-4.9:
  Fix atomic lock file creation on NFS
  Use constant for ".lock"
  Fix handling of option core.supportsAtomicCreateNewFile
  GC: Avoid logging errors when deleting non-empty folders

Change-Id: I32dc651870b7ba7c88de448c7984134b7c99e7e3
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2018-09-08 10:03:22 +02:00
Matthias Sohn 4ce79bf738 Merge branch 'stable-4.8' into stable-4.9
* stable-4.8:
  Fix atomic lock file creation on NFS
  Use constant for ".lock"
  Fix handling of option core.supportsAtomicCreateNewFile
  GC: Avoid logging errors when deleting non-empty folders

Change-Id: Id7f68f4e8fb07a21737e3b7090f600507a13bbbe
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2018-09-08 09:15:01 +02:00
Matthias Sohn 8699a95d2d Merge branch 'stable-4.7' into stable-4.8
* stable-4.7:
  Fix atomic lock file creation on NFS
  Use constant for ".lock"
  Fix handling of option core.supportsAtomicCreateNewFile
  GC: Avoid logging errors when deleting non-empty folders

Change-Id: Ia7a18f69eee173aec9e462c16eee2b0ca4565e76
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2018-09-08 08:58:12 +02:00
Matthias Sohn 06e06fc291 Fix atomic lock file creation on NFS
FS_POSIX.createNewFile(File) failed to properly implement atomic file
creation on NFS using the algorithm [1]:
- name of the hard link must be unique to prevent that two processes
  using different NFS clients try to create the same link. This would
  render nlink useless to detect if there was a race.
- the hard link must be retained for the lifetime of the file since we
  don't know when the state of the involved NFS clients will be
  synchronized. This depends on NFS configuration options.

To fix these issues we need to change the signature of createNewFile
which would break API. Hence deprecate the old method
FS.createNewFile(File) and add a new method createNewFileAtomic(File).

The new method returns a LockToken which needs to be retained by the
caller (LockFile) until all involved NFS clients synchronized their
state. Since we don't know when the NFS caches are synchronized we need
to retain the token until the corresponding file is no longer needed.
The LockToken must be closed after the LockFile using it has been
committed or unlocked. On Posix, if core.supportsAtomicCreateNewFile =
false this will delete the hard link which guarded the atomic creation
of the file. When acquiring the lock fails ensure that the hard link is
removed.

[1] https://www.time-travellers.org/shane/papers/NFS_considered_harmful.html
also see file creation flag O_EXCL in
http://man7.org/linux/man-pages/man2/open.2.html

Change-Id: I84fcb16143a5f877e9b08c6ee0ff8fa4ea68a90d
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2018-09-07 12:13:53 +02:00
Han-Wen Nienhuys f3ec7cf3f0 Remove further unnecessary 'final' keywords
Remove it from

 * package private functions.

 * try blocks

 * for loops

this was done with the following python script:

$ cat f.py
import sys
import re
import os

def replaceFinal(m):
  return m.group(1) + "(" +  m.group(2).replace('final ', '') + ")"

methodDecl = re.compile(r"^([\t ]*[a-zA-Z_ ]+)\(([^)]*)\)")

def subst(fn):
  input = open(fn)
  os.rename(fn, fn + "~")

  dest = open(fn, 'w')
  for l in input:
    l = methodDecl.sub(replaceFinal, l)
    dest.write(l)
  dest.close()


for root, dirs, files in os.walk(".", topdown=False):
  for f in files:
    if not f.endswith('.java'):
      continue

    full = os.path.join(root, f)
    print full
    subst(full)

Change-Id: If533a75a417594fc893e7c669d2c1f0f6caeb7ca
Signed-off-by: Han-Wen Nienhuys <hanwen@google.com>
2018-05-18 17:59:45 +02:00
Han-Wen Nienhuys 6d370d837c Remove 'final' in parameter lists
Change-Id: Id924f79c8b2c720297ebc49bf9c5d4ddd6d52547
Signed-off-by: Han-Wen Nienhuys <hanwen@google.com>
2018-05-15 17:05:02 -04:00
Thomas Wolf 4bfc6c2ae9 Significantly speed up FileTreeIterator on Windows
Getting attributes of files on Windows is an expensive operation.
Windows stores file attributes in the directory, so they are
basically available "for free" when a directory is listed. The
implementation of Java's Files.walkFileTree() takes advantage of
that (at least in the OpenJDK implementation for Windows) and
provides the attributes from the directory to a FileVisitor.

Using Files.walkFileTree() with a maximum depth of 1 is thus a
good approach on Windows to get both the file names and the
attributes in one go.

In my tests, this gives a significant speed-up of FileTreeIterator
over the "normal" way: using File.listFiles() and then reading the
attributes of each file individually. The speed-up is hard to
quantify exactly, but in my tests I've observed consistently 30-40%
for staging 500 files one after another, each individually, and up
to 50% for individual TreeWalks with a FileTreeIterator.

On Unix, this technique is detrimental. Unix stores file attributes
differently, and getting attributes of individual files is not costly.
On Unix, the old way of doing a listFiles() and getting individual
attributes (both native operations) is about three times faster than
using walkFileTree, which is implemented in Java.

Therefore, move the operation to FS/FS_Win32 and call it from
FileTreeIterator, so that we can have different implementations
depending on the file system.

A little performance test program is included as a JUnit test (to be
run manually).

While this does speed up things on Windows, it doesn't solve the basic
problem of bug 532300: the iterator always gets the full directory
listing and the attributes of all files, and the more files there are
the longer that takes.

Bug: 532300
Change-Id: Ic5facb871c725256c2324b0d97b95e6efc33282a
Signed-off-by: Thomas Wolf <thomas.wolf@paranor.ch>
2018-03-25 13:43:37 +02:00
David Pursehouse 76b4ed6a85 FS#runProcess: Fix OutputStream left unclosed after IOException
The runProcess method creates an OutputStream that is not managed by
a try-with-resource because it's manually closed and any IOException
raised by the close() method is explicitly ignored.

Suppress the resource warning with an explanatory comment.

Enclose the call to StreamGobbler#copy in an inner try-block, and move
the call to close() inside its finally block. This prevents the stream
from being left unclosed if StreamGobbler#copy raises IOException.

Change-Id: Idca9adfc4d87e0989d787ad8239c055c0c849814
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2018-03-24 22:15:43 +01:00
David Pursehouse fabd645fad FS: Open TemporaryBuffer in try-with-resource
Change-Id: I52e048e491e838b7f762a5b5f4d148e91049877c
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2018-03-06 16:58:12 +09:00
Matthias Sohn fdbaa25db9 Fix javadoc in org.eclipse.jgit util packages
Change-Id: Ia655f45153bcf1d422ffffce6dcf914847e14c4c
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2017-12-20 22:10:11 +01:00
Matthias Sohn 9d79dc95e2 Fix typo in key of a JGitText externalized string
Change-Id: I0d22e24a0aa3b17339ef68849554f7c99b350dde
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2017-12-11 09:35:15 +09:00
Matthias Sohn b46656077a Fix typo in key of a JGitText externalized string
Change-Id: I0d22e24a0aa3b17339ef68849554f7c99b350dde
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2017-12-10 18:33:23 +01:00
Matthias Sohn 032750acbf Merge branch 'stable-4.9'
* stable-4.9:
  Fix IllegalThreadStateException if stderr closed without exiting

Change-Id: I8a6a6788c2bb000171233b88d9592ed0640ad15e
2017-12-10 18:10:34 +01:00
Dmitry Pavlenko 7ccf38adc6 Fix IllegalThreadStateException if stderr closed without exiting
If some process executed by FS#readPipe lived for a while after
closing stderr, FS#GobblerThread#run failed with an
IllegalThreadStateException exception when accessing p.exitValue()
for the process which is still alive.

Add Process#waitFor calls to wait for the process completion.

Bug: 528335
Change-Id: I87e0b6f9ad0b995dbce46ddfb877e33eaf3ae5a6
Signed-off-by: Dmitry Pavlenko <pavlenko@tmatesoft.com>
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2017-12-10 18:00:55 +01:00
Matthias Sohn f0c119de4f Merge branch 'stable-4.9'
* stable-4.9:
  Ignore warning for minor version change without API change
  Silence boxing warning
  Prepare 4.5.5-SNAPSHOT builds
  JGit v4.5.4.201711221230-r
  Fix LockFile semantics when running on NFS
  Honor trustFolderStats also when reading packed-refs
  Prepare 4.5.4-SNAPSHOT builds
  JGit v4.5.3.201708160445-r

Change-Id: Icc33d2e36f140e8714fce088379673a8834ae9de
2017-11-24 01:18:13 +01:00
Matthias Sohn 4ac790fda8 Merge branch 'stable-4.7' into stable-4.8
* stable-4.7:
  Silence boxing warning
  Prepare 4.5.5-SNAPSHOT builds
  JGit v4.5.4.201711221230-r
  Fix LockFile semantics when running on NFS
  Honor trustFolderStats also when reading packed-refs
  Prepare 4.5.4-SNAPSHOT builds
  JGit v4.5.3.201708160445-r

Change-Id: Iaa99ec84594baf733c993c2d6768281ff14f545a
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2017-11-22 23:30:13 +01:00
Matthias Sohn 5f79ef0ba4 Merge branch 'stable-4.6' into stable-4.7
* stable-4.6:
  Silence boxing warning
  Prepare 4.5.5-SNAPSHOT builds
  JGit v4.5.4.201711221230-r
  Fix LockFile semantics when running on NFS
  Honor trustFolderStats also when reading packed-refs
  Prepare 4.5.4-SNAPSHOT builds
  JGit v4.5.3.201708160445-r

Change-Id: I8f6bc09540727c6273d22775a9f9ca382a729c9b
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2017-11-22 23:07:01 +01:00
Matthias Sohn 3ac44f1b38 Merge branch 'stable-4.5' into stable-4.6
* stable-4.5:
  Prepare 4.5.5-SNAPSHOT builds
  JGit v4.5.4.201711221230-r
  Fix LockFile semantics when running on NFS
  Honor trustFolderStats also when reading packed-refs
  Prepare 4.5.4-SNAPSHOT builds
  JGit v4.5.3.201708160445-r

Change-Id: Ie9c8e0d9172c8d53f075c284bf2a9677980d8dfb
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2017-11-22 21:34:08 +01:00
Christian Halstrick 10e65cb4fa Fix LockFile semantics when running on NFS
When running on NFS there was a chance that JGits LockFile
semantic is broken because File#createNewFile() may allow
multiple clients to create the same file in parallel. This
change provides a fix which is only used when the new config
option core.supportsAtomicCreateNewFile is set to false. The
default for this option is true. This option can only be set in the
global or the system config file. The repository config file is not
taken into account in this case.

If the config option core.supportsAtomicCreateNewFile is true
then File#createNewFile() is trusted and the behaviour doesn't
change.

But if core.supportsAtomicCreateNewFile is set to false then after
successful creation of the lock file a hardlink to that lock file is
created and the attribute nlink of the lock file is checked to be 2. If
multiple clients manage to create the same lock file nlink would be
greater than 2 showing the error.

This expensive workaround is described in
 https://www.time-travellers.org/shane/papers/NFS_considered_harmful.html
section III.d) "Exclusive File Creation"

Change-Id: I3d2cc48d8eb280d5f7039eb94da37804f903be6a
2017-11-22 18:15:11 +01:00
Saša Živkov 176466ed28 Move loggers to the top of their class
There is a possibility of hitting NPE on a logger if it is not the first
statically initialized member. For example, if another static
initializer creates an instance of its class and the logger is used
from the constructor.

Change-Id: I51fa855a8883c107f2e4ef5ac039dc12a571a7ae
2017-10-30 04:43:51 -04:00
Bryan Donlan 2204cc9866 Fix null return from FS.readPipe when command fails to launch
When a command invoked from readPipe fails to launch (i.e. the exec call
fails due to a missing command executable), Process.start() throws,
which gets caught by the generic IOException handler, resulting in a
null return. This change detects this case and rethrows a
CommandFailedException instead.

Additionally, this change uses /bin/sh instead of bash for its posix
command failure test, to accomodate building in environments where bash
is unavailable.

Change-Id: Ifae51e457e5718be610c0a0914b18fe35ea7b008
Signed-off-by: Bryan Donlan <bdonlan@gmail.com>
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2017-05-24 23:35:39 +02:00
Dan Willemsen b6fc8e2f3c RepoCommand: Add linkfile support.
Android wants them to work, and we're only interested in them for bare
repos, so add them just for that.

Make sure to use symlinks instead of just using the copyfile
implementation. Some scripts look up where they're actually located in
order to find related files, so they need the link back to their
project.

Change-Id: I929b69b2505f03036f69e25a55daf93842871f30
Signed-off-by: Dan Willemsen <dwillemsen@google.com>
Signed-off-by: Stefan Beller <sbeller@google.com>
Signed-off-by: Jeff Gaston <jeffrygaston@google.com>
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2017-04-18 10:33:37 +02:00
David Pursehouse 3b4448637f Enable and fix warnings about redundant specification of type arguments
Since the introduction of generic type parameter inference in Java 7,
it's not necessary to explicitly specify the type of generic parameters.

Enable the warning in Eclipse, and fix all occurrences.

Change-Id: I9158caf1beca5e4980b6240ac401f3868520aad0
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2017-02-20 22:47:23 +01:00
David Pursehouse 7ac182f4e4 Enable and fix 'Should be tagged with @Override' warning
Set missingOverrideAnnotation=warning in Eclipse compiler preferences
which enables the warning:

  The method <method> of type <type> should be tagged with @Override
  since it actually overrides a superclass method

Justification for this warning is described in:

  http://stackoverflow.com/a/94411/381622

Enabling this causes in excess of 1000 warnings across the entire
code-base. They are very easy to fix automatically with Eclipse's
"Quick Fix" tool.

Fix all of them except 2 which cause compilation failure when the
project is built with mvn; add TODO comments on those for further
investigation.

Change-Id: I5772061041fd361fe93137fd8b0ad356e748a29c
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2017-02-19 20:05:08 -04:00
Shawn Pearce 131b09106f Change StreamGobbler to Runnable to avoid unused Future
It can be considered a programming error to create a Future<T>
but do nothing with that object. There is an async computation
happening and without holding and checking the Future for done
or exception the caller has no idea if it has completed.

FS doesn't really care about these StreamGobblers finishing.
Instead use Runnable with execute(Runnable), which doesn't
return a Future.

Change-Id: I93b66d1f6c869e66be5c1169d8edafe781e601f6
2017-01-21 09:44:14 +01:00
David Pursehouse bdf3e43d76 FS: Fix lazy initialization of non-volatile static field
The 'factory' field is lazy initialized in the detect() method.

According to FindBugs:

   Because the compiler or processor may reorder instructions, threads
   are not guaranteed to see a completely initialized object, if the
   method can be called by multiple threads.

Fix this by declaring the member as 'volatile'.

Change-Id: Ib32663bb28c9564584256e01f625b4e7875e6223
Signed-off-by: David Pursehouse <david.pursehouse@gmail.com>
2016-10-18 14:15:53 +09:00
Matthias Sohn abeaafc9c7 Don't log error if system git config does not exist
- enhance FS.readPipe to throw an exception if the external command
fails to enable the caller to handle the command failure
- reduce log level to warning if system git config does not exist
- improve log message 

Bug: 476639
Change-Id: I94ae3caec22150dde81f1ea8e1e665df55290d42
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2016-09-05 17:41:36 +02:00
Masaya Suzuki 108bee17cf Ignore IOException thrown from close
AddCommandTest is flaky because IOException is thrown sometimes.

Caused by: java.io.IOException: Stream closed
        at java.lang.ProcessBuilder$NullOutputStream.write(ProcessBuilder.java:433)
        at java.io.OutputStream.write(OutputStream.java:116)
        at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
        at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
        at java.io.FilterOutputStream.close(FilterOutputStream.java:158)
        at org.eclipse.jgit.util.FS.runProcess(FS.java:993)
        at org.eclipse.jgit.util.FS.execute(FS.java:1102)
        at org.eclipse.jgit.treewalk.WorkingTreeIterator.filterClean(WorkingTreeIterator.java:470)
        ... 22 more

OpenJDK replaces the underlying OutputStream with NullOutputStream when
the process exits. This throws IOException for all write operation. When
it exits before JGit writes the input to the pipe buffer, the input
stays in BufferedOutputStream. The close method tries to write it again,
and IOException is thrown.

Since we ignore IOException in StreamGobbler, we also ignore it when
we close the stream.

Fixes Bug 499633.

Change-Id: I30c7ac78e05b00bd0152f697848f4d17d53efd17
Signed-off-by: Masaya Suzuki <draftcode@gmail.com>
2016-08-19 14:09:17 -07:00
Christian Halstrick 55fb18feaa Fix FS.runProcess() to close the InputStream
When FS.runProcess was called and an InputStream was given the method
tried to pump the whole InputStream to the process. When the method
ended the InputStream was not giving any data anymore. Consequently
close the InputStream inside the method.

Change-Id: I0ed738a775e5c977b21447d195acee1ecf5e2cb9
2015-11-26 00:36:09 +01:00
Christian Halstrick 69cd6f5864 Introduce FS.execute() to execute a command defined by a ProcessBuilder
Change-Id: I2ad2c71ad30b969455bdea89637b8e996b1dad8c
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2015-11-18 00:28:45 +01:00
Terry Parker 6ddb8e703b Use the JGit-internal @Nullable annotation
Update existing @Nullable uses to use the JGit-internal version of the
annotation. 

Change-Id: I95234ffad4c3110f9597fbd3a2760f653e22ecf7
Signed-off-by: Terry Parker <tparker@google.com>
2015-11-09 14:27:52 -08:00
Christian Halstrick 67a77d402a Enhance FS.runProcess() to support stdin-redirection and binary data
In order to support filters in gitattributes FS.runProcess() is made
public. Support for stdin redirection has been added. Support for binary
data on stdin/stdout (as used be clean/smudge filters) has been added.

Change-Id: Ice2c152e9391368dc5748d7b825a838e3eb755f9
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2015-11-02 22:19:47 +01:00
Andrey Loskutov 8473bc4f8d Cleaned up various readPipe() threading issues
Fixed random errors in discoverGitSystemConfig() on Linux where the
process error stream was closed by readPipe() before or while
GobblerThread was reading from it.

Marked readPipe() as @Nullable and fixed potential NPE in
discoverGitSystemConfig() on readPipe() return value.

Fixed process error output randomly mixed with other threads log
messages.

Change-Id: Id882af2762cfb75f010f693b2e1c46eb6968ee82
Signed-off-by: Andrey Loskutov <loskutov@gmx.de>
2015-11-01 14:03:52 +01:00
Andrey Loskutov 3601c8cdf1 Don't report errors logged by FS with "debug" level
Change-Id: I6a10116cd2e6b58d2300a9e741afe2eeac719b03
Signed-off-by: Andrey Loskutov <loskutov@gmx.de>
2015-10-31 00:06:27 +01:00
Kaloyan Raev 8a53d7e2fd JGit CLI should check if calling itself when invoking native git exe
Bug: 480782
Change-Id: I0d7f7a648671e7ff678f2b19fe39b85f8835c061
Signed-off-by: Kaloyan Raev <kaloyan.r@zend.com>
2015-10-29 04:35:58 -04:00
Andrey Loskutov 260e092e79 [performance] Remove synthetic access$ methods in lib, util and dircache
Java compiler must generate synthetic access methods for private methods
and fields of the enclosing class if they are accessed from inner
classes and vice versa.

While invisible in the code, those synthetic access methods exist in the
bytecode and seem to produce some extra execution overhead at runtime
(compared with the direct access to this fields or methods), see
https://git.eclipse.org/r/58948/.

By removing the "private" access modifier from affected methods and
fields we help compiler to avoid generation of synthetic access methods
and hope to improve execution performance.

To validate changes, one can either use javap or use Bytecode Outline
plugin in Eclipse. In both cases one should look for "synthetic
access$<number>" methods at the end of the class and inner class files
in question - there should be none.

NB: don't mix this "synthetic access$" methods up with "public synthetic
bridge" methods generated to allow generic method override return types.

Change-Id: Ie7b65f251ec4452d5a5ed48aa0f272cf49a9aecd
Signed-off-by: Andrey Loskutov <loskutov@gmx.de>
2015-10-28 20:52:43 +01:00
Matthias Sohn 9e5380e7fb Use java.nio.file consistently in FS
Since 4.0 we require Java 7 so there is no longer a need to override the
following methods in FS_POSIX, FS_Win32, FS_Win32_Cygwin
- lastModified()
- setLastModified()
- length()
- isSymlink()
- exists()
- isDirectory()
- isFile()
- isHidden()
Hence implement these methods in FS and remove overrides in subclasses.

Change-Id: I5dbde6ec806c66c86ac542978918361461021294
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2015-09-27 22:24:06 +02:00
Andrey Loskutov 35d45abfb2 Deprecate redundant FileUtil.delete(File), use FileUtils instead
Bug: 475070
Change-Id: I6dc651f4b47e1b2c8d7954ec982e21ae6bb5f7a6
Signed-off-by: Andrey Loskutov <loskutov@gmx.de>
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2015-08-26 23:25:38 +02:00
Andrey Loskutov 2e5c7c5db4 Move createSymLink/readSymLink to FileUtils
Bug: 475070
Change-Id: I258f4bf291e02ef8e6f867b5d71c04ec902b6bcb
Signed-off-by: Andrey Loskutov <loskutov@gmx.de>
2015-08-17 16:06:15 +02:00
Christian Halstrick d0d637342b Change FS not to throw NPE when facing InMemory databases
The FS class and the subclasses FS_POSIX assumed in the findHook()
method that every repository has a valid gitDir. But in tests when using
in-memory-repositories this is not true and this method was generating
NPEs. Change the method to return null if no repository directory can be
determined.

Change-Id: I38a4d36dc6452b5dacae3d0dbf562b569ca3c19b
2015-08-16 22:20:06 +02:00
Andrey Loskutov bfc3e1262c Cleanup Attributes and remove obsoleted Java7BasicAttributes class
After jgit moved to Java 7 there is no need in an extra
Java7BasicAttributes class. Also all fields of Attributes can be made
final now.

Change-Id: I0be6daf7758189b0eecc4e26294bd278ed8bf7a0
Signed-off-by: Andrey Loskutov <loskutov@gmx.de>
2015-08-13 15:12:05 -04:00
Dave Borowitz b8c8008115 FS: Extract GobblerThread into a private static class
The primary goal is to improve exception readability. Since this is a
standalone thread, just logging the stack trace of the caught
exception is not very useful:

java.io.IOException: Stream closed
	at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:162)
	at java.io.BufferedInputStream.read(BufferedInputStream.java:258)
	at org.eclipse.jgit.util.FS$2.run(FS.java:451)

Providing a named class eliminates the "FS$2", and including the
command name provides a little more context in the error message.
A future improvement might include the stack trace that created the
GobblerThread as well.

Change-Id: Ibf16d15b47a85b6f41844a177e398c2fc94f27b0
2015-05-27 10:04:35 -07:00
Matthias Sohn 2390531888 Externalize translatable texts in org.eclipse.jgit
Change-Id: Ibf4c299f9d203c78cae79e61f88d4bea60ea2795
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
2015-05-26 10:52:20 +02:00
Sebastian Schuberth 7ce6abe858 FS: Allow to manually set the path to the Git system config file
Now that d7a4473 removed the gitprefix property, we did not have a way to
specify the path to the Git system config file in case
discoverGitSystemConfig() fails. Fix that by introducing a member variable
that caches the result of discoverGitSystemConfig() as well as a setter
method to overwrite the content of that variable.

Change-Id: Icd965bffbe2f11b18c9505ee2ddd2afad5b64d70
Signed-off-by: Sebastian Schuberth <sschuberth@gmail.com>
2015-05-25 21:23:21 +02:00