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