<commit_before>/*  Copyright (c) 2008 Konrad-Zuse-Zentrum fuer Informationstechnik Berlin and
    Barcelona Supercomputing Center - Centro Nacional de Supercomputacion.

    This file is part of XtreemFS. XtreemFS is part of XtreemOS, a Linux-based
    Grid Operating System, see <http://www.xtreemos.eu> for more details.
    The XtreemOS project has been developed with the financial support of the
    European Commission's IST program under contract #FP6-033576.

    XtreemFS is free software: you can redistribute it and/or modify it under
    the terms of the GNU General Public License as published by the Free
    Software Foundation, either version 2 of the License, or (at your option)
    any later version.

    XtreemFS is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with XtreemFS. If not, see <http://www.gnu.org/licenses/>.
 */
/*
 * AUTHORS: <NAME> (ZIB), <NAME> (ZIB), <NAME> (BSC)
 */

package org.xtreemfs.common;

import java.net.InetSocketAddress;

import org.xtreemfs.common.logging.Logging;
import org.xtreemfs.common.logging.Logging.Category;
import org.xtreemfs.dir.client.DIRClient;
import org.xtreemfs.foundation.LifeCycleThread;
import org.xtreemfs.foundation.oncrpc.client.RPCNIOSocketClient;
import org.xtreemfs.foundation.oncrpc.client.RPCResponse;

/**
 * A class that offers a local time w/ adjustable granularity and a global time
 * based on the time reported by the DIR. Global time is adjusted periodically.
 * This class should be used to minimize the number of calls to
 * System.currentTimeMillis which is a costly system call on Linux. Moreover it
 * offers a system-global time.
 * 
 * @author bjko
 */
public final class TimeSync extends LifeCycleThread {
    
    /**
     * A dir client used to synchronize clocks
     */
    private DIRClient        dir;
    
    /**
     * interval in ms to wait between to synchronizations.
     */
    private final int        timeSyncInterval;
    
    /**
     * interval between updates of the local system clock.
     */
    private final int        localTimeRenew;
    
    /**
     * local sys time as of last update
     */
    private volatile long    localSysTime;
    
    /**
     * drift between local clock and global time as of last resync() operation.
     */
    private volatile long    currentDrift;
    
    /**
     * set to true to stop thread
     */
    private volatile boolean quit;
    
    /**
     * timestamp of last resync operation
     */
    private volatile long    lastSync;

    private volatile int     syncRTT;

    private volatile boolean syncSuccess;
    
    private static TimeSync  theInstance;
    
    /**
     * Creates a new instance of TimeSync
     * 
     * @dir a directory server to use for synchronizing clocks, can be null for
     *      test setups only
     */
    private TimeSync(DIRClient dir, int timeSyncInterval, int localTimeRenew) {
        super("TimeSync Thread");
        setDaemon(true);
        this.localTimeRenew = localTimeRenew;
        this.timeSyncInterval = timeSyncInterval;
        this.dir = dir;
        this.syncSuccess = false;
    }
    
    /**
     * main loop
     */
    @Override
    public void run() {
        TimeSync.theInstance = this;
        notifyStarted();
        String tsStatus = " using the local clock (precision is " + this.localTimeRenew + "ms)";
        if (this.dir != null) {
            tsStatus = " and remote sync every " + this.timeSyncInterval + "ms";
        }
        Logging.logMessage(Logging.LEVEL_INFO, Category.lifecycle, this, "TimeSync is running %s", tsStatus);
        while (!quit) {
            localSysTime = System.currentTimeMillis();
            if (localSysTime - lastSync > timeSyncInterval) {
                resync();
            }
            if (!quit) {
                try {
                    TimeSync.sleep(localTimeRenew);
                } catch (InterruptedException ex) {
                    break;
                }
            }
            
        }
        
        notifyStopped();
        syncSuccess = false;
        theInstance = null;
    }
    
    /**
     * Initializes the time synchronizer. Note that only the first invocation of
     * this method has an effect, any further invocations will be ignored.
     * 
     * @param dir
     * @param timeSyncInterval
     * @param localTimeRenew
     * @param dirAuthStr
     */
    public static TimeSync initialize(DIRClient dir, int timeSyncInterval, int localTimeRenew) {
        
        if (theInstance != null) {
            Logging.logMessage(Logging.LEVEL_WARN, Category.lifecycle, null, "time sync already running",
                new Object[0]);
            return theInstance;
        }
        
        TimeSync s = new TimeSync(dir, timeSyncInterval, localTimeRenew);
        s.start();
        return s;
    }
    
