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

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