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

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