You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FS.java 69KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291
  1. /*
  2. * Copyright (C) 2008, 2020 Shawn O. Pearce <spearce@spearce.org> and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.util;
  11. import static java.nio.charset.StandardCharsets.UTF_8;
  12. import static java.time.Instant.EPOCH;
  13. import java.io.BufferedReader;
  14. import java.io.ByteArrayInputStream;
  15. import java.io.Closeable;
  16. import java.io.File;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.InputStreamReader;
  20. import java.io.OutputStream;
  21. import java.io.OutputStreamWriter;
  22. import java.io.PrintStream;
  23. import java.io.Writer;
  24. import java.nio.charset.Charset;
  25. import java.nio.file.AccessDeniedException;
  26. import java.nio.file.FileStore;
  27. import java.nio.file.Files;
  28. import java.nio.file.InvalidPathException;
  29. import java.nio.file.Path;
  30. import java.nio.file.attribute.BasicFileAttributes;
  31. import java.nio.file.attribute.FileTime;
  32. import java.security.AccessControlException;
  33. import java.security.AccessController;
  34. import java.security.PrivilegedAction;
  35. import java.text.MessageFormat;
  36. import java.time.Duration;
  37. import java.time.Instant;
  38. import java.util.ArrayList;
  39. import java.util.Arrays;
  40. import java.util.HashMap;
  41. import java.util.Map;
  42. import java.util.Objects;
  43. import java.util.Optional;
  44. import java.util.UUID;
  45. import java.util.concurrent.CancellationException;
  46. import java.util.concurrent.CompletableFuture;
  47. import java.util.concurrent.ConcurrentHashMap;
  48. import java.util.concurrent.ExecutionException;
  49. import java.util.concurrent.Executor;
  50. import java.util.concurrent.ExecutorService;
  51. import java.util.concurrent.Executors;
  52. import java.util.concurrent.SynchronousQueue;
  53. import java.util.concurrent.ThreadPoolExecutor;
  54. import java.util.concurrent.TimeUnit;
  55. import java.util.concurrent.TimeoutException;
  56. import java.util.concurrent.atomic.AtomicBoolean;
  57. import java.util.concurrent.atomic.AtomicInteger;
  58. import java.util.concurrent.atomic.AtomicReference;
  59. import java.util.concurrent.locks.Lock;
  60. import java.util.concurrent.locks.ReentrantLock;
  61. import org.eclipse.jgit.annotations.NonNull;
  62. import org.eclipse.jgit.annotations.Nullable;
  63. import org.eclipse.jgit.api.errors.JGitInternalException;
  64. import org.eclipse.jgit.errors.CommandFailedException;
  65. import org.eclipse.jgit.errors.ConfigInvalidException;
  66. import org.eclipse.jgit.errors.LockFailedException;
  67. import org.eclipse.jgit.internal.JGitText;
  68. import org.eclipse.jgit.internal.storage.file.FileSnapshot;
  69. import org.eclipse.jgit.lib.Config;
  70. import org.eclipse.jgit.lib.ConfigConstants;
  71. import org.eclipse.jgit.lib.Constants;
  72. import org.eclipse.jgit.lib.Repository;
  73. import org.eclipse.jgit.lib.StoredConfig;
  74. import org.eclipse.jgit.treewalk.FileTreeIterator.FileEntry;
  75. import org.eclipse.jgit.treewalk.FileTreeIterator.FileModeStrategy;
  76. import org.eclipse.jgit.treewalk.WorkingTreeIterator.Entry;
  77. import org.eclipse.jgit.util.ProcessResult.Status;
  78. import org.slf4j.Logger;
  79. import org.slf4j.LoggerFactory;
  80. /**
  81. * Abstraction to support various file system operations not in Java.
  82. */
  83. public abstract class FS {
  84. private static final Logger LOG = LoggerFactory.getLogger(FS.class);
  85. /**
  86. * An empty array of entries, suitable as a return value for
  87. * {@link #list(File, FileModeStrategy)}.
  88. *
  89. * @since 5.0
  90. */
  91. protected static final Entry[] NO_ENTRIES = {};
  92. private volatile Boolean supportSymlinks;
  93. /**
  94. * This class creates FS instances. It will be overridden by a Java7 variant
  95. * if such can be detected in {@link #detect(Boolean)}.
  96. *
  97. * @since 3.0
  98. */
  99. public static class FSFactory {
  100. /**
  101. * Constructor
  102. */
  103. protected FSFactory() {
  104. // empty
  105. }
  106. /**
  107. * Detect the file system
  108. *
  109. * @param cygwinUsed
  110. * @return FS instance
  111. */
  112. public FS detect(Boolean cygwinUsed) {
  113. if (SystemReader.getInstance().isWindows()) {
  114. if (cygwinUsed == null) {
  115. cygwinUsed = Boolean.valueOf(FS_Win32_Cygwin.isCygwin());
  116. }
  117. if (cygwinUsed.booleanValue()) {
  118. return new FS_Win32_Cygwin();
  119. }
  120. return new FS_Win32();
  121. }
  122. return new FS_POSIX();
  123. }
  124. }
  125. /**
  126. * Result of an executed process. The caller is responsible to close the
  127. * contained {@link TemporaryBuffer}s
  128. *
  129. * @since 4.2
  130. */
  131. public static class ExecutionResult {
  132. private TemporaryBuffer stdout;
  133. private TemporaryBuffer stderr;
  134. private int rc;
  135. /**
  136. * @param stdout
  137. * @param stderr
  138. * @param rc
  139. */
  140. public ExecutionResult(TemporaryBuffer stdout, TemporaryBuffer stderr,
  141. int rc) {
  142. this.stdout = stdout;
  143. this.stderr = stderr;
  144. this.rc = rc;
  145. }
  146. /**
  147. * @return buffered standard output stream
  148. */
  149. public TemporaryBuffer getStdout() {
  150. return stdout;
  151. }
  152. /**
  153. * @return buffered standard error stream
  154. */
  155. public TemporaryBuffer getStderr() {
  156. return stderr;
  157. }
  158. /**
  159. * @return the return code of the process
  160. */
  161. public int getRc() {
  162. return rc;
  163. }
  164. }
  165. /**
  166. * Attributes of FileStores on this system
  167. *
  168. * @since 5.1.9
  169. */
  170. public final static class FileStoreAttributes {
  171. private static final Duration UNDEFINED_DURATION = Duration
  172. .ofNanos(Long.MAX_VALUE);
  173. /**
  174. * Fallback filesystem timestamp resolution. The worst case timestamp
  175. * resolution on FAT filesystems is 2 seconds.
  176. */
  177. public static final Duration FALLBACK_TIMESTAMP_RESOLUTION = Duration
  178. .ofMillis(2000);
  179. /**
  180. * Fallback FileStore attributes used when we can't measure the
  181. * filesystem timestamp resolution. The last modified time granularity
  182. * of FAT filesystems is 2 seconds.
  183. */
  184. public static final FileStoreAttributes FALLBACK_FILESTORE_ATTRIBUTES = new FileStoreAttributes(
  185. FALLBACK_TIMESTAMP_RESOLUTION);
  186. private static final Map<FileStore, FileStoreAttributes> attributeCache = new ConcurrentHashMap<>();
  187. private static final SimpleLruCache<Path, FileStoreAttributes> attrCacheByPath = new SimpleLruCache<>(
  188. 100, 0.2f);
  189. private static AtomicBoolean background = new AtomicBoolean();
  190. private static Map<FileStore, Lock> locks = new ConcurrentHashMap<>();
  191. private static void setBackground(boolean async) {
  192. background.set(async);
  193. }
  194. private static final String javaVersionPrefix = SystemReader
  195. .getInstance().getHostname() + '|'
  196. + System.getProperty("java.vendor") + '|' //$NON-NLS-1$
  197. + System.getProperty("java.version") + '|'; //$NON-NLS-1$
  198. private static final Duration FALLBACK_MIN_RACY_INTERVAL = Duration
  199. .ofMillis(10);
  200. private static final AtomicInteger threadNumber = new AtomicInteger(1);
  201. /**
  202. * Don't use the default thread factory of the ForkJoinPool for the
  203. * CompletableFuture; it runs without any privileges, which causes
  204. * trouble if a SecurityManager is present.
  205. * <p>
  206. * Instead use normal daemon threads. They'll belong to the
  207. * SecurityManager's thread group, or use the one of the calling thread,
  208. * as appropriate.
  209. * </p>
  210. *
  211. * @see java.util.concurrent.Executors#newCachedThreadPool()
  212. */
  213. private static final Executor FUTURE_RUNNER = new ThreadPoolExecutor(0,
  214. 5, 30L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
  215. runnable -> {
  216. Thread t = new Thread(runnable, "FileStoreAttributeReader-" //$NON-NLS-1$
  217. + threadNumber.getAndIncrement());
  218. // Make sure these threads don't prevent application/JVM
  219. // shutdown.
  220. t.setDaemon(true);
  221. return t;
  222. });
  223. /**
  224. * Configures size and purge factor of the path-based cache for file
  225. * system attributes. Caching of file system attributes avoids recurring
  226. * lookup of @{code FileStore} of files which may be expensive on some
  227. * platforms.
  228. *
  229. * @param maxSize
  230. * maximum size of the cache, default is 100
  231. * @param purgeFactor
  232. * when the size of the map reaches maxSize the oldest
  233. * entries will be purged to free up some space for new
  234. * entries, {@code purgeFactor} is the fraction of
  235. * {@code maxSize} to purge when this happens
  236. * @since 5.1.9
  237. */
  238. public static void configureAttributesPathCache(int maxSize,
  239. float purgeFactor) {
  240. FileStoreAttributes.attrCacheByPath.configure(maxSize, purgeFactor);
  241. }
  242. /**
  243. * Get the FileStoreAttributes for the given FileStore
  244. *
  245. * @param path
  246. * file residing in the FileStore to get attributes for
  247. * @return FileStoreAttributes for the given path.
  248. */
  249. public static FileStoreAttributes get(Path path) {
  250. try {
  251. path = path.toAbsolutePath();
  252. Path dir = Files.isDirectory(path) ? path : path.getParent();
  253. FileStoreAttributes cached = attrCacheByPath.get(dir);
  254. if (cached != null) {
  255. return cached;
  256. }
  257. FileStoreAttributes attrs = getFileStoreAttributes(dir);
  258. attrCacheByPath.put(dir, attrs);
  259. return attrs;
  260. } catch (SecurityException e) {
  261. return FALLBACK_FILESTORE_ATTRIBUTES;
  262. }
  263. }
  264. private static FileStoreAttributes getFileStoreAttributes(Path dir) {
  265. FileStore s;
  266. try {
  267. if (Files.exists(dir)) {
  268. s = Files.getFileStore(dir);
  269. FileStoreAttributes c = attributeCache.get(s);
  270. if (c != null) {
  271. return c;
  272. }
  273. if (!Files.isWritable(dir)) {
  274. // cannot measure resolution in a read-only directory
  275. LOG.debug(
  276. "{}: cannot measure timestamp resolution in read-only directory {}", //$NON-NLS-1$
  277. Thread.currentThread(), dir);
  278. return FALLBACK_FILESTORE_ATTRIBUTES;
  279. }
  280. } else {
  281. // cannot determine FileStore of an unborn directory
  282. LOG.debug(
  283. "{}: cannot measure timestamp resolution of unborn directory {}", //$NON-NLS-1$
  284. Thread.currentThread(), dir);
  285. return FALLBACK_FILESTORE_ATTRIBUTES;
  286. }
  287. CompletableFuture<Optional<FileStoreAttributes>> f = CompletableFuture
  288. .supplyAsync(() -> {
  289. Lock lock = locks.computeIfAbsent(s,
  290. l -> new ReentrantLock());
  291. if (!lock.tryLock()) {
  292. LOG.debug(
  293. "{}: couldn't get lock to measure timestamp resolution in {}", //$NON-NLS-1$
  294. Thread.currentThread(), dir);
  295. return Optional.empty();
  296. }
  297. Optional<FileStoreAttributes> attributes = Optional
  298. .empty();
  299. try {
  300. // Some earlier future might have set the value
  301. // and removed itself since we checked for the
  302. // value above. Hence check cache again.
  303. FileStoreAttributes c = attributeCache.get(s);
  304. if (c != null) {
  305. return Optional.of(c);
  306. }
  307. attributes = readFromConfig(s);
  308. if (attributes.isPresent()) {
  309. attributeCache.put(s, attributes.get());
  310. return attributes;
  311. }
  312. Optional<Duration> resolution = measureFsTimestampResolution(
  313. s, dir);
  314. if (resolution.isPresent()) {
  315. c = new FileStoreAttributes(
  316. resolution.get());
  317. attributeCache.put(s, c);
  318. // for high timestamp resolution measure
  319. // minimal racy interval
  320. if (c.fsTimestampResolution
  321. .toNanos() < 100_000_000L) {
  322. c.minimalRacyInterval = measureMinimalRacyInterval(
  323. dir);
  324. }
  325. if (LOG.isDebugEnabled()) {
  326. LOG.debug(c.toString());
  327. }
  328. saveToConfig(s, c);
  329. }
  330. attributes = Optional.of(c);
  331. } finally {
  332. lock.unlock();
  333. locks.remove(s);
  334. }
  335. return attributes;
  336. }, FUTURE_RUNNER);
  337. f = f.exceptionally(e -> {
  338. LOG.error(e.getLocalizedMessage(), e);
  339. return Optional.empty();
  340. });
  341. // even if measuring in background wait a little - if the result
  342. // arrives, it's better than returning the large fallback
  343. Optional<FileStoreAttributes> d = background.get() ? f.get(
  344. 100, TimeUnit.MILLISECONDS) : f.get();
  345. if (d.isPresent()) {
  346. return d.get();
  347. }
  348. // return fallback until measurement is finished
  349. } catch (IOException | InterruptedException
  350. | ExecutionException | CancellationException e) {
  351. LOG.error(e.getMessage(), e);
  352. } catch (TimeoutException | SecurityException e) {
  353. // use fallback
  354. }
  355. LOG.debug("{}: use fallback timestamp resolution for directory {}", //$NON-NLS-1$
  356. Thread.currentThread(), dir);
  357. return FALLBACK_FILESTORE_ATTRIBUTES;
  358. }
  359. @SuppressWarnings("boxing")
  360. private static Duration measureMinimalRacyInterval(Path dir) {
  361. LOG.debug("{}: start measure minimal racy interval in {}", //$NON-NLS-1$
  362. Thread.currentThread(), dir);
  363. int n = 0;
  364. int failures = 0;
  365. long racyNanos = 0;
  366. ArrayList<Long> deltas = new ArrayList<>();
  367. Path probe = dir.resolve(".probe-" + UUID.randomUUID()); //$NON-NLS-1$
  368. Instant end = Instant.now().plusSeconds(3);
  369. try {
  370. Files.createFile(probe);
  371. do {
  372. n++;
  373. write(probe, "a"); //$NON-NLS-1$
  374. FileSnapshot snapshot = FileSnapshot.save(probe.toFile());
  375. read(probe);
  376. write(probe, "b"); //$NON-NLS-1$
  377. if (!snapshot.isModified(probe.toFile())) {
  378. deltas.add(Long.valueOf(snapshot.lastDelta()));
  379. racyNanos = snapshot.lastRacyThreshold();
  380. failures++;
  381. }
  382. } while (Instant.now().compareTo(end) < 0);
  383. } catch (IOException e) {
  384. LOG.error(e.getMessage(), e);
  385. return FALLBACK_MIN_RACY_INTERVAL;
  386. } finally {
  387. deleteProbe(probe);
  388. }
  389. if (failures > 0) {
  390. Stats stats = new Stats();
  391. for (Long d : deltas) {
  392. stats.add(d);
  393. }
  394. LOG.debug(
  395. "delta [ns] since modification FileSnapshot failed to detect\n" //$NON-NLS-1$
  396. + "count, failures, racy limit [ns], delta min [ns]," //$NON-NLS-1$
  397. + " delta max [ns], delta avg [ns]," //$NON-NLS-1$
  398. + " delta stddev [ns]\n" //$NON-NLS-1$
  399. + "{}, {}, {}, {}, {}, {}, {}", //$NON-NLS-1$
  400. n, failures, racyNanos, stats.min(), stats.max(),
  401. stats.avg(), stats.stddev());
  402. return Duration
  403. .ofNanos(Double.valueOf(stats.max()).longValue());
  404. }
  405. // since no failures occurred using the measured filesystem
  406. // timestamp resolution there is no need for minimal racy interval
  407. LOG.debug("{}: no failures when measuring minimal racy interval", //$NON-NLS-1$
  408. Thread.currentThread());
  409. return Duration.ZERO;
  410. }
  411. private static void write(Path p, String body) throws IOException {
  412. FileUtils.mkdirs(p.getParent().toFile(), true);
  413. try (Writer w = new OutputStreamWriter(Files.newOutputStream(p),
  414. UTF_8)) {
  415. w.write(body);
  416. }
  417. }
  418. private static String read(Path p) throws IOException {
  419. final byte[] body = IO.readFully(p.toFile());
  420. return new String(body, 0, body.length, UTF_8);
  421. }
  422. private static Optional<Duration> measureFsTimestampResolution(
  423. FileStore s, Path dir) {
  424. LOG.debug("{}: start measure timestamp resolution {} in {}", //$NON-NLS-1$
  425. Thread.currentThread(), s, dir);
  426. Path probe = dir.resolve(".probe-" + UUID.randomUUID()); //$NON-NLS-1$
  427. try {
  428. Files.createFile(probe);
  429. FileTime t1 = Files.getLastModifiedTime(probe);
  430. FileTime t2 = t1;
  431. Instant t1i = t1.toInstant();
  432. for (long i = 1; t2.compareTo(t1) <= 0; i += 1 + i / 20) {
  433. Files.setLastModifiedTime(probe,
  434. FileTime.from(t1i.plusNanos(i * 1000)));
  435. t2 = Files.getLastModifiedTime(probe);
  436. }
  437. Duration fsResolution = Duration.between(t1.toInstant(), t2.toInstant());
  438. Duration clockResolution = measureClockResolution();
  439. fsResolution = fsResolution.plus(clockResolution);
  440. LOG.debug("{}: end measure timestamp resolution {} in {}", //$NON-NLS-1$
  441. Thread.currentThread(), s, dir);
  442. return Optional.of(fsResolution);
  443. } catch (SecurityException e) {
  444. // Log it here; most likely deleteProbe() below will also run
  445. // into a SecurityException, and then this one will be lost
  446. // without trace.
  447. LOG.warn(e.getLocalizedMessage(), e);
  448. } catch (AccessDeniedException e) {
  449. LOG.warn(e.getLocalizedMessage(), e); // see bug 548648
  450. } catch (IOException e) {
  451. LOG.error(e.getLocalizedMessage(), e);
  452. } finally {
  453. deleteProbe(probe);
  454. }
  455. return Optional.empty();
  456. }
  457. private static Duration measureClockResolution() {
  458. Duration clockResolution = Duration.ZERO;
  459. for (int i = 0; i < 10; i++) {
  460. Instant t1 = Instant.now();
  461. Instant t2 = t1;
  462. while (t2.compareTo(t1) <= 0) {
  463. t2 = Instant.now();
  464. }
  465. Duration r = Duration.between(t1, t2);
  466. if (r.compareTo(clockResolution) > 0) {
  467. clockResolution = r;
  468. }
  469. }
  470. return clockResolution;
  471. }
  472. private static void deleteProbe(Path probe) {
  473. try {
  474. FileUtils.delete(probe.toFile(),
  475. FileUtils.SKIP_MISSING | FileUtils.RETRY);
  476. } catch (IOException e) {
  477. LOG.error(e.getMessage(), e);
  478. }
  479. }
  480. private static Optional<FileStoreAttributes> readFromConfig(
  481. FileStore s) {
  482. StoredConfig userConfig;
  483. try {
  484. userConfig = SystemReader.getInstance().getUserConfig();
  485. } catch (IOException | ConfigInvalidException e) {
  486. LOG.error(JGitText.get().readFileStoreAttributesFailed, e);
  487. return Optional.empty();
  488. }
  489. String key = getConfigKey(s);
  490. Duration resolution = Duration.ofNanos(userConfig.getTimeUnit(
  491. ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
  492. ConfigConstants.CONFIG_KEY_TIMESTAMP_RESOLUTION,
  493. UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS));
  494. if (UNDEFINED_DURATION.equals(resolution)) {
  495. return Optional.empty();
  496. }
  497. Duration minRacyThreshold = Duration.ofNanos(userConfig.getTimeUnit(
  498. ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
  499. ConfigConstants.CONFIG_KEY_MIN_RACY_THRESHOLD,
  500. UNDEFINED_DURATION.toNanos(), TimeUnit.NANOSECONDS));
  501. FileStoreAttributes c = new FileStoreAttributes(resolution);
  502. if (!UNDEFINED_DURATION.equals(minRacyThreshold)) {
  503. c.minimalRacyInterval = minRacyThreshold;
  504. }
  505. return Optional.of(c);
  506. }
  507. private static void saveToConfig(FileStore s,
  508. FileStoreAttributes c) {
  509. StoredConfig jgitConfig;
  510. try {
  511. jgitConfig = SystemReader.getInstance().getJGitConfig();
  512. } catch (IOException | ConfigInvalidException e) {
  513. LOG.error(JGitText.get().saveFileStoreAttributesFailed, e);
  514. return;
  515. }
  516. long resolution = c.getFsTimestampResolution().toNanos();
  517. TimeUnit resolutionUnit = getUnit(resolution);
  518. long resolutionValue = resolutionUnit.convert(resolution,
  519. TimeUnit.NANOSECONDS);
  520. long minRacyThreshold = c.getMinimalRacyInterval().toNanos();
  521. TimeUnit minRacyThresholdUnit = getUnit(minRacyThreshold);
  522. long minRacyThresholdValue = minRacyThresholdUnit
  523. .convert(minRacyThreshold, TimeUnit.NANOSECONDS);
  524. final int max_retries = 5;
  525. int retries = 0;
  526. boolean succeeded = false;
  527. String key = getConfigKey(s);
  528. while (!succeeded && retries < max_retries) {
  529. try {
  530. jgitConfig.setString(
  531. ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
  532. ConfigConstants.CONFIG_KEY_TIMESTAMP_RESOLUTION,
  533. String.format("%d %s", //$NON-NLS-1$
  534. Long.valueOf(resolutionValue),
  535. resolutionUnit.name().toLowerCase()));
  536. jgitConfig.setString(
  537. ConfigConstants.CONFIG_FILESYSTEM_SECTION, key,
  538. ConfigConstants.CONFIG_KEY_MIN_RACY_THRESHOLD,
  539. String.format("%d %s", //$NON-NLS-1$
  540. Long.valueOf(minRacyThresholdValue),
  541. minRacyThresholdUnit.name().toLowerCase()));
  542. jgitConfig.save();
  543. succeeded = true;
  544. } catch (LockFailedException e) {
  545. // race with another thread, wait a bit and try again
  546. try {
  547. retries++;
  548. if (retries < max_retries) {
  549. Thread.sleep(100);
  550. LOG.debug("locking {} failed, retries {}/{}", //$NON-NLS-1$
  551. jgitConfig, Integer.valueOf(retries),
  552. Integer.valueOf(max_retries));
  553. } else {
  554. LOG.warn(MessageFormat.format(
  555. JGitText.get().lockFailedRetry, jgitConfig,
  556. Integer.valueOf(retries)));
  557. }
  558. } catch (InterruptedException e1) {
  559. Thread.currentThread().interrupt();
  560. break;
  561. }
  562. } catch (IOException e) {
  563. LOG.error(MessageFormat.format(
  564. JGitText.get().cannotSaveConfig, jgitConfig), e);
  565. break;
  566. }
  567. }
  568. }
  569. private static String getConfigKey(FileStore s) {
  570. final String storeKey;
  571. if (SystemReader.getInstance().isWindows()) {
  572. Object attribute = null;
  573. try {
  574. attribute = s.getAttribute("volume:vsn"); //$NON-NLS-1$
  575. } catch (IOException ignored) {
  576. // ignore
  577. }
  578. if (attribute instanceof Integer) {
  579. storeKey = attribute.toString();
  580. } else {
  581. storeKey = s.name();
  582. }
  583. } else {
  584. storeKey = s.name();
  585. }
  586. return javaVersionPrefix + storeKey;
  587. }
  588. private static TimeUnit getUnit(long nanos) {
  589. TimeUnit unit;
  590. if (nanos < 200_000L) {
  591. unit = TimeUnit.NANOSECONDS;
  592. } else if (nanos < 200_000_000L) {
  593. unit = TimeUnit.MICROSECONDS;
  594. } else {
  595. unit = TimeUnit.MILLISECONDS;
  596. }
  597. return unit;
  598. }
  599. private final @NonNull Duration fsTimestampResolution;
  600. private Duration minimalRacyInterval;
  601. /**
  602. * @return the measured minimal interval after a file has been modified
  603. * in which we cannot rely on lastModified to detect
  604. * modifications
  605. */
  606. public Duration getMinimalRacyInterval() {
  607. return minimalRacyInterval;
  608. }
  609. /**
  610. * @return the measured filesystem timestamp resolution
  611. */
  612. @NonNull
  613. public Duration getFsTimestampResolution() {
  614. return fsTimestampResolution;
  615. }
  616. /**
  617. * Construct a FileStoreAttributeCache entry for the given filesystem
  618. * timestamp resolution
  619. *
  620. * @param fsTimestampResolution
  621. */
  622. public FileStoreAttributes(
  623. @NonNull Duration fsTimestampResolution) {
  624. this.fsTimestampResolution = fsTimestampResolution;
  625. this.minimalRacyInterval = Duration.ZERO;
  626. }
  627. @SuppressWarnings({ "nls", "boxing" })
  628. @Override
  629. public String toString() {
  630. return String.format(
  631. "FileStoreAttributes[fsTimestampResolution=%,d µs, "
  632. + "minimalRacyInterval=%,d µs]",
  633. fsTimestampResolution.toNanos() / 1000,
  634. minimalRacyInterval.toNanos() / 1000);
  635. }
  636. }
  637. /** The auto-detected implementation selected for this operating system and JRE. */
  638. public static final FS DETECTED = detect();
  639. private volatile static FSFactory factory;
  640. /**
  641. * Auto-detect the appropriate file system abstraction.
  642. *
  643. * @return detected file system abstraction
  644. */
  645. public static FS detect() {
  646. return detect(null);
  647. }
  648. /**
  649. * Whether FileStore attributes should be determined asynchronously
  650. *
  651. * @param asynch
  652. * whether FileStore attributes should be determined
  653. * asynchronously. If false access to cached attributes may block
  654. * for some seconds for the first call per FileStore
  655. * @since 5.1.9
  656. */
  657. public static void setAsyncFileStoreAttributes(boolean asynch) {
  658. FileStoreAttributes.setBackground(asynch);
  659. }
  660. /**
  661. * Auto-detect the appropriate file system abstraction, taking into account
  662. * the presence of a Cygwin installation on the system. Using jgit in
  663. * combination with Cygwin requires a more elaborate (and possibly slower)
  664. * resolution of file system paths.
  665. *
  666. * @param cygwinUsed
  667. * <ul>
  668. * <li><code>Boolean.TRUE</code> to assume that Cygwin is used in
  669. * combination with jgit</li>
  670. * <li><code>Boolean.FALSE</code> to assume that Cygwin is
  671. * <b>not</b> used with jgit</li>
  672. * <li><code>null</code> to auto-detect whether a Cygwin
  673. * installation is present on the system and in this case assume
  674. * that Cygwin is used</li>
  675. * </ul>
  676. *
  677. * Note: this parameter is only relevant on Windows.
  678. * @return detected file system abstraction
  679. */
  680. public static FS detect(Boolean cygwinUsed) {
  681. if (factory == null) {
  682. factory = new FS.FSFactory();
  683. }
  684. return factory.detect(cygwinUsed);
  685. }
  686. /**
  687. * Get cached FileStore attributes, if not yet available measure them using
  688. * a probe file under the given directory.
  689. *
  690. * @param dir
  691. * the directory under which the probe file will be created to
  692. * measure the timer resolution.
  693. * @return measured filesystem timestamp resolution
  694. * @since 5.1.9
  695. */
  696. public static FileStoreAttributes getFileStoreAttributes(
  697. @NonNull Path dir) {
  698. return FileStoreAttributes.get(dir);
  699. }
  700. private volatile Holder<File> userHome;
  701. private volatile Holder<File> gitSystemConfig;
  702. /**
  703. * Constructs a file system abstraction.
  704. */
  705. protected FS() {
  706. // Do nothing by default.
  707. }
  708. /**
  709. * Initialize this FS using another's current settings.
  710. *
  711. * @param src
  712. * the source FS to copy from.
  713. */
  714. protected FS(FS src) {
  715. userHome = src.userHome;
  716. gitSystemConfig = src.gitSystemConfig;
  717. }
  718. /**
  719. * Create a new instance of the same type of FS.
  720. *
  721. * @return a new instance of the same type of FS.
  722. */
  723. public abstract FS newInstance();
  724. /**
  725. * Does this operating system and JRE support the execute flag on files?
  726. *
  727. * @return true if this implementation can provide reasonably accurate
  728. * executable bit information; false otherwise.
  729. */
  730. public abstract boolean supportsExecute();
  731. /**
  732. * Does this file system support atomic file creation via
  733. * java.io.File#createNewFile()? In certain environments (e.g. on NFS) it is
  734. * not guaranteed that when two file system clients run createNewFile() in
  735. * parallel only one will succeed. In such cases both clients may think they
  736. * created a new file.
  737. *
  738. * @return true if this implementation support atomic creation of new Files
  739. * by {@link java.io.File#createNewFile()}
  740. * @since 4.5
  741. */
  742. public boolean supportsAtomicCreateNewFile() {
  743. return true;
  744. }
  745. /**
  746. * Does this operating system and JRE supports symbolic links. The
  747. * capability to handle symbolic links is detected at runtime.
  748. *
  749. * @return true if symbolic links may be used
  750. * @since 3.0
  751. */
  752. public boolean supportsSymlinks() {
  753. if (supportSymlinks == null) {
  754. detectSymlinkSupport();
  755. }
  756. return Boolean.TRUE.equals(supportSymlinks);
  757. }
  758. private void detectSymlinkSupport() {
  759. File tempFile = null;
  760. try {
  761. tempFile = File.createTempFile("tempsymlinktarget", ""); //$NON-NLS-1$ //$NON-NLS-2$
  762. File linkName = new File(tempFile.getParentFile(), "tempsymlink"); //$NON-NLS-1$
  763. createSymLink(linkName, tempFile.getPath());
  764. supportSymlinks = Boolean.TRUE;
  765. linkName.delete();
  766. } catch (IOException | UnsupportedOperationException | SecurityException
  767. | InternalError e) {
  768. supportSymlinks = Boolean.FALSE;
  769. } finally {
  770. if (tempFile != null) {
  771. try {
  772. FileUtils.delete(tempFile);
  773. } catch (IOException e) {
  774. LOG.error(JGitText.get().cannotDeleteFile, tempFile);
  775. }
  776. }
  777. }
  778. }
  779. /**
  780. * Is this file system case sensitive
  781. *
  782. * @return true if this implementation is case sensitive
  783. */
  784. public abstract boolean isCaseSensitive();
  785. /**
  786. * Determine if the file is executable (or not).
  787. * <p>
  788. * Not all platforms and JREs support executable flags on files. If the
  789. * feature is unsupported this method will always return false.
  790. * <p>
  791. * <em>If the platform supports symbolic links and <code>f</code> is a symbolic link
  792. * this method returns false, rather than the state of the executable flags
  793. * on the target file.</em>
  794. *
  795. * @param f
  796. * abstract path to test.
  797. * @return true if the file is believed to be executable by the user.
  798. */
  799. public abstract boolean canExecute(File f);
  800. /**
  801. * Set a file to be executable by the user.
  802. * <p>
  803. * Not all platforms and JREs support executable flags on files. If the
  804. * feature is unsupported this method will always return false and no
  805. * changes will be made to the file specified.
  806. *
  807. * @param f
  808. * path to modify the executable status of.
  809. * @param canExec
  810. * true to enable execution; false to disable it.
  811. * @return true if the change succeeded; false otherwise.
  812. */
  813. public abstract boolean setExecute(File f, boolean canExec);
  814. /**
  815. * Get the last modified time of a file system object. If the OS/JRE support
  816. * symbolic links, the modification time of the link is returned, rather
  817. * than that of the link target.
  818. *
  819. * @param f
  820. * a {@link java.io.File} object.
  821. * @return last modified time of f
  822. * @throws java.io.IOException
  823. * @since 3.0
  824. * @deprecated use {@link #lastModifiedInstant(Path)} instead
  825. */
  826. @Deprecated
  827. public long lastModified(File f) throws IOException {
  828. return FileUtils.lastModified(f);
  829. }
  830. /**
  831. * Get the last modified time of a file system object. If the OS/JRE support
  832. * symbolic links, the modification time of the link is returned, rather
  833. * than that of the link target.
  834. *
  835. * @param p
  836. * a {@link Path} object.
  837. * @return last modified time of p
  838. * @since 5.1.9
  839. */
  840. public Instant lastModifiedInstant(Path p) {
  841. return FileUtils.lastModifiedInstant(p);
  842. }
  843. /**
  844. * Get the last modified time of a file system object. If the OS/JRE support
  845. * symbolic links, the modification time of the link is returned, rather
  846. * than that of the link target.
  847. *
  848. * @param f
  849. * a {@link File} object.
  850. * @return last modified time of p
  851. * @since 5.1.9
  852. */
  853. public Instant lastModifiedInstant(File f) {
  854. return FileUtils.lastModifiedInstant(f.toPath());
  855. }
  856. /**
  857. * Set the last modified time of a file system object. If the OS/JRE support
  858. * symbolic links, the link is modified, not the target,
  859. *
  860. * @param f
  861. * a {@link java.io.File} object.
  862. * @param time
  863. * last modified time
  864. * @throws java.io.IOException
  865. * @since 3.0
  866. * @deprecated use {@link #setLastModified(Path, Instant)} instead
  867. */
  868. @Deprecated
  869. public void setLastModified(File f, long time) throws IOException {
  870. FileUtils.setLastModified(f, time);
  871. }
  872. /**
  873. * Set the last modified time of a file system object. If the OS/JRE support
  874. * symbolic links, the link is modified, not the target,
  875. *
  876. * @param p
  877. * a {@link Path} object.
  878. * @param time
  879. * last modified time
  880. * @throws java.io.IOException
  881. * @since 5.1.9
  882. */
  883. public void setLastModified(Path p, Instant time) throws IOException {
  884. FileUtils.setLastModified(p, time);
  885. }
  886. /**
  887. * Get the length of a file or link, If the OS/JRE supports symbolic links
  888. * it's the length of the link, else the length of the target.
  889. *
  890. * @param path
  891. * a {@link java.io.File} object.
  892. * @return length of a file
  893. * @throws java.io.IOException
  894. * @since 3.0
  895. */
  896. public long length(File path) throws IOException {
  897. return FileUtils.getLength(path);
  898. }
  899. /**
  900. * Delete a file. Throws an exception if delete fails.
  901. *
  902. * @param f
  903. * a {@link java.io.File} object.
  904. * @throws java.io.IOException
  905. * this may be a Java7 subclass with detailed information
  906. * @since 3.3
  907. */
  908. public void delete(File f) throws IOException {
  909. FileUtils.delete(f);
  910. }
  911. /**
  912. * Resolve this file to its actual path name that the JRE can use.
  913. * <p>
  914. * This method can be relatively expensive. Computing a translation may
  915. * require forking an external process per path name translated. Callers
  916. * should try to minimize the number of translations necessary by caching
  917. * the results.
  918. * <p>
  919. * Not all platforms and JREs require path name translation. Currently only
  920. * Cygwin on Win32 require translation for Cygwin based paths.
  921. *
  922. * @param dir
  923. * directory relative to which the path name is.
  924. * @param name
  925. * path name to translate.
  926. * @return the translated path. <code>new File(dir,name)</code> if this
  927. * platform does not require path name translation.
  928. */
  929. public File resolve(File dir, String name) {
  930. final File abspn = new File(name);
  931. if (abspn.isAbsolute())
  932. return abspn;
  933. return new File(dir, name);
  934. }
  935. /**
  936. * Determine the user's home directory (location where preferences are).
  937. * <p>
  938. * This method can be expensive on the first invocation if path name
  939. * translation is required. Subsequent invocations return a cached result.
  940. * <p>
  941. * Not all platforms and JREs require path name translation. Currently only
  942. * Cygwin on Win32 requires translation of the Cygwin HOME directory.
  943. *
  944. * @return the user's home directory; null if the user does not have one.
  945. */
  946. public File userHome() {
  947. Holder<File> p = userHome;
  948. if (p == null) {
  949. p = new Holder<>(userHomeImpl());
  950. userHome = p;
  951. }
  952. return p.value;
  953. }
  954. /**
  955. * Set the user's home directory location.
  956. *
  957. * @param path
  958. * the location of the user's preferences; null if there is no
  959. * home directory for the current user.
  960. * @return {@code this}.
  961. */
  962. public FS setUserHome(File path) {
  963. userHome = new Holder<>(path);
  964. return this;
  965. }
  966. /**
  967. * Does this file system have problems with atomic renames?
  968. *
  969. * @return true if the caller should retry a failed rename of a lock file.
  970. */
  971. public abstract boolean retryFailedLockFileCommit();
  972. /**
  973. * Return all the attributes of a file, without following symbolic links.
  974. *
  975. * @param file
  976. * @return {@link BasicFileAttributes} of the file
  977. * @throws IOException in case of any I/O errors accessing the file
  978. *
  979. * @since 4.5.6
  980. */
  981. public BasicFileAttributes fileAttributes(File file) throws IOException {
  982. return FileUtils.fileAttributes(file);
  983. }
  984. /**
  985. * Determine the user's home directory (location where preferences are).
  986. *
  987. * @return the user's home directory; null if the user does not have one.
  988. */
  989. protected File userHomeImpl() {
  990. final String home = AccessController.doPrivileged(
  991. (PrivilegedAction<String>) () -> System.getProperty("user.home") //$NON-NLS-1$
  992. );
  993. if (home == null || home.length() == 0)
  994. return null;
  995. return new File(home).getAbsoluteFile();
  996. }
  997. /**
  998. * Searches the given path to see if it contains one of the given files.
  999. * Returns the first it finds. Returns null if not found or if path is null.
  1000. *
  1001. * @param path
  1002. * List of paths to search separated by File.pathSeparator
  1003. * @param lookFor
  1004. * Files to search for in the given path
  1005. * @return the first match found, or null
  1006. * @since 3.0
  1007. */
  1008. protected static File searchPath(String path, String... lookFor) {
  1009. if (path == null)
  1010. return null;
  1011. for (String p : path.split(File.pathSeparator)) {
  1012. for (String command : lookFor) {
  1013. final File file = new File(p, command);
  1014. try {
  1015. if (file.isFile()) {
  1016. return file.getAbsoluteFile();
  1017. }
  1018. } catch (SecurityException e) {
  1019. LOG.warn(MessageFormat.format(
  1020. JGitText.get().skipNotAccessiblePath,
  1021. file.getPath()));
  1022. }
  1023. }
  1024. }
  1025. return null;
  1026. }
  1027. /**
  1028. * Execute a command and return a single line of output as a String
  1029. *
  1030. * @param dir
  1031. * Working directory for the command
  1032. * @param command
  1033. * as component array
  1034. * @param encoding
  1035. * to be used to parse the command's output
  1036. * @return the one-line output of the command or {@code null} if there is
  1037. * none
  1038. * @throws org.eclipse.jgit.errors.CommandFailedException
  1039. * thrown when the command failed (return code was non-zero)
  1040. */
  1041. @Nullable
  1042. protected static String readPipe(File dir, String[] command,
  1043. String encoding) throws CommandFailedException {
  1044. return readPipe(dir, command, encoding, null);
  1045. }
  1046. /**
  1047. * Execute a command and return a single line of output as a String
  1048. *
  1049. * @param dir
  1050. * Working directory for the command
  1051. * @param command
  1052. * as component array
  1053. * @param encoding
  1054. * to be used to parse the command's output
  1055. * @param env
  1056. * Map of environment variables to be merged with those of the
  1057. * current process
  1058. * @return the one-line output of the command or {@code null} if there is
  1059. * none
  1060. * @throws org.eclipse.jgit.errors.CommandFailedException
  1061. * thrown when the command failed (return code was non-zero)
  1062. * @since 4.0
  1063. */
  1064. @Nullable
  1065. protected static String readPipe(File dir, String[] command,
  1066. String encoding, Map<String, String> env)
  1067. throws CommandFailedException {
  1068. final boolean debug = LOG.isDebugEnabled();
  1069. try {
  1070. if (debug) {
  1071. LOG.debug("readpipe " + Arrays.asList(command) + "," //$NON-NLS-1$ //$NON-NLS-2$
  1072. + dir);
  1073. }
  1074. ProcessBuilder pb = new ProcessBuilder(command);
  1075. pb.directory(dir);
  1076. if (env != null) {
  1077. pb.environment().putAll(env);
  1078. }
  1079. Process p;
  1080. try {
  1081. p = pb.start();
  1082. } catch (IOException e) {
  1083. // Process failed to start
  1084. throw new CommandFailedException(-1, e.getMessage(), e);
  1085. }
  1086. p.getOutputStream().close();
  1087. GobblerThread gobbler = new GobblerThread(p, command, dir);
  1088. gobbler.start();
  1089. String r = null;
  1090. try (BufferedReader lineRead = new BufferedReader(
  1091. new InputStreamReader(p.getInputStream(), encoding))) {
  1092. r = lineRead.readLine();
  1093. if (debug) {
  1094. LOG.debug("readpipe may return '" + r + "'"); //$NON-NLS-1$ //$NON-NLS-2$
  1095. LOG.debug("remaining output:\n"); //$NON-NLS-1$
  1096. String l;
  1097. while ((l = lineRead.readLine()) != null) {
  1098. LOG.debug(l);
  1099. }
  1100. }
  1101. }
  1102. for (;;) {
  1103. try {
  1104. int rc = p.waitFor();
  1105. gobbler.join();
  1106. if (rc == 0 && !gobbler.fail.get()) {
  1107. return r;
  1108. }
  1109. if (debug) {
  1110. LOG.debug("readpipe rc=" + rc); //$NON-NLS-1$
  1111. }
  1112. throw new CommandFailedException(rc,
  1113. gobbler.errorMessage.get(),
  1114. gobbler.exception.get());
  1115. } catch (InterruptedException ie) {
  1116. // Stop bothering me, I have a zombie to reap.
  1117. }
  1118. }
  1119. } catch (IOException e) {
  1120. LOG.error("Caught exception in FS.readPipe()", e); //$NON-NLS-1$
  1121. } catch (AccessControlException e) {
  1122. LOG.warn(MessageFormat.format(
  1123. JGitText.get().readPipeIsNotAllowedRequiredPermission,
  1124. command, dir, e.getPermission()));
  1125. } catch (SecurityException e) {
  1126. LOG.warn(MessageFormat.format(JGitText.get().readPipeIsNotAllowed,
  1127. command, dir));
  1128. }
  1129. if (debug) {
  1130. LOG.debug("readpipe returns null"); //$NON-NLS-1$
  1131. }
  1132. return null;
  1133. }
  1134. private static class GobblerThread extends Thread {
  1135. /* The process has 5 seconds to exit after closing stderr */
  1136. private static final int PROCESS_EXIT_TIMEOUT = 5;
  1137. private final Process p;
  1138. private final String desc;
  1139. private final String dir;
  1140. final AtomicBoolean fail = new AtomicBoolean();
  1141. final AtomicReference<String> errorMessage = new AtomicReference<>();
  1142. final AtomicReference<Throwable> exception = new AtomicReference<>();
  1143. GobblerThread(Process p, String[] command, File dir) {
  1144. this.p = p;
  1145. this.desc = Arrays.toString(command);
  1146. this.dir = Objects.toString(dir);
  1147. }
  1148. @Override
  1149. public void run() {
  1150. StringBuilder err = new StringBuilder();
  1151. try (InputStream is = p.getErrorStream()) {
  1152. int ch;
  1153. while ((ch = is.read()) != -1) {
  1154. err.append((char) ch);
  1155. }
  1156. } catch (IOException e) {
  1157. if (waitForProcessCompletion(e) && p.exitValue() != 0) {
  1158. setError(e, e.getMessage(), p.exitValue());
  1159. fail.set(true);
  1160. } else {
  1161. // ignore. command terminated faster and stream was just closed
  1162. // or the process didn't terminate within timeout
  1163. }
  1164. } finally {
  1165. if (waitForProcessCompletion(null) && err.length() > 0) {
  1166. setError(null, err.toString(), p.exitValue());
  1167. if (p.exitValue() != 0) {
  1168. fail.set(true);
  1169. }
  1170. }
  1171. }
  1172. }
  1173. @SuppressWarnings("boxing")
  1174. private boolean waitForProcessCompletion(IOException originalError) {
  1175. try {
  1176. if (!p.waitFor(PROCESS_EXIT_TIMEOUT, TimeUnit.SECONDS)) {
  1177. setError(originalError, MessageFormat.format(
  1178. JGitText.get().commandClosedStderrButDidntExit,
  1179. desc, PROCESS_EXIT_TIMEOUT), -1);
  1180. fail.set(true);
  1181. return false;
  1182. }
  1183. } catch (InterruptedException e) {
  1184. setError(originalError, MessageFormat.format(
  1185. JGitText.get().threadInterruptedWhileRunning, desc), -1);
  1186. fail.set(true);
  1187. return false;
  1188. }
  1189. return true;
  1190. }
  1191. private void setError(IOException e, String message, int exitCode) {
  1192. exception.set(e);
  1193. errorMessage.set(MessageFormat.format(
  1194. JGitText.get().exceptionCaughtDuringExecutionOfCommand,
  1195. desc, dir, Integer.valueOf(exitCode), message));
  1196. }
  1197. }
  1198. /**
  1199. * Discover the path to the Git executable.
  1200. *
  1201. * @return the path to the Git executable or {@code null} if it cannot be
  1202. * determined.
  1203. * @since 4.0
  1204. */
  1205. protected abstract File discoverGitExe();
  1206. /**
  1207. * Discover the path to the system-wide Git configuration file
  1208. *
  1209. * @return the path to the system-wide Git configuration file or
  1210. * {@code null} if it cannot be determined.
  1211. * @since 4.0
  1212. */
  1213. protected File discoverGitSystemConfig() {
  1214. File gitExe = discoverGitExe();
  1215. if (gitExe == null) {
  1216. return null;
  1217. }
  1218. // Bug 480782: Check if the discovered git executable is JGit CLI
  1219. String v;
  1220. try {
  1221. v = readPipe(gitExe.getParentFile(),
  1222. new String[] { "git", "--version" }, //$NON-NLS-1$ //$NON-NLS-2$
  1223. Charset.defaultCharset().name());
  1224. } catch (CommandFailedException e) {
  1225. LOG.warn(e.getMessage());
  1226. return null;
  1227. }
  1228. if (StringUtils.isEmptyOrNull(v)
  1229. || (v != null && v.startsWith("jgit"))) { //$NON-NLS-1$
  1230. return null;
  1231. }
  1232. // Trick Git into printing the path to the config file by using "echo"
  1233. // as the editor.
  1234. Map<String, String> env = new HashMap<>();
  1235. env.put("GIT_EDITOR", "echo"); //$NON-NLS-1$ //$NON-NLS-2$
  1236. String w;
  1237. try {
  1238. w = readPipe(gitExe.getParentFile(),
  1239. new String[] { "git", "config", "--system", "--edit" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
  1240. Charset.defaultCharset().name(), env);
  1241. } catch (CommandFailedException e) {
  1242. LOG.warn(e.getMessage());
  1243. return null;
  1244. }
  1245. if (StringUtils.isEmptyOrNull(w)) {
  1246. return null;
  1247. }
  1248. return new File(w);
  1249. }
  1250. /**
  1251. * Get the currently used path to the system-wide Git configuration file.
  1252. *
  1253. * @return the currently used path to the system-wide Git configuration file
  1254. * or {@code null} if none has been set.
  1255. * @since 4.0
  1256. */
  1257. public File getGitSystemConfig() {
  1258. if (gitSystemConfig == null) {
  1259. gitSystemConfig = new Holder<>(discoverGitSystemConfig());
  1260. }
  1261. return gitSystemConfig.value;
  1262. }
  1263. /**
  1264. * Set the path to the system-wide Git configuration file to use.
  1265. *
  1266. * @param configFile
  1267. * the path to the config file.
  1268. * @return {@code this}
  1269. * @since 4.0
  1270. */
  1271. public FS setGitSystemConfig(File configFile) {
  1272. gitSystemConfig = new Holder<>(configFile);
  1273. return this;
  1274. }
  1275. /**
  1276. * Get the parent directory of this file's parent directory
  1277. *
  1278. * @param grandchild
  1279. * a {@link java.io.File} object.
  1280. * @return the parent directory of this file's parent directory or
  1281. * {@code null} in case there's no grandparent directory
  1282. * @since 4.0
  1283. */
  1284. protected static File resolveGrandparentFile(File grandchild) {
  1285. if (grandchild != null) {
  1286. File parent = grandchild.getParentFile();
  1287. if (parent != null)
  1288. return parent.getParentFile();
  1289. }
  1290. return null;
  1291. }
  1292. /**
  1293. * Check if a file is a symbolic link and read it
  1294. *
  1295. * @param path
  1296. * a {@link java.io.File} object.
  1297. * @return target of link or null
  1298. * @throws java.io.IOException
  1299. * @since 3.0
  1300. */
  1301. public String readSymLink(File path) throws IOException {
  1302. return FileUtils.readSymLink(path);
  1303. }
  1304. /**
  1305. * Whether the path is a symbolic link (and we support these).
  1306. *
  1307. * @param path
  1308. * a {@link java.io.File} object.
  1309. * @return true if the path is a symbolic link (and we support these)
  1310. * @throws java.io.IOException
  1311. * @since 3.0
  1312. */
  1313. public boolean isSymLink(File path) throws IOException {
  1314. return FileUtils.isSymlink(path);
  1315. }
  1316. /**
  1317. * Tests if the path exists, in case of a symbolic link, true even if the
  1318. * target does not exist
  1319. *
  1320. * @param path
  1321. * a {@link java.io.File} object.
  1322. * @return true if path exists
  1323. * @since 3.0
  1324. */
  1325. public boolean exists(File path) {
  1326. return FileUtils.exists(path);
  1327. }
  1328. /**
  1329. * Check if path is a directory. If the OS/JRE supports symbolic links and
  1330. * path is a symbolic link to a directory, this method returns false.
  1331. *
  1332. * @param path
  1333. * a {@link java.io.File} object.
  1334. * @return true if file is a directory,
  1335. * @since 3.0
  1336. */
  1337. public boolean isDirectory(File path) {
  1338. return FileUtils.isDirectory(path);
  1339. }
  1340. /**
  1341. * Examine if path represents a regular file. If the OS/JRE supports
  1342. * symbolic links the test returns false if path represents a symbolic link.
  1343. *
  1344. * @param path
  1345. * a {@link java.io.File} object.
  1346. * @return true if path represents a regular file
  1347. * @since 3.0
  1348. */
  1349. public boolean isFile(File path) {
  1350. return FileUtils.isFile(path);
  1351. }
  1352. /**
  1353. * Whether path is hidden, either starts with . on unix or has the hidden
  1354. * attribute in windows
  1355. *
  1356. * @param path
  1357. * a {@link java.io.File} object.
  1358. * @return true if path is hidden, either starts with . on unix or has the
  1359. * hidden attribute in windows
  1360. * @throws java.io.IOException
  1361. * @since 3.0
  1362. */
  1363. public boolean isHidden(File path) throws IOException {
  1364. return FileUtils.isHidden(path);
  1365. }
  1366. /**
  1367. * Set the hidden attribute for file whose name starts with a period.
  1368. *
  1369. * @param path
  1370. * a {@link java.io.File} object.
  1371. * @param hidden
  1372. * whether to set the file hidden
  1373. * @throws java.io.IOException
  1374. * @since 3.0
  1375. */
  1376. public void setHidden(File path, boolean hidden) throws IOException {
  1377. FileUtils.setHidden(path, hidden);
  1378. }
  1379. /**
  1380. * Create a symbolic link
  1381. *
  1382. * @param path
  1383. * a {@link java.io.File} object.
  1384. * @param target
  1385. * target path of the symlink
  1386. * @throws java.io.IOException
  1387. * @since 3.0
  1388. */
  1389. public void createSymLink(File path, String target) throws IOException {
  1390. FileUtils.createSymLink(path, target);
  1391. }
  1392. /**
  1393. * Create a new file. See {@link java.io.File#createNewFile()}. Subclasses
  1394. * of this class may take care to provide a safe implementation for this
  1395. * even if {@link #supportsAtomicCreateNewFile()} is <code>false</code>
  1396. *
  1397. * @param path
  1398. * the file to be created
  1399. * @return <code>true</code> if the file was created, <code>false</code> if
  1400. * the file already existed
  1401. * @throws java.io.IOException
  1402. * @deprecated use {@link #createNewFileAtomic(File)} instead
  1403. * @since 4.5
  1404. */
  1405. @Deprecated
  1406. public boolean createNewFile(File path) throws IOException {
  1407. return path.createNewFile();
  1408. }
  1409. /**
  1410. * A token representing a file created by
  1411. * {@link #createNewFileAtomic(File)}. The token must be retained until the
  1412. * file has been deleted in order to guarantee that the unique file was
  1413. * created atomically. As soon as the file is no longer needed the lock
  1414. * token must be closed.
  1415. *
  1416. * @since 4.7
  1417. */
  1418. public static class LockToken implements Closeable {
  1419. private boolean isCreated;
  1420. private Optional<Path> link;
  1421. LockToken(boolean isCreated, Optional<Path> link) {
  1422. this.isCreated = isCreated;
  1423. this.link = link;
  1424. }
  1425. /**
  1426. * @return {@code true} if the file was created successfully
  1427. */
  1428. public boolean isCreated() {
  1429. return isCreated;
  1430. }
  1431. @Override
  1432. public void close() {
  1433. if (!link.isPresent()) {
  1434. return;
  1435. }
  1436. Path p = link.get();
  1437. if (!Files.exists(p)) {
  1438. return;
  1439. }
  1440. try {
  1441. Files.delete(p);
  1442. } catch (IOException e) {
  1443. LOG.error(MessageFormat
  1444. .format(JGitText.get().closeLockTokenFailed, this), e);
  1445. }
  1446. }
  1447. @Override
  1448. public String toString() {
  1449. return "LockToken [lockCreated=" + isCreated + //$NON-NLS-1$
  1450. ", link=" //$NON-NLS-1$
  1451. + (link.isPresent() ? link.get().getFileName() + "]" //$NON-NLS-1$
  1452. : "<null>]"); //$NON-NLS-1$
  1453. }
  1454. }
  1455. /**
  1456. * Create a new file. See {@link java.io.File#createNewFile()}. Subclasses
  1457. * of this class may take care to provide a safe implementation for this
  1458. * even if {@link #supportsAtomicCreateNewFile()} is <code>false</code>
  1459. *
  1460. * @param path
  1461. * the file to be created
  1462. * @return LockToken this token must be closed after the created file was
  1463. * deleted
  1464. * @throws IOException
  1465. * @since 4.7
  1466. */
  1467. public LockToken createNewFileAtomic(File path) throws IOException {
  1468. return new LockToken(path.createNewFile(), Optional.empty());
  1469. }
  1470. /**
  1471. * See
  1472. * {@link org.eclipse.jgit.util.FileUtils#relativizePath(String, String, String, boolean)}.
  1473. *
  1474. * @param base
  1475. * The path against which <code>other</code> should be
  1476. * relativized.
  1477. * @param other
  1478. * The path that will be made relative to <code>base</code>.
  1479. * @return A relative path that, when resolved against <code>base</code>,
  1480. * will yield the original <code>other</code>.
  1481. * @see FileUtils#relativizePath(String, String, String, boolean)
  1482. * @since 3.7
  1483. */
  1484. public String relativize(String base, String other) {
  1485. return FileUtils.relativizePath(base, other, File.separator, this.isCaseSensitive());
  1486. }
  1487. /**
  1488. * Enumerates children of a directory.
  1489. *
  1490. * @param directory
  1491. * to get the children of
  1492. * @param fileModeStrategy
  1493. * to use to calculate the git mode of a child
  1494. * @return an array of entries for the children
  1495. *
  1496. * @since 5.0
  1497. */
  1498. public Entry[] list(File directory, FileModeStrategy fileModeStrategy) {
  1499. final File[] all = directory.listFiles();
  1500. if (all == null) {
  1501. return NO_ENTRIES;
  1502. }
  1503. final Entry[] result = new Entry[all.length];
  1504. for (int i = 0; i < result.length; i++) {
  1505. result[i] = new FileEntry(all[i], this, fileModeStrategy);
  1506. }
  1507. return result;
  1508. }
  1509. /**
  1510. * Checks whether the given hook is defined for the given repository, then
  1511. * runs it with the given arguments.
  1512. * <p>
  1513. * The hook's standard output and error streams will be redirected to
  1514. * <code>System.out</code> and <code>System.err</code> respectively. The
  1515. * hook will have no stdin.
  1516. * </p>
  1517. *
  1518. * @param repository
  1519. * The repository for which a hook should be run.
  1520. * @param hookName
  1521. * The name of the hook to be executed.
  1522. * @param args
  1523. * Arguments to pass to this hook. Cannot be <code>null</code>,
  1524. * but can be an empty array.
  1525. * @return The ProcessResult describing this hook's execution.
  1526. * @throws org.eclipse.jgit.api.errors.JGitInternalException
  1527. * if we fail to run the hook somehow. Causes may include an
  1528. * interrupted process or I/O errors.
  1529. * @since 4.0
  1530. */
  1531. public ProcessResult runHookIfPresent(Repository repository,
  1532. final String hookName,
  1533. String[] args) throws JGitInternalException {
  1534. return runHookIfPresent(repository, hookName, args, System.out, System.err,
  1535. null);
  1536. }
  1537. /**
  1538. * Checks whether the given hook is defined for the given repository, then
  1539. * runs it with the given arguments.
  1540. *
  1541. * @param repository
  1542. * The repository for which a hook should be run.
  1543. * @param hookName
  1544. * The name of the hook to be executed.
  1545. * @param args
  1546. * Arguments to pass to this hook. Cannot be <code>null</code>,
  1547. * but can be an empty array.
  1548. * @param outRedirect
  1549. * A print stream on which to redirect the hook's stdout. Can be
  1550. * <code>null</code>, in which case the hook's standard output
  1551. * will be lost.
  1552. * @param errRedirect
  1553. * A print stream on which to redirect the hook's stderr. Can be
  1554. * <code>null</code>, in which case the hook's standard error
  1555. * will be lost.
  1556. * @param stdinArgs
  1557. * A string to pass on to the standard input of the hook. May be
  1558. * <code>null</code>.
  1559. * @return The ProcessResult describing this hook's execution.
  1560. * @throws org.eclipse.jgit.api.errors.JGitInternalException
  1561. * if we fail to run the hook somehow. Causes may include an
  1562. * interrupted process or I/O errors.
  1563. * @since 4.0
  1564. */
  1565. public ProcessResult runHookIfPresent(Repository repository,
  1566. final String hookName,
  1567. String[] args, PrintStream outRedirect, PrintStream errRedirect,
  1568. String stdinArgs) throws JGitInternalException {
  1569. return new ProcessResult(Status.NOT_SUPPORTED);
  1570. }
  1571. /**
  1572. * See
  1573. * {@link #runHookIfPresent(Repository, String, String[], PrintStream, PrintStream, String)}
  1574. * . Should only be called by FS supporting shell scripts execution.
  1575. *
  1576. * @param repository
  1577. * The repository for which a hook should be run.
  1578. * @param hookName
  1579. * The name of the hook to be executed.
  1580. * @param args
  1581. * Arguments to pass to this hook. Cannot be <code>null</code>,
  1582. * but can be an empty array.
  1583. * @param outRedirect
  1584. * A print stream on which to redirect the hook's stdout. Can be
  1585. * <code>null</code>, in which case the hook's standard output
  1586. * will be lost.
  1587. * @param errRedirect
  1588. * A print stream on which to redirect the hook's stderr. Can be
  1589. * <code>null</code>, in which case the hook's standard error
  1590. * will be lost.
  1591. * @param stdinArgs
  1592. * A string to pass on to the standard input of the hook. May be
  1593. * <code>null</code>.
  1594. * @return The ProcessResult describing this hook's execution.
  1595. * @throws org.eclipse.jgit.api.errors.JGitInternalException
  1596. * if we fail to run the hook somehow. Causes may include an
  1597. * interrupted process or I/O errors.
  1598. * @since 4.0
  1599. */
  1600. protected ProcessResult internalRunHookIfPresent(Repository repository,
  1601. final String hookName, String[] args, PrintStream outRedirect,
  1602. PrintStream errRedirect, String stdinArgs)
  1603. throws JGitInternalException {
  1604. File hookFile = findHook(repository, hookName);
  1605. if (hookFile == null || hookName == null) {
  1606. return new ProcessResult(Status.NOT_PRESENT);
  1607. }
  1608. File runDirectory = getRunDirectory(repository, hookName);
  1609. if (runDirectory == null) {
  1610. return new ProcessResult(Status.NOT_PRESENT);
  1611. }
  1612. String cmd = hookFile.getAbsolutePath();
  1613. ProcessBuilder hookProcess = runInShell(cmd, args);
  1614. hookProcess.directory(runDirectory.getAbsoluteFile());
  1615. Map<String, String> environment = hookProcess.environment();
  1616. environment.put(Constants.GIT_DIR_KEY,
  1617. repository.getDirectory().getAbsolutePath());
  1618. if (!repository.isBare()) {
  1619. environment.put(Constants.GIT_WORK_TREE_KEY,
  1620. repository.getWorkTree().getAbsolutePath());
  1621. }
  1622. try {
  1623. return new ProcessResult(runProcess(hookProcess, outRedirect,
  1624. errRedirect, stdinArgs), Status.OK);
  1625. } catch (IOException e) {
  1626. throw new JGitInternalException(MessageFormat.format(
  1627. JGitText.get().exceptionCaughtDuringExecutionOfHook,
  1628. hookName), e);
  1629. } catch (InterruptedException e) {
  1630. throw new JGitInternalException(MessageFormat.format(
  1631. JGitText.get().exceptionHookExecutionInterrupted,
  1632. hookName), e);
  1633. }
  1634. }
  1635. /**
  1636. * Tries to find a hook matching the given one in the given repository.
  1637. *
  1638. * @param repository
  1639. * The repository within which to find a hook.
  1640. * @param hookName
  1641. * The name of the hook we're trying to find.
  1642. * @return The {@link java.io.File} containing this particular hook if it
  1643. * exists in the given repository, <code>null</code> otherwise.
  1644. * @since 4.0
  1645. */
  1646. public File findHook(Repository repository, String hookName) {
  1647. if (hookName == null) {
  1648. return null;
  1649. }
  1650. File hookDir = getHooksDirectory(repository);
  1651. if (hookDir == null) {
  1652. return null;
  1653. }
  1654. File hookFile = new File(hookDir, hookName);
  1655. if (hookFile.isAbsolute()) {
  1656. if (!hookFile.exists() || (FS.DETECTED.supportsExecute()
  1657. && !FS.DETECTED.canExecute(hookFile))) {
  1658. return null;
  1659. }
  1660. } else {
  1661. try {
  1662. File runDirectory = getRunDirectory(repository, hookName);
  1663. if (runDirectory == null) {
  1664. return null;
  1665. }
  1666. Path hookPath = runDirectory.getAbsoluteFile().toPath()
  1667. .resolve(hookFile.toPath());
  1668. FS fs = repository.getFS();
  1669. if (fs == null) {
  1670. fs = FS.DETECTED;
  1671. }
  1672. if (!Files.exists(hookPath) || (fs.supportsExecute()
  1673. && !fs.canExecute(hookPath.toFile()))) {
  1674. return null;
  1675. }
  1676. hookFile = hookPath.toFile();
  1677. } catch (InvalidPathException e) {
  1678. LOG.warn(MessageFormat.format(JGitText.get().invalidHooksPath,
  1679. hookFile));
  1680. return null;
  1681. }
  1682. }
  1683. return hookFile;
  1684. }
  1685. private File getRunDirectory(Repository repository,
  1686. @NonNull String hookName) {
  1687. if (repository.isBare()) {
  1688. return repository.getDirectory();
  1689. }
  1690. switch (hookName) {
  1691. case "pre-receive": //$NON-NLS-1$
  1692. case "update": //$NON-NLS-1$
  1693. case "post-receive": //$NON-NLS-1$
  1694. case "post-update": //$NON-NLS-1$
  1695. case "push-to-checkout": //$NON-NLS-1$
  1696. return repository.getDirectory();
  1697. default:
  1698. return repository.getWorkTree();
  1699. }
  1700. }
  1701. private File getHooksDirectory(Repository repository) {
  1702. Config config = repository.getConfig();
  1703. String hooksDir = config.getString(ConfigConstants.CONFIG_CORE_SECTION,
  1704. null, ConfigConstants.CONFIG_KEY_HOOKS_PATH);
  1705. if (hooksDir != null) {
  1706. return new File(hooksDir);
  1707. }
  1708. File dir = repository.getDirectory();
  1709. return dir == null ? null : new File(dir, Constants.HOOKS);
  1710. }
  1711. /**
  1712. * Runs the given process until termination, clearing its stdout and stderr
  1713. * streams on-the-fly.
  1714. *
  1715. * @param processBuilder
  1716. * The process builder configured for this process.
  1717. * @param outRedirect
  1718. * A OutputStream on which to redirect the processes stdout. Can
  1719. * be <code>null</code>, in which case the processes standard
  1720. * output will be lost.
  1721. * @param errRedirect
  1722. * A OutputStream on which to redirect the processes stderr. Can
  1723. * be <code>null</code>, in which case the processes standard
  1724. * error will be lost.
  1725. * @param stdinArgs
  1726. * A string to pass on to the standard input of the hook. Can be
  1727. * <code>null</code>.
  1728. * @return the exit value of this process.
  1729. * @throws java.io.IOException
  1730. * if an I/O error occurs while executing this process.
  1731. * @throws java.lang.InterruptedException
  1732. * if the current thread is interrupted while waiting for the
  1733. * process to end.
  1734. * @since 4.2
  1735. */
  1736. public int runProcess(ProcessBuilder processBuilder,
  1737. OutputStream outRedirect, OutputStream errRedirect, String stdinArgs)
  1738. throws IOException, InterruptedException {
  1739. InputStream in = (stdinArgs == null) ? null : new ByteArrayInputStream(
  1740. stdinArgs.getBytes(UTF_8));
  1741. return runProcess(processBuilder, outRedirect, errRedirect, in);
  1742. }
  1743. /**
  1744. * Runs the given process until termination, clearing its stdout and stderr
  1745. * streams on-the-fly.
  1746. *
  1747. * @param processBuilder
  1748. * The process builder configured for this process.
  1749. * @param outRedirect
  1750. * An OutputStream on which to redirect the processes stdout. Can
  1751. * be <code>null</code>, in which case the processes standard
  1752. * output will be lost.
  1753. * @param errRedirect
  1754. * An OutputStream on which to redirect the processes stderr. Can
  1755. * be <code>null</code>, in which case the processes standard
  1756. * error will be lost.
  1757. * @param inRedirect
  1758. * An InputStream from which to redirect the processes stdin. Can
  1759. * be <code>null</code>, in which case the process doesn't get
  1760. * any data over stdin. It is assumed that the whole InputStream
  1761. * will be consumed by the process. The method will close the
  1762. * inputstream after all bytes are read.
  1763. * @return the return code of this process.
  1764. * @throws java.io.IOException
  1765. * if an I/O error occurs while executing this process.
  1766. * @throws java.lang.InterruptedException
  1767. * if the current thread is interrupted while waiting for the
  1768. * process to end.
  1769. * @since 4.2
  1770. */
  1771. public int runProcess(ProcessBuilder processBuilder,
  1772. OutputStream outRedirect, OutputStream errRedirect,
  1773. InputStream inRedirect) throws IOException,
  1774. InterruptedException {
  1775. final ExecutorService executor = Executors.newFixedThreadPool(2);
  1776. Process process = null;
  1777. // We'll record the first I/O exception that occurs, but keep on trying
  1778. // to dispose of our open streams and file handles
  1779. IOException ioException = null;
  1780. try {
  1781. process = processBuilder.start();
  1782. executor.execute(
  1783. new StreamGobbler(process.getErrorStream(), errRedirect));
  1784. executor.execute(
  1785. new StreamGobbler(process.getInputStream(), outRedirect));
  1786. @SuppressWarnings("resource") // Closed in the finally block
  1787. OutputStream outputStream = process.getOutputStream();
  1788. try {
  1789. if (inRedirect != null) {
  1790. new StreamGobbler(inRedirect, outputStream).copy();
  1791. }
  1792. } finally {
  1793. try {
  1794. outputStream.close();
  1795. } catch (IOException e) {
  1796. // When the process exits before consuming the input, the OutputStream
  1797. // is replaced with the null output stream. This null output stream
  1798. // throws IOException for all write calls. When StreamGobbler fails to
  1799. // flush the buffer because of this, this close call tries to flush it
  1800. // again. This causes another IOException. Since we ignore the
  1801. // IOException in StreamGobbler, we also ignore the exception here.
  1802. }
  1803. }
  1804. return process.waitFor();
  1805. } catch (IOException e) {
  1806. ioException = e;
  1807. } finally {
  1808. shutdownAndAwaitTermination(executor);
  1809. if (process != null) {
  1810. try {
  1811. process.waitFor();
  1812. } catch (InterruptedException e) {
  1813. // Thrown by the outer try.
  1814. // Swallow this one to carry on our cleanup, and clear the
  1815. // interrupted flag (processes throw the exception without
  1816. // clearing the flag).
  1817. Thread.interrupted();
  1818. }
  1819. // A process doesn't clean its own resources even when destroyed
  1820. // Explicitly try and close all three streams, preserving the
  1821. // outer I/O exception if any.
  1822. if (inRedirect != null) {
  1823. inRedirect.close();
  1824. }
  1825. try {
  1826. process.getErrorStream().close();
  1827. } catch (IOException e) {
  1828. ioException = ioException != null ? ioException : e;
  1829. }
  1830. try {
  1831. process.getInputStream().close();
  1832. } catch (IOException e) {
  1833. ioException = ioException != null ? ioException : e;
  1834. }
  1835. try {
  1836. process.getOutputStream().close();
  1837. } catch (IOException e) {
  1838. ioException = ioException != null ? ioException : e;
  1839. }
  1840. process.destroy();
  1841. }
  1842. }
  1843. // We can only be here if the outer try threw an IOException.
  1844. throw ioException;
  1845. }
  1846. /**
  1847. * Shuts down an {@link ExecutorService} in two phases, first by calling
  1848. * {@link ExecutorService#shutdown() shutdown} to reject incoming tasks, and
  1849. * then calling {@link ExecutorService#shutdownNow() shutdownNow}, if
  1850. * necessary, to cancel any lingering tasks. Returns true if the pool has
  1851. * been properly shutdown, false otherwise.
  1852. * <p>
  1853. *
  1854. * @param pool
  1855. * the pool to shutdown
  1856. * @return <code>true</code> if the pool has been properly shutdown,
  1857. * <code>false</code> otherwise.
  1858. */
  1859. private static boolean shutdownAndAwaitTermination(ExecutorService pool) {
  1860. boolean hasShutdown = true;
  1861. pool.shutdown(); // Disable new tasks from being submitted
  1862. try {
  1863. // Wait a while for existing tasks to terminate
  1864. if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
  1865. pool.shutdownNow(); // Cancel currently executing tasks
  1866. // Wait a while for tasks to respond to being canceled
  1867. if (!pool.awaitTermination(60, TimeUnit.SECONDS))
  1868. hasShutdown = false;
  1869. }
  1870. } catch (InterruptedException ie) {
  1871. // (Re-)Cancel if current thread also interrupted
  1872. pool.shutdownNow();
  1873. // Preserve interrupt status
  1874. Thread.currentThread().interrupt();
  1875. hasShutdown = false;
  1876. }
  1877. return hasShutdown;
  1878. }
  1879. /**
  1880. * Initialize a ProcessBuilder to run a command using the system shell.
  1881. *
  1882. * @param cmd
  1883. * command to execute. This string should originate from the
  1884. * end-user, and thus is platform specific.
  1885. * @param args
  1886. * arguments to pass to command. These should be protected from
  1887. * shell evaluation.
  1888. * @return a partially completed process builder. Caller should finish
  1889. * populating directory, environment, and then start the process.
  1890. */
  1891. public abstract ProcessBuilder runInShell(String cmd, String[] args);
  1892. /**
  1893. * Execute a command defined by a {@link java.lang.ProcessBuilder}.
  1894. *
  1895. * @param pb
  1896. * The command to be executed
  1897. * @param in
  1898. * The standard input stream passed to the process
  1899. * @return The result of the executed command
  1900. * @throws java.lang.InterruptedException
  1901. * @throws java.io.IOException
  1902. * @since 4.2
  1903. */
  1904. public ExecutionResult execute(ProcessBuilder pb, InputStream in)
  1905. throws IOException, InterruptedException {
  1906. try (TemporaryBuffer stdout = new TemporaryBuffer.LocalFile(null);
  1907. TemporaryBuffer stderr = new TemporaryBuffer.Heap(1024,
  1908. 1024 * 1024)) {
  1909. int rc = runProcess(pb, stdout, stderr, in);
  1910. return new ExecutionResult(stdout, stderr, rc);
  1911. }
  1912. }
  1913. private static class Holder<V> {
  1914. final V value;
  1915. Holder(V value) {
  1916. this.value = value;
  1917. }
  1918. }
  1919. /**
  1920. * File attributes we typically care for.
  1921. *
  1922. * @since 3.3
  1923. */
  1924. public static class Attributes {
  1925. /**
  1926. * @return true if this are the attributes of a directory
  1927. */
  1928. public boolean isDirectory() {
  1929. return isDirectory;
  1930. }
  1931. /**
  1932. * @return true if this are the attributes of an executable file
  1933. */
  1934. public boolean isExecutable() {
  1935. return isExecutable;
  1936. }
  1937. /**
  1938. * @return true if this are the attributes of a symbolic link
  1939. */
  1940. public boolean isSymbolicLink() {
  1941. return isSymbolicLink;
  1942. }
  1943. /**
  1944. * @return true if this are the attributes of a regular file
  1945. */
  1946. public boolean isRegularFile() {
  1947. return isRegularFile;
  1948. }
  1949. /**
  1950. * @return the time when the file was created
  1951. */
  1952. public long getCreationTime() {
  1953. return creationTime;
  1954. }
  1955. /**
  1956. * @return the time (milliseconds since 1970-01-01) when this object was
  1957. * last modified
  1958. * @deprecated use getLastModifiedInstant instead
  1959. */
  1960. @Deprecated
  1961. public long getLastModifiedTime() {
  1962. return lastModifiedInstant.toEpochMilli();
  1963. }
  1964. /**
  1965. * @return the time when this object was last modified
  1966. * @since 5.1.9
  1967. */
  1968. public Instant getLastModifiedInstant() {
  1969. return lastModifiedInstant;
  1970. }
  1971. private final boolean isDirectory;
  1972. private final boolean isSymbolicLink;
  1973. private final boolean isRegularFile;
  1974. private final long creationTime;
  1975. private final Instant lastModifiedInstant;
  1976. private final boolean isExecutable;
  1977. private final File file;
  1978. private final boolean exists;
  1979. /**
  1980. * file length
  1981. */
  1982. protected long length = -1;
  1983. final FS fs;
  1984. Attributes(FS fs, File file, boolean exists, boolean isDirectory,
  1985. boolean isExecutable, boolean isSymbolicLink,
  1986. boolean isRegularFile, long creationTime,
  1987. Instant lastModifiedInstant, long length) {
  1988. this.fs = fs;
  1989. this.file = file;
  1990. this.exists = exists;
  1991. this.isDirectory = isDirectory;
  1992. this.isExecutable = isExecutable;
  1993. this.isSymbolicLink = isSymbolicLink;
  1994. this.isRegularFile = isRegularFile;
  1995. this.creationTime = creationTime;
  1996. this.lastModifiedInstant = lastModifiedInstant;
  1997. this.length = length;
  1998. }
  1999. /**
  2000. * Constructor when there are issues with reading. All attributes except
  2001. * given will be set to the default values.
  2002. *
  2003. * @param fs
  2004. * @param path
  2005. */
  2006. public Attributes(File path, FS fs) {
  2007. this(fs, path, false, false, false, false, false, 0L, EPOCH, 0L);
  2008. }
  2009. /**
  2010. * @return length of this file object
  2011. */
  2012. public long getLength() {
  2013. if (length == -1)
  2014. return length = file.length();
  2015. return length;
  2016. }
  2017. /**
  2018. * @return the filename
  2019. */
  2020. public String getName() {
  2021. return file.getName();
  2022. }
  2023. /**
  2024. * @return the file the attributes apply to
  2025. */
  2026. public File getFile() {
  2027. return file;
  2028. }
  2029. boolean exists() {
  2030. return exists;
  2031. }
  2032. }
  2033. /**
  2034. * Get the file attributes we care for.
  2035. *
  2036. * @param path
  2037. * a {@link java.io.File} object.
  2038. * @return the file attributes we care for.
  2039. * @since 3.3
  2040. */
  2041. public Attributes getAttributes(File path) {
  2042. boolean isDirectory = isDirectory(path);
  2043. boolean isFile = !isDirectory && path.isFile();
  2044. assert path.exists() == isDirectory || isFile;
  2045. boolean exists = isDirectory || isFile;
  2046. boolean canExecute = exists && !isDirectory && canExecute(path);
  2047. boolean isSymlink = false;
  2048. Instant lastModified = exists ? lastModifiedInstant(path) : EPOCH;
  2049. long createTime = 0L;
  2050. return new Attributes(this, path, exists, isDirectory, canExecute,
  2051. isSymlink, isFile, createTime, lastModified, -1);
  2052. }
  2053. /**
  2054. * Normalize the unicode path to composed form.
  2055. *
  2056. * @param file
  2057. * a {@link java.io.File} object.
  2058. * @return NFC-format File
  2059. * @since 3.3
  2060. */
  2061. public File normalize(File file) {
  2062. return file;
  2063. }
  2064. /**
  2065. * Normalize the unicode path to composed form.
  2066. *
  2067. * @param name
  2068. * path name
  2069. * @return NFC-format string
  2070. * @since 3.3
  2071. */
  2072. public String normalize(String name) {
  2073. return name;
  2074. }
  2075. /**
  2076. * This runnable will consume an input stream's content into an output
  2077. * stream as soon as it gets available.
  2078. * <p>
  2079. * Typically used to empty processes' standard output and error, preventing
  2080. * them to choke.
  2081. * </p>
  2082. * <p>
  2083. * <b>Note</b> that a {@link StreamGobbler} will never close either of its
  2084. * streams.
  2085. * </p>
  2086. */
  2087. private static class StreamGobbler implements Runnable {
  2088. private InputStream in;
  2089. private OutputStream out;
  2090. public StreamGobbler(InputStream stream, OutputStream output) {
  2091. this.in = stream;
  2092. this.out = output;
  2093. }
  2094. @Override
  2095. public void run() {
  2096. try {
  2097. copy();
  2098. } catch (IOException e) {
  2099. // Do nothing on read failure; leave streams open.
  2100. }
  2101. }
  2102. void copy() throws IOException {
  2103. boolean writeFailure = false;
  2104. byte buffer[] = new byte[4096];
  2105. int readBytes;
  2106. while ((readBytes = in.read(buffer)) != -1) {
  2107. // Do not try to write again after a failure, but keep
  2108. // reading as long as possible to prevent the input stream
  2109. // from choking.
  2110. if (!writeFailure && out != null) {
  2111. try {
  2112. out.write(buffer, 0, readBytes);
  2113. out.flush();
  2114. } catch (IOException e) {
  2115. writeFailure = true;
  2116. }
  2117. }
  2118. }
  2119. }
  2120. }
  2121. }