    public static TimeSync initializeLocal(int timeSyncInterval, int localTimeRenew) {
        if (theInstance != null) {
            Logging.logMessage(Logging.LEVEL_WARN, Category.lifecycle, null, "time sync already running",
                new Object[0]);
            return theInstance;
        }
        
        TimeSync s = new TimeSync(null, timeSyncInterval, localTimeRenew);
        s.start();<commit_msg>servers: TimeSync initialize is now fully synchornous<commit_after>/*  Copyright (c) 2008 Konrad-Zuse-Zentrum fuer Informationstechnik Berlin and
    Barcelona Supercomputing Center - Centro Nacional de Supercomputacion.

    This file is part of XtreemFS. XtreemFS is part of XtreemOS, a Linux-based
    Grid Operating System, see <http://www.xtreemos.eu> for more details.
    The XtreemOS project has been developed with the financial support of the
    European Commission's IST program under contract #FP6-033576.

    XtreemFS is free software: you can redistribute it and/or modify it under
    the terms of the GNU General Public License as published by the Free
    Software Foundation, either version 2 of the License, or (at your option)
    any later version.

    XtreemFS is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with XtreemFS. If not, see <http://www.gnu.org/licenses/>.
 */
/*
 * AUTHORS: <NAME> (ZIB), <NAME> (ZIB), <NAME> (BSC)
 */

package org.xtreemfs.common;

import java.net.InetSocketAddress;

import org.xtreemfs.common.logging.Logging;
import org.xtreemfs.common.logging.Logging.Category;
import org.xtreemfs.dir.client.DIRClient;
import org.xtreemfs.foundation.LifeCycleThread;
import org.xtreemfs.foundation.oncrpc.client.RPCNIOSocketClient;
import org.xtreemfs.foundation.oncrpc.client.RPCResponse;

/**
 * A class that offers a local time w/ adjustable granularity and a global time
 * based on the time reported by the DIR. Global time is adjusted periodically.
 * This class should be used to minimize the number of calls to
 * System.currentTimeMillis which is a costly system call on Linux. Moreover it
 * offers a system-global time.
 * 
 * @author bjko
 */
public final class TimeSync extends LifeCycleThread {
    
    /**
     * A dir client used to synchronize clocks
     */
    private DIRClient        dir;
    
    /**
     * interval in ms to wait between to synchronizations.
     */
    private final int        timeSyncInterval;
    
    /**
     * interval between updates of the local system clock.
     */
    private final int        localTimeRenew;
    
    /**
     * local sys time as of last update
     */
    private volatile long    localSysTime;
    
    /**
     * drift between local clock and global time as of last resync() operation.
     */
    private volatile long    currentDrift;
    
    /**
     * set to true to stop thread
     */
    private volatile boolean quit;
    
    /**
     * timestamp of last resync operation
     */
    private volatile long    lastSync;

    private volatile int     syncRTT;

    private volatile boolean syncSuccess;
    
    private static TimeSync  theInstance;
    
    /**
     * Creates a new instance of TimeSync
     * 
     * @dir a directory server to use for synchronizing clocks, can be null for
     *      test setups only
     */
    private TimeSync(DIRClient dir, int timeSyncInterval, int localTimeRenew) {
        super("TimeSync Thread");
        setDaemon(true);
        this.localTimeRenew = localTimeRenew;
        this.timeSyncInterval = timeSyncInterval;
        this.dir = dir;
        this.syncSuccess = false;
    }
    
    /**
     * main loop
     */
    @Override
    public void run() {
        TimeSync.theInstance = this;
        notifyStarted();
        String tsStatus = " using the local clock (precision is " + this.localTimeRenew + "ms)";
        if (this.dir != null) {
            tsStatus = " and remote sync every " + this.timeSyncInterval + "ms";
        }
        Logging.logMessage(Logging.LEVEL_INFO, Category.lifecycle, this, "TimeSync is running %s", tsStatus);
        while (!quit) {
            localSysTime = System.currentTimeMillis();
            if (localSysTime - lastSync > timeSyncInterval) {
                resync();
            }
            if (!quit) {
                try {
                    TimeSync.sleep(localTimeRenew);
                } catch (InterruptedException ex) {
                    break;
                }
            }
            
        }
        
        notifyStopped();
        syncSuccess = false;
        theInstance = null;
    }
    
    /**
     * Initializes the time synchronizer. Note that only the first invocation of
     * this method has an effect, any further invocations will be ignored.
     * 
     * @param dir
     * @param timeSyncInterval
     * @param localTimeRenew
     * @param dirAuthStr
     */
    public static TimeSync initialize(DIRClient dir, int timeSyncInterval, int localTimeRenew)
            throws Exception {
        
        if (theInstance != null) {
            Logging.logMessage(Logging.LEVEL_WARN, Category.lifecycle, null, "time sync already running",
                new Object[0]);
            return theInstance;
        }
        
        TimeSync s = new TimeSync(dir, timeSyncInterval, localTimeRenew);
        s.start();
        s.waitForStartup();
        return s;
    }
    
    public static TimeSync initializeLocal(int timeSyncInterval, int localTimeRenew) {
        if (theInstance != null) {
            Logging.logMessage(Logging.LEVEL_WARN, Category.lifecycle, null, "time sync already running",
                new Object[0]);
            return theInstance;
        }
        
        TimeSync s = new TimeSync(null, timeSyncInterval, localTimeRenew);
        s.start();
{'fraction_non_alphanumeric': 0.07538503107268306, 'fraction_numerical': 0.002521840943889039, 'mean_word_length': 2.2572601936051626, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5210700', 'n_tokens_mistral': 3065, 'n_tokens_neox': 2977, 'n_words': 1044}