/** * Waits for a condition to be satisfied. * * @param description a description of what causes condition to evaluate to true * @param condition the condition to wait on * @throws TimeoutException if the function times out while waiting for the condition to be true */ public static void waitFor(String description, Supplier<Boolean> condition) throws InterruptedException, TimeoutException { waitFor(description, condition, WaitForOptions.defaults()); }
@Override public void run() { while (true) { CommonUtils.sleepMs(intervalMs); if (Thread.interrupted()) { return; } stream.print("."); } } });
/** * Constructs a new custom authentication provider. * * @param providerName the name of the provider */ public CustomAuthenticationProvider(String providerName) { Class<?> customProviderClass; try { customProviderClass = Class.forName(providerName); } catch (ClassNotFoundException e) { throw new RuntimeException(providerName + " not found"); } mCustomProvider = (AuthenticationProvider) CommonUtils .createNewClassInstance(customProviderClass, null, null); }
@Override public boolean attempt() { if (mAttemptCount == 0) { // first attempt, set the start time mStartMs = CommonUtils.getCurrentMs(); mAttemptCount++; return true; } if (mSleepMs > 0) { CommonUtils.sleepMs(mSleepMs); } if ((CommonUtils.getCurrentMs() - mStartMs) <= mRetryTimeoutMs) { mAttemptCount++; return true; } return false; } }
private void edgeLockTest(LockMode take, LockMode tryToTake, boolean expectBlocking) throws Exception { InodeLockManager lockManager = new InodeLockManager(); AtomicBoolean threadFinished = new AtomicBoolean(false); LockResource lock = lockManager.lockEdge(new Edge(10, "name"), take); Thread t = new Thread(() -> { // Use a new Edge each time to make sure we aren't comparing edges by reference. try (LockResource lr = lockManager.lockEdge(new Edge(10, "name"), tryToTake)) { threadFinished.set(true); } }); t.start(); if (expectBlocking) { CommonUtils.sleepMs(20); assertFalse(threadFinished.get()); lock.close(); } CommonUtils.waitFor("lock to be acquired by the second thread", () -> threadFinished.get()); } }
/** * Formats time elapsed since the given start time (in milliseconds). * * @param startTimeMs start time in milliseconds * @param message prefix for the message to be printed * @return formatted string with the elapsed time (in milliseconds) */ public static String formatTimeTakenMs(long startTimeMs, String message) { return message + " took " + (CommonUtils.getCurrentMs() - startTimeMs) + " ms."; }
/** * Creates a new temp file to write to. */ private void initNewFile() throws IOException { mFile = new File(PathUtils.concatPath(CommonUtils.getTmpDir(mTmpDirs), UUID.randomUUID())); if (mHash != null) { mLocalOutputStream = new BufferedOutputStream(new DigestOutputStream(new FileOutputStream(mFile), mHash)); } else { mLocalOutputStream = new BufferedOutputStream(new FileOutputStream(mFile)); } mPartitionOffset = 0; LOG.debug("Init new temp file @ {}", mFile.getPath()); }
/** * Generates a path to use for a RocksDB database. This method incorporates randomness to avoid * creating multiple databases at the same path. * * @param baseDir the base directory path * @param dbName a name for the database * @return the generated database path */ public static String generateDbPath(String baseDir, String dbName) { return PathUtils.concatPath(baseDir, String.format("%s-%s-%s", dbName, System.currentTimeMillis(), CommonUtils.randomAlphaNumString(3))); }
print("Web Port: " + masterInfo.getWebPort()); print("Rpc Port: " + masterInfo.getRpcPort()); print("Started: " + CommonUtils.convertMsToDate(masterInfo.getStartTimeMs(), mDateFormatPattern)); print("Uptime: " + CommonUtils.convertMsToClockTime(masterInfo.getUpTimeMs())); print("Version: " + masterInfo.getVersion()); print("Safe Mode: " + masterInfo.getSafeMode());
/** * Gets uptime. * * @return the uptime */ public String getUptime() { return CommonUtils.convertMsToClockTime(System.currentTimeMillis() - mStartTimeMs); }
private void inodeLockTest(LockMode take, LockMode tryToTake, boolean expectBlocking) throws Exception { InodeLockManager lockManager = new InodeLockManager(); AtomicBoolean threadFinished = new AtomicBoolean(false); MutableInodeFile inode = MutableInodeFile.create(0, 0, "name", 0, CreateFileContext.defaults()); LockResource lock = lockManager.lockInode(inode, take); Thread t = new Thread(() -> { // Copy the inode to make sure we aren't comparing inodes by reference. MutableInodeFile inodeCopy = MutableInodeFile.fromJournalEntry(inode.toJournalEntry().getInodeFile()); try (LockResource lr = lockManager.lockInode(inodeCopy, tryToTake)) { threadFinished.set(true); } }); t.start(); if (expectBlocking) { CommonUtils.sleepMs(20); assertFalse(threadFinished.get()); lock.close(); } CommonUtils.waitFor("lock to be acquired by the second thread", () -> threadFinished.get()); }
/** * Tests the {@link CommonUtils#getCurrentMs()} and {@link CommonUtils#sleepMs(long)} methods. */ @Test public void getCurrentMsAndSleepMs() { long delta = 100; long startTime = CommonUtils.getCurrentMs(); CommonUtils.sleepMs(delta); long currentTime = CommonUtils.getCurrentMs(); /* Check that currentTime falls into the interval [startTime + delta; startTime + 2*delta] */ assertTrue(startTime + delta <= currentTime); assertTrue(currentTime <= 2 * delta + startTime); }
@Override public boolean attempt() { if (mFirstAttempt || (CommonUtils.getCurrentMs() - mLastAttempTimeMs) > mRefreshPeriodMs) { mLastAttempTimeMs = CommonUtils.getCurrentMs(); mFirstAttempt = false; return true; } return false; } }
/** * Creates a new instance of {@link SwiftMockOutputStream}. * * @param account simulated Swift account * @param containerName container name * @param objectName name of file or folder to write * @param tmpDirs a list of temporary directories */ public SwiftMockOutputStream(Account account, String containerName, String objectName, List<String> tmpDirs) throws IOException { try { mAccount = account; mContainerName = containerName; mObjectName = objectName; mFile = new File(PathUtils.concatPath(CommonUtils.getTmpDir(tmpDirs), UUID.randomUUID())); mOutputStream = new BufferedOutputStream(new FileOutputStream(mFile)); } catch (Exception e) { LOG.error(e.getMessage()); throw new IOException(e); } }
private static LocalityTier createRandomLocalityTier() { Random random = new Random(); String tier = CommonUtils.randomAlphaNumString(random.nextInt(10) + 1); String value = CommonUtils.randomAlphaNumString(random.nextInt(10) + 1); return new LocalityTier(tier, value); } }
.convertMsToClockTime(System.currentTimeMillis() - mMetaMaster.getStartTimeMs())) .setStartTime(CommonUtils.convertMsToDate(mMetaMaster.getStartTimeMs(), ServerConfiguration.get(PropertyKey.USER_DATE_FORMAT_PATTERN))) .setVersion(RuntimeConstants.VERSION)
/** * Starts {@link DailyMetadataBackup}. */ public void start() { Preconditions.checkState(mBackup == null); long delayedTimeInMillis = getTimeToNextBackup(); mBackup = mScheduledExecutor.scheduleAtFixedRate(this::dailyBackup, delayedTimeInMillis, FormatUtils.parseTimeSize("1day"), TimeUnit.MILLISECONDS); LOG.info("Daily metadata backup scheduled to start in {}", CommonUtils.convertMsToClockTime(delayedTimeInMillis)); }
@Override public boolean waitForReady(int timeoutMs) { try { CommonUtils.waitFor(this + " to start", () -> mStopped == false, WaitForOptions.defaults().setTimeoutMs(timeoutMs)); return true; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } catch (TimeoutException e) { return false; } } }
@Override public void run() { CommonUtils.sleepMs(lifetimeMs); LOG.info("Process has timed out after {}ms, exiting now", lifetimeMs); System.exit(-1); } }, "life-limiter").start();
/** * Factory method for {@link JournalFormatter}. * * @return the created formatter */ public static JournalFormatter create() { return CommonUtils.createNewClassInstance(ServerConfiguration .<JournalFormatter>getClass(PropertyKey.MASTER_JOURNAL_FORMATTER_CLASS), null, null); } }