You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mesos.apache.org by be...@apache.org on 2011/06/05 07:38:31 UTC

svn commit: r1131831 - in /incubator/mesos/trunk/src: ./ tests/ third_party/libprocess/

Author: benh
Date: Sun Jun  5 05:38:30 2011
New Revision: 1131831

URL: http://svn.apache.org/viewvc?rev=1131831&view=rev
Log:
Adding clock and filter functionality to libprocess to make testing easier (initial commit from patch to make branch clean).

Modified:
    incubator/mesos/trunk/src/master.cpp
    incubator/mesos/trunk/src/master.hpp
    incubator/mesos/trunk/src/messages.hpp
    incubator/mesos/trunk/src/slave.cpp
    incubator/mesos/trunk/src/tests/test_master.cpp
    incubator/mesos/trunk/src/third_party/libprocess/process.cpp
    incubator/mesos/trunk/src/third_party/libprocess/process.hpp
    incubator/mesos/trunk/src/third_party/libprocess/serialization.cpp
    incubator/mesos/trunk/src/third_party/libprocess/serialization.hpp

Modified: incubator/mesos/trunk/src/master.cpp
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/src/master.cpp?rev=1131831&r1=1131830&r2=1131831&view=diff
==============================================================================
--- incubator/mesos/trunk/src/master.cpp (original)
+++ incubator/mesos/trunk/src/master.cpp Sun Jun  5 05:38:30 2011
@@ -38,7 +38,6 @@ protected:
   {
     link(master);
     do {
-      // TODO: Make timer interval configurable, and hopefully less than 1 sec
       switch (receive(1)) {
       case PROCESS_TIMEOUT:
 	send(master, pack<M2M_TIMER_TICK>());
@@ -293,9 +292,8 @@ void Master::operator () ()
     case F2M_REGISTER_FRAMEWORK: {
       FrameworkID fid = lexical_cast<string>(masterId) + "-"
 	+ lexical_cast<string>(nextFrameworkId++);
-      Framework *framework = new Framework(from(), fid);
-      unpack<F2M_REGISTER_FRAMEWORK>(framework->name,
-				     framework->user,
+      Framework *framework = new Framework(from(), fid, elapsed());
+      unpack<F2M_REGISTER_FRAMEWORK>(framework->name, framework->user,
 				     framework->executorInfo);
       LOG(INFO) << "Registering " << framework << " at " << framework->pid;
       addFramework(framework);
@@ -303,12 +301,10 @@ void Master::operator () ()
     }
 
     case F2M_REREGISTER_FRAMEWORK: {
-      Framework *framework = new Framework(from());
+      Framework *framework = new Framework(from(), "", elapsed());
       bool failover;
-      unpack<F2M_REREGISTER_FRAMEWORK>(framework->id,
-                                       framework->name,
-                                       framework->user,
-                                       framework->executorInfo,
+      unpack<F2M_REREGISTER_FRAMEWORK>(framework->id, framework->name,
+                                       framework->user, framework->executorInfo,
                                        failover);
 
       if (framework->id == "") {
@@ -397,30 +393,32 @@ void Master::operator () ()
     }
 
     case S2M_REGISTER_SLAVE: {
-      string slaveId = lexical_cast<string>(masterId) + "-" + lexical_cast<string>(nextSlaveId++);
-
-      Slave *slave = new Slave(from(), slaveId);
+      string slaveId = lexical_cast<string>(masterId) + "-"
+        + lexical_cast<string>(nextSlaveId++);
+      Slave *slave = new Slave(from(), slaveId, elapsed());
       unpack<S2M_REGISTER_SLAVE>(slave->hostname, slave->publicDns,
                                  slave->resources);
       LOG(INFO) << "Registering " << slave << " at " << slave->pid;
       slaves[slave->id] = slave;
       pidToSid[slave->pid] = slave->id;
       link(slave->pid);
-      send(slave->pid, pack<M2S_REGISTER_REPLY>(slave->id));
+      send(slave->pid,
+	   pack<M2S_REGISTER_REPLY>(slave->id, HEARTBEAT_INTERVAL));
       allocator->slaveAdded(slave);
       break;
     }
 
     case S2M_REREGISTER_SLAVE: {
-      Slave *slave = new Slave(from());
+      Slave *slave = new Slave(from(), "", elapsed());
       vector<Task> taskVec;
-
       unpack<S2M_REREGISTER_SLAVE>(slave->id, slave->hostname, slave->publicDns,
-      				   slave->resources, taskVec);
+                                   slave->resources, taskVec);
 
       if (slave->id == "") {
-        slave->id = lexical_cast<string>(masterId) + "-" + lexical_cast<string>(nextSlaveId++);
-        DLOG(WARNING) << "Slave re-registered without a SlaveID, generating a new id for it.";
+        slave->id = lexical_cast<string>(masterId) + "-"
+          + lexical_cast<string>(nextSlaveId++);
+        DLOG(WARNING) << "Slave re-registered without a SlaveID, "
+                      << "generating a new id for it.";
       }
 
       foreach(Task &ti, taskVec) {
@@ -437,14 +435,9 @@ void Master::operator () ()
       slaves[slave->id] = slave;
       pidToSid[slave->pid] = slave->id;
       link(slave->pid);
-      send(slave->pid, pack<M2S_REREGISTER_REPLY>(slave->id));
+      send(slave->pid,
+           pack<M2S_REREGISTER_REPLY>(slave->id, HEARTBEAT_INTERVAL));
       allocator->slaveAdded(slave);
-
-      timeval tv;
-      gettimeofday(&tv, NULL);
-       
-      DLOG(INFO) << tv.tv_sec << "." << tv.tv_usec << " STAT: Slave count: " << slaves.size() << " Framework count: " << frameworks.size();
-       
       break;
     }
 
@@ -583,7 +576,7 @@ void Master::operator () ()
       unpack<SH2M_HEARTBEAT>(sid);
       Slave *slave = lookupSlave(sid);
       if (slave != NULL) {
-        slave->lastHeartbeat = time(NULL);
+        slave->lastHeartbeat = elapsed();
       } else {
         LOG(WARNING) << "Received heartbeat for UNKNOWN slave " << sid
                      << " from " << from();
@@ -594,15 +587,15 @@ void Master::operator () ()
     case M2M_TIMER_TICK: {
       unordered_map<SlaveID, Slave *> slavesCopy = slaves;
       foreachpair (_, Slave *slave, slavesCopy) {
-        if (slave->lastHeartbeat + HEARTBEAT_TIMEOUT <= time(NULL)) {
-          LOG(INFO) << slave << " missing heartbeats ... considering disconnected";
-          removeSlave(slave);
-        }
+	if (slave->lastHeartbeat + HEARTBEAT_TIMEOUT <= elapsed()) {
+	  LOG(INFO) << slave << " missing heartbeats ... considering disconnected";
+	  removeSlave(slave);
+	}
       }
 
       // Check which framework filters can be expired.
       foreachpair (_, Framework *framework, frameworks)
-        framework->removeExpiredFilters();
+        framework->removeExpiredFilters(elapsed());
 
       // Do allocations!
       allocator->timerTick();
@@ -746,7 +739,7 @@ void Master::processOfferReply(SlotOffer
   // If there are resources left on some slaves, add filters for them
   vector<SlaveResources> resourcesLeft;
   int timeout = params.getInt32("timeout", DEFAULT_REFUSAL_TIMEOUT);
-  time_t expiry = (timeout == -1) ? 0 : time(0) + timeout;
+  double expiry = (timeout == -1) ? 0 : elapsed() + timeout;
   foreachpair (Slave *s, Resources offRes, offerResources) {
     Resources respRes = responseResources[s];
     Resources left = offRes - respRes;

Modified: incubator/mesos/trunk/src/master.hpp
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/src/master.hpp?rev=1131831&r1=1131830&r2=1131831&view=diff
==============================================================================
--- incubator/mesos/trunk/src/master.hpp (original)
+++ incubator/mesos/trunk/src/master.hpp Sun Jun  5 05:38:30 2011
@@ -51,7 +51,7 @@ using namespace nexus::internal;
 const int MAX_OFFERS_PER_FRAMEWORK = 50;
 
 // Default number of seconds until a refused slot is resent to a framework.
-const time_t DEFAULT_REFUSAL_TIMEOUT = 5;
+const double DEFAULT_REFUSAL_TIMEOUT = 5;
 
 // Minimum number of cpus / task.
 const int32_t MIN_CPUS = 1;
@@ -65,8 +65,11 @@ const int32_t MAX_CPUS = 1000 * 1000;
 // Maximum amount of memory / machine.
 const int64_t MAX_MEM = 1024LL * 1024LL * 1024LL * 1024LL * 1024LL;
 
-// Acceptable time since we saw the last heartbeat.
-const time_t HEARTBEAT_TIMEOUT = 4;
+// Interval that slaves should send heartbeats.
+const double HEARTBEAT_INTERVAL = 2;
+
+// Acceptable time since we saw the last heartbeat (four heartbeats).
+const double HEARTBEAT_TIMEOUT = HEARTBEAT_INTERVAL * 4;
 
 // Some forward declarations
 class Slave;
@@ -105,7 +108,7 @@ struct Framework
   string name;
   string user;
   ExecutorInfo executorInfo;
-  time_t connectTime;
+  double connectTime;
 
   unordered_map<TaskID, Task *> tasks;
   unordered_set<SlotOffer *> slotOffers; // Active offers given to this framework
@@ -114,13 +117,10 @@ struct Framework
   
   // Contains a time of unfiltering for each slave we've filtered,
   // or 0 for slaves that we want to keep filtered forever
-  unordered_map<Slave *, time_t> slaveFilter;
+  unordered_map<Slave *, double> slaveFilter;
 
-  Framework(const PID &_pid, FrameworkID _id = "")
-    : pid(_pid), id(_id), active(true)
-  {
-    time(&connectTime);
-  }
+  Framework(const PID &_pid, FrameworkID _id, double time)
+    : pid(_pid), id(_id), active(true), connectTime(time) {}
   
   Task * lookupTask(TaskID tid)
   {
@@ -175,11 +175,10 @@ struct Framework
     return slaveFilter.find(slave) != slaveFilter.end();
   }
   
-  void removeExpiredFilters()
-  {  
-    time_t now = time(0);
+  void removeExpiredFilters(double now)
+  {
     vector<Slave *> toRemove;
-    foreachpair (Slave *slave, time_t removalTime, slaveFilter)
+    foreachpair (Slave *slave, double removalTime, slaveFilter)
       if (removalTime != 0 && removalTime <= now)
         toRemove.push_back(slave);
     foreach (Slave *slave, toRemove)
@@ -196,8 +195,8 @@ struct Slave
   bool active; // Turns false when slave is being removed
   string hostname;
   string publicDns;
-  time_t connectTime;
-  time_t lastHeartbeat;
+  double connectTime;
+  double lastHeartbeat;
   
   Resources resources;        // Total resources on slave
   Resources resourcesOffered; // Resources currently in offers
@@ -206,8 +205,10 @@ struct Slave
   unordered_map<pair<FrameworkID, TaskID>, Task *> tasks;
   unordered_set<SlotOffer *> slotOffers; // Active offers of slots on this slave
   
-  Slave(const PID &_pid, SlaveID _id = "") : pid(_pid), id(_id), active(true) {
-    connectTime = lastHeartbeat = time(NULL);
+  Slave(const PID &_pid, SlaveID _id, double time)
+    : pid(_pid), id(_id), active(true)
+  {
+    connectTime = lastHeartbeat = time;
   }
 
   Task * lookupTask(FrameworkID fid, TaskID tid)

Modified: incubator/mesos/trunk/src/messages.hpp
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/src/messages.hpp?rev=1131831&r1=1131830&r2=1131831&view=diff
==============================================================================
--- incubator/mesos/trunk/src/messages.hpp (original)
+++ incubator/mesos/trunk/src/messages.hpp Sun Jun  5 05:38:30 2011
@@ -244,10 +244,12 @@ TUPLE(GOT_MASTER_ID,
       (std::string /* id */));
   
 TUPLE(M2S_REGISTER_REPLY,
-      (SlaveID));
+      (SlaveID,
+       double /*heartbeat interval*/));
 
 TUPLE(M2S_REREGISTER_REPLY,
-      (SlaveID));
+      (SlaveID,
+       double /*heartbeat interval*/));
 
 TUPLE(M2S_RUN_TASK,
       (FrameworkID,

Modified: incubator/mesos/trunk/src/slave.cpp
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/src/slave.cpp?rev=1131831&r1=1131830&r2=1131831&view=diff
==============================================================================
--- incubator/mesos/trunk/src/slave.cpp (original)
+++ incubator/mesos/trunk/src/slave.cpp Sun Jun  5 05:38:30 2011
@@ -39,13 +39,14 @@ private:
   PID master;
   PID slave;
   SlaveID sid;
+  double interval;
 
 protected:
   void operator () ()
   {
     link(slave);
     do {
-      switch (receive(2)) {
+      switch (receive(interval)) {
       case PROCESS_TIMEOUT:
 	send(master, pack<SH2M_HEARTBEAT>(sid));
 	break;
@@ -56,8 +57,8 @@ protected:
   }
 
 public:
-  Heart(const PID &_master, const PID &_slave, SlaveID _sid)
-    : master(_master), slave(_slave), sid(_sid) {}
+  Heart(const PID &_master, const PID &_slave, SlaveID _sid, double _interval)
+    : master(_master), slave(_slave), sid(_sid), interval(_interval) {}
 };
 
 } /* namespace */
@@ -170,9 +171,10 @@ void Slave::operator () ()
       }
 
       case M2S_REGISTER_REPLY: {
-        unpack<M2S_REGISTER_REPLY>(this->id);
+	double interval = 0;
+        unpack<M2S_REGISTER_REPLY>(this->id, interval);
         LOG(INFO) << "Registered with master; given slave ID " << this->id;
-        link(spawn(new Heart(master, this->getPID(), this->id)));
+        link(spawn(new Heart(master, this->getPID(), this->id, interval)));
         isolationModule = createIsolationModule();
         if (!isolationModule)
           LOG(FATAL) << "Unrecognized isolation type: " << isolationType;
@@ -181,11 +183,12 @@ void Slave::operator () ()
       
       case M2S_REREGISTER_REPLY: {
         FrameworkID tmpfid;
-        unpack<M2S_REGISTER_REPLY>(tmpfid);
+	double interval = 0;
+        unpack<M2S_REGISTER_REPLY>(tmpfid, interval);
         LOG(INFO) << "RE-registered with master; given slave ID " << tmpfid << " had "<< this->id;
         if (this->id == "")
           this->id = tmpfid;
-        link(spawn(new Heart(master, getPID(), this->id)));
+        link(spawn(new Heart(master, getPID(), this->id, interval)));
         break;
       }
       

Modified: incubator/mesos/trunk/src/tests/test_master.cpp
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/src/tests/test_master.cpp?rev=1131831&r1=1131830&r2=1131831&view=diff
==============================================================================
--- incubator/mesos/trunk/src/tests/test_master.cpp (original)
+++ incubator/mesos/trunk/src/tests/test_master.cpp Sun Jun  5 05:38:30 2011
@@ -343,8 +343,6 @@ TEST(MasterTest, SlaveLost)
 }
 
 
-/* TODO(benh): Test lost slave due to missing heartbeats. */
-
 
 class FailoverScheduler : public Scheduler
 {
@@ -421,3 +419,58 @@ TEST(MasterTest, SchedulerFailover)
 
   local::shutdown();
 }
+
+
+/***************************************************************
+ *                                                             *
+ * ALL TESTS BELOW HERE MANUALLY CONTROL THE LIBPROCESS CLOCK! *
+ *                                                             *
+ ***************************************************************/
+
+class HeartbeatMessageFilter : public MessageFilter
+{
+public:
+  bool filter(struct msg *msg) {
+    return msg->id == SH2M_HEARTBEAT;
+  }
+};
+
+
+TEST(MasterTest, SlavePartitioned)
+{
+  ASSERT_TRUE(GTEST_IS_THREADSAFE);
+
+  ProcessClock *clock = Process::clock();
+
+  Master m;
+  PID master = Process::spawn(&m);
+
+  Slave s(Resources(2, 1 * Gigabyte), true);
+  PID slave = Process::spawn(&s);
+
+  BasicMasterDetector detector(master, slave, true);
+
+  SlaveLostScheduler sched(slave);
+  NexusSchedulerDriver driver(&sched, master);
+
+  driver.start();
+
+  HeartbeatMessageFilter filter;
+  Process::filter(&filter);
+
+  clock->advance(master::HEARTBEAT_TIMEOUT);
+
+  driver.join();
+
+  EXPECT_TRUE(sched.slaveLostCalled);
+
+  // Explicitely shut down the slave to avoid slave output from
+  // commiting suicide when the master gets killed.
+  Process::post(slave, S2S_SHUTDOWN);
+  Process::wait(slave);
+
+  Process::post(master, M2M_SHUTDOWN);
+  Process::wait(master);
+
+  Process::filter(NULL);
+}

Modified: incubator/mesos/trunk/src/third_party/libprocess/process.cpp
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/src/third_party/libprocess/process.cpp?rev=1131831&r1=1131830&r2=1131831&view=diff
==============================================================================
--- incubator/mesos/trunk/src/third_party/libprocess/process.cpp (original)
+++ incubator/mesos/trunk/src/third_party/libprocess/process.cpp Sun Jun  5 05:38:30 2011
@@ -80,6 +80,7 @@ using std::find;
 using std::list;
 using std::make_pair;
 using std::map;
+using std::max;
 using std::pair;
 using std::queue;
 using std::set;
@@ -146,16 +147,16 @@ using std::stack;
 
 
 /* Local server socket. */
-static int s;
+static int s = -1;
 
 /* Local IP address. */
-static uint32_t ip;
+static uint32_t ip = 0;
 
 /* Local port. */
-static uint16_t port;
+static uint16_t port = 0;
 
 /* Event loop. */
-static struct ev_loop *loop;
+static struct ev_loop *loop = NULL;
 
 /* Queue of new I/O watchers. */
 static queue<ev_io *> *io_watchersq = new queue<ev_io *>();
@@ -180,10 +181,11 @@ static int timers_lock = UNLOCKED;
 static pthread_mutex_t timers_mutex = PTHREAD_MUTEX_INITIALIZER;
 #endif /* USE_LITHE */
 
-/* Map (sorted) of process timers. */
-typedef tuple<ev_tstamp, Process *, int> timeout_t;
-static map<ev_tstamp, list<timeout_t> > *timers =
-  new map<ev_tstamp, list<timeout_t> >();
+/* Map of process timers (we exploit that the map is SORTED!). */
+typedef tuple<double, Process *, int> timeout_t;
+typedef list<timeout_t> timeouts_t;
+static map<ev_tstamp, timeouts_t> *timers =
+  new map<ev_tstamp, timeouts_t>();
 
 /* Flag to indicate whether or to update the timer on async interrupt. */
 static bool update_timer = false;
@@ -224,9 +226,6 @@ static int idle = 0;
 /* Scheduler gate. */
 static Gate *gate = new Gate();
 
-/* Status of infrastructure initialization (done lazily). */
-static bool initialized = false;
-
 /* Stack of stacks. */
 static stack<void *> *stacks = new stack<void *>();
 
@@ -248,6 +247,31 @@ static map<uint32_t, queue<struct msg *>
 static map<uint32_t, deque<uint32_t> > *replay_pipes =
   new map<uint32_t, deque<uint32_t> >();
 
+/* Filter? */
+static bool filtering = false;
+
+/* Filter. */
+static MessageFilter *filterer = NULL;
+
+/* Filtering mutex. */
+static pthread_mutex_t filter_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* Tick, tock ... */
+class InternalProcessClock : public ProcessClock
+{
+public:
+  map<Process *, double> elapsed;
+  double current;
+
+  InternalProcessClock();
+  ~InternalProcessClock();
+
+  virtual void advance(double secs);
+};
+
+static InternalProcessClock *clk = NULL;
+
+
 struct write_ctx {
   int len;
   struct msg *msg;
@@ -830,6 +854,25 @@ private:
   }
 
 public:
+  Process * lookup(const PID &pid)
+  {
+    if (!(pid.ip == ip && pid.port == port))
+      return NULL;
+
+    Process *process = NULL;
+
+    acquire(processes);
+    {
+      map<uint32_t, Process *>::iterator it = processes.find(pid.pipe);
+      if (it != processes.end()) {
+	process = it->second;
+      }
+    }
+    release(processes);
+
+    return process;
+  }
+
   void record(struct msg *msg)
   {
     assert(recording && !replaying);
@@ -1066,6 +1109,15 @@ public:
     /* TODO(benh): Assert that we are on the transition stack. */
 #endif /* USE_LITHE */
 
+    /* Remove from internal clock (if necessary). */
+    acquire(timers);
+    {
+      if (clk != NULL) {
+	clk->elapsed.erase(process);
+      }
+    }
+    release(timers);
+
     /* Inform link manager. */
     LinkManager::instance()->exited(process);
 
@@ -1361,7 +1413,7 @@ public:
     process->lock();
     {
       if (secs > 0) {
-	/* Setup the timeout. */
+	/* Create/Start the timeout. */
 	start_timeout(create_timeout(process, secs));
 
 	/* Context switch. */
@@ -1757,9 +1809,20 @@ public:
   timeout_t create_timeout(Process *process, double secs)
   {
     assert(process != NULL);
-//     ev_tstamp now = ev_now(loop);
-    ev_tstamp now = ev_time();
-    ev_tstamp tstamp = now + secs;
+
+    ev_tstamp tstamp;
+
+    acquire(timers);
+    {
+      if (clk != NULL) {
+	tstamp = clk->elapsed[process] + secs;
+      } else {
+	// TODO(benh): Unclear if want ev_now(...) or ev_time().
+	tstamp = ev_time() + secs;
+      }
+    }
+    release(timers);
+
     return make_tuple(tstamp, process, process->generation);
   }
 
@@ -1772,16 +1835,15 @@ public:
     acquire(timers);
     {
       if (timers->size() == 0 || tstamp < timers->begin()->first) {
-        // Need to interrupt the loop to update/set timer repeat.
-        (*timers)[tstamp].push_back(timeout);
-        update_timer = true;
-        ev_async_send(loop, &async_watcher);
+	// Need to interrupt the loop to update/set timer repeat.
+	(*timers)[tstamp].push_back(timeout);
+	update_timer = true;
+	ev_async_send(loop, &async_watcher);
       } else {
-        // Timer repeat is adequate, just add the timeout.
-        assert(timers->size() >= 1);
-        (*timers)[tstamp].push_back(timeout);
+	// Timer repeat is adequate, just add the timeout.
+	assert(timers->size() >= 1);
+	(*timers)[tstamp].push_back(timeout);
       }
-
     }
     release(timers);
   }
@@ -1793,26 +1855,22 @@ public:
 
     acquire(timers);
     {
-      /* Check if the timer has fired. */
-      ev_tstamp tstamp = timeout.get<0>();
-      if (timers->find(tstamp) != timers->end()) {
-	list<timeout_t> &timeouts = (*timers)[tstamp];
+      /* Check if the timer has fired (this is highly unoptimized). */
+      foreachpair (const ev_tstamp &tstamp, timeouts_t &timeouts, *timers) {
 	list<timeout_t>::iterator it = timeouts.begin();
 	while (it != timeouts.end()) {
 	  if (it->get<0>() == timeout.get<0>() &&
 	      it->get<1>() == timeout.get<1>() &&
 	      it->get<2>() == timeout.get<2>()) {
 	    timeouts.erase(it++);
+	    cancelled = true;
+	    break;
 	  } else {
 	    ++it;
 	  }
 	}
-
-	/* If no more timeouts for this time stamp then cleanup. */
-	if ((*timers)[tstamp].empty())
-	  timers->erase(tstamp);
-
-	cancelled = true;
+	if (cancelled)
+	  break;
       }
     }
     release(timers);
@@ -1899,16 +1957,32 @@ static void handle_async(struct ev_loop 
   {
     if (update_timer) {
       if (!timers->empty()) {
-// 	timer_watcher.repeat = timers->begin()->first - ev_now(loop);
-	timer_watcher.repeat = timers->begin()->first - ev_time();
-	/* If timer has elapsed feed the event immediately. */
-	if (timer_watcher.repeat <= 0) {
-	  timer_watcher.repeat = 0;
-	  ev_feed_event(loop, &timer_watcher, EV_TIMEOUT);
+	// Determine the current time.
+	ev_tstamp current_tstamp;
+	if (clk != NULL) {
+	  current_tstamp = clk->current;
 	} else {
+	  // TODO(benh): Unclear if want ev_now(...) or ev_time().
+	  current_tstamp = ev_time();
+	}
+
+	timer_watcher.repeat = timers->begin()->first - current_tstamp;
+
+	// Check when the timer event should fire.
+        if (timer_watcher.repeat <= 0) {
+	  // Feed the event now!
+	  timer_watcher.repeat = 0;
+	  ev_timer_again(loop, &timer_watcher);
+          ev_feed_event(loop, &timer_watcher, EV_TIMEOUT);
+        } else {
+	  // Only repeat the timer if not using a manual clock (a call
+	  // to ProcessClock::advance() will force a timer event later).
+	  if (clk != NULL && timer_watcher.repeat > 0)
+	    timer_watcher.repeat = 0;
 	  ev_timer_again(loop, &timer_watcher);
 	}
       }
+
       update_timer = false;
     }
   }
@@ -2272,8 +2346,14 @@ void handle_timeout(struct ev_loop *loop
 
   acquire(timers);
   {
-//     ev_tstamp now = ev_now(loop);
-    ev_tstamp now = ev_time();
+    ev_tstamp current_tstamp;
+
+    if (clk != NULL) {
+      current_tstamp = clk->current;
+    } else {
+      // TODO(benh): Unclear if want ev_now(...) or ev_time().
+      current_tstamp = ev_time();
+    }
 
     map<ev_tstamp, list<timeout_t> >::iterator it = timers->begin();
     map<ev_tstamp, list<timeout_t> >::iterator last = timers->begin();
@@ -2281,15 +2361,23 @@ void handle_timeout(struct ev_loop *loop
     for (; it != timers->end(); ++it) {
       // Check if timer has expired.
       ev_tstamp tstamp = it->first;
-      if (tstamp > now) {
+      if (tstamp > current_tstamp) {
 	last = it;
 	break;
       }
 
-      // Save all expired timeouts.
+      // Save expired timeouts and determine time elapsed/simulated.
       const list<timeout_t> &timeouts = it->second;
-      foreach (const timeout_t &timeout, timeouts)
+      foreach (const timeout_t &timeout, timeouts) {
+	if (clk != NULL) {
+	  // N.B. There should not be more than one timeout per process!
+	  Process *process = timeout.get<1>();
+	  double elapsed = timeout.get<0>();
+	  clk->elapsed[process] += elapsed;
+	}
+	// TODO(benh): Ensure deterministic order for testing?
 	timedout.push_back(timeout);
+      }
     }
 
     if (it == timers->end())
@@ -2297,12 +2385,14 @@ void handle_timeout(struct ev_loop *loop
     else if (last != timers->begin())
       timers->erase(timers->begin(), last);
 
-    if (!timers->empty()) {
-      timer_watcher.repeat = timers->begin()->first - now;
+    assert(timers->empty() || (timers->begin()->first > current_tstamp));
+
+    if (!timers->empty() && clk == NULL) {
+      timer_watcher.repeat = timers->begin()->first - current_tstamp;
       assert(timer_watcher.repeat > 0);
       ev_timer_again(loop, &timer_watcher);
     } else {
-      timer_watcher.repeat = 0.;
+      timer_watcher.repeat = 0;
       ev_timer_again(loop, &timer_watcher);
     }
 
@@ -2641,6 +2731,22 @@ void trampoline(int process0, int proces
 
 static void initialize()
 {
+  static volatile bool initialized = false;
+  static volatile bool initializing = true;
+
+  // Try and do the initialization or wait for it to complete.
+  if (initialized && !initializing) {
+    return;
+  } else if (initialized && initializing) {
+    while (initializing);
+    return;
+  } else {
+    if (!__sync_bool_compare_and_swap(&initialized, false, true)) {
+      while (initializing);
+      return;
+    }
+  }
+
 //   /* Install signal handler. */
 //   struct sigaction sa;
 
@@ -2758,6 +2864,7 @@ static void initialize()
 
   /* Set up socket. */
   struct sockaddr_in addr;
+  memset(&addr, 0, sizeof(addr));
   addr.sin_family = PF_INET;
   addr.sin_addr.s_addr = ip;
   addr.sin_port = htons(port);
@@ -2809,21 +2916,14 @@ static void initialize()
 
   if (pthread_create(&io_thread, NULL, node, loop) != 0)
     fatalerror("failed to initialize node (pthread_create)");
+
+  initializing = false;
 }
 
 
 Process::Process()
 {
-  static volatile bool initializing = true;
-  /* Confirm everything is initialized. */
-  if (!initialized) {
-    if (__sync_bool_compare_and_swap(&initialized, false, true)) {
-      initialize();
-      initializing = false;
-    }
-  }
-
-  while (initializing);
+  initialize();
 
 #ifdef USE_LITHE
   l = UNLOCKED;
@@ -2881,6 +2981,20 @@ void Process::enqueue(struct msg *msg)
   {
     assert (state != EXITED);
 
+    acquire(filter);
+    {
+      if (filtering) {
+        assert(filterer != NULL);
+        if (filterer->filter(msg)) {
+          free(msg);
+          release(filter);
+          unlock();
+          return;
+        }
+      }
+    }
+    release(filter);
+
     //cout << "enqueing pending message: " << msg << endl;
     msgs.push_back(msg);
 
@@ -3070,6 +3184,31 @@ MSGID Process::receive(double secs)
   if (recording)
     ProcessManager::instance()->record(current);
 
+  // Make sure elapsed timing is correct (i.e., preserve
+  // happens-before relationship).
+  acquire(timers);
+  {
+    if (clk != NULL) {
+      // Only do this if there is time that could be elapsed. Note
+      // that across different nodes (e.g., machines) we don't have
+      // elapsed timing info, so anyone trying to control the clock on
+      // two different nodes might get an unpleasent surprise if they
+      // are expecting some timing based happens-before relationship.
+      if (clk->elapsed[this] < clk->current &&
+	  current->from.ip == ip &&
+	  current->from.port == port) {
+	// Lookup the process (might die before we start looking).
+	Process *process = ProcessManager::instance()->lookup(current->from);
+
+	// Set new elapsed time (if the process isn't dead).
+	if (process != NULL) {
+	  clk->elapsed[this] = max(clk->elapsed[this], clk->elapsed[process]);
+	}
+      }
+    }
+  }
+  release(timers);
+
   return current->id;
 
  timeout:
@@ -3083,6 +3222,9 @@ MSGID Process::receive(double secs)
   current->id = PROCESS_TIMEOUT;
   current->len = 0;
 
+  if (recording)
+    ProcessManager::instance()->record(current);
+
   return current->id;
 }
 
@@ -3275,3 +3417,96 @@ void Process::invoke(const std::tr1::fun
   swapcontext(&proc_process->uctx, &proc_uctx_running);
   legacy = false;
 }
+
+
+double Process::elapsed()
+{
+  double now = 0;
+
+  acquire(timers);
+  {
+    if (clk != NULL) {
+      now = clk->elapsed[this];
+    } else {
+      // TODO(benh): Unclear if want ev_now(...) or ev_time().
+      now = ev_time();
+    }
+  }
+  release(timers);
+
+  return now;
+}
+
+
+ProcessClock * Process::clock()
+{
+  initialize();
+
+  // Update current timers to use a manually controlled clock.
+  acquire(timers);
+  {
+    // For now, only one global clock (rather than clock per process).
+    if (clk != NULL) {
+      release(timers);
+      return clk;
+    }
+
+    clk = new InternalProcessClock();
+
+    // The map is sorted, so updating it in place is a little
+    // tricky. For now we'll be lazy create a new map with the
+    // timeouts relative to the clock time and swap them below.
+    map<ev_tstamp, timeouts_t> *relative_timers =
+      new map<ev_tstamp, timeouts_t>();
+
+    foreachpair (const ev_tstamp &tstamp, const timeouts_t &timeouts, *timers) {
+      foreach (const timeout_t &timeout, timeouts) {
+	// TODO(benh): Do we want to consider only adding the remaining time?
+	ev_tstamp relative_tstamp = clk->current + timeout.get<0>();
+	(*relative_timers)[relative_tstamp].push_back(timeout);
+      }
+    }
+
+    // Update to use the warped timers.
+    delete timers;
+    timers = relative_timers;
+
+    // TODO(benh): Update the libev timer (can this ever be bad?).
+    update_timer = true;
+    ev_async_send(loop, &async_watcher);
+  }
+  release(timers);
+
+  return clk;
+}
+
+
+void Process::filter(MessageFilter *filter)
+{
+  acquire(filter);
+  {
+    filterer = filter;
+    filtering = filter != NULL;
+  }
+  release(filter);
+}
+
+
+InternalProcessClock::InternalProcessClock() : current(0) {}
+
+
+InternalProcessClock::~InternalProcessClock() {}
+
+
+void InternalProcessClock::advance(double secs)
+{
+  acquire(timers);
+  {
+    current += secs;
+
+    // TODO(benh): Update the libev timer (can this ever be bad?).
+    update_timer = true;
+    ev_async_send(loop, &async_watcher);
+  }
+  release(timers);
+}

Modified: incubator/mesos/trunk/src/third_party/libprocess/process.hpp
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/src/third_party/libprocess/process.hpp?rev=1131831&r1=1131830&r2=1131831&view=diff
==============================================================================
--- incubator/mesos/trunk/src/third_party/libprocess/process.hpp (original)
+++ incubator/mesos/trunk/src/third_party/libprocess/process.hpp Sun Jun  5 05:38:30 2011
@@ -53,6 +53,15 @@ struct msg
   uint32_t len;
 };
 
+class ProcessClock {
+public:
+  virtual void advance(double secs) = 0;
+};
+
+class MessageFilter {
+public:
+  virtual bool filter(struct msg *) = 0;
+};
 
 #ifdef USE_LITHE
 
@@ -207,6 +216,9 @@ protected:
   /* Returns true if operation on file descriptor is ready. */
   bool ready(int fd, int op);
 
+  /* Returns sub-second elapsed time (according to this process). */
+  double elapsed();
+
 public:
   virtual ~Process();
 
@@ -230,6 +242,12 @@ public:
 
   /* Invoke the thunk in a legacy safe way. */
   static void invoke(const std::tr1::function<void (void)> &thunk);
+
+  /* Manually control time using the returned clock. */
+  static ProcessClock * clock();
+
+  /* Filter messages to be enqueued (except for timeout messages). */
+  static void filter(MessageFilter *);
 };
 
 

Modified: incubator/mesos/trunk/src/third_party/libprocess/serialization.cpp
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/src/third_party/libprocess/serialization.cpp?rev=1131831&r1=1131830&r2=1131831&view=diff
==============================================================================
--- incubator/mesos/trunk/src/third_party/libprocess/serialization.cpp (original)
+++ incubator/mesos/trunk/src/third_party/libprocess/serialization.cpp Sun Jun  5 05:38:30 2011
@@ -31,6 +31,13 @@ void serializer::operator & (const int64
 }
 
 
+void serializer::operator & (const double &d)
+{
+  // TODO(*): Deal with endian issues?
+  stream.write((char *) &d, sizeof(d));
+}
+
+
 void serializer::operator & (const size_t &i)
 {
   if (sizeof(size_t) == sizeof(int32_t))
@@ -71,6 +78,7 @@ void deserializer::operator & (int32_t &
   i = ntohl(netInt);
 }
 
+
 void deserializer::operator & (int64_t &i)
 {
   uint32_t hiInt, loInt;
@@ -81,6 +89,14 @@ void deserializer::operator & (int64_t &
   i = (hi64 << 32) | lo64;
 }
 
+
+void deserializer::operator & (double &d)
+{
+  // TODO(*): Deal with endian issues?
+  stream.read((char *) &d, sizeof(d));
+}
+
+
 void deserializer::operator & (size_t &i)
 {
   if (sizeof(size_t) == sizeof(int32_t))
@@ -91,6 +107,7 @@ void deserializer::operator & (size_t &i
     abort();
 }  
 
+
 void deserializer::operator & (std::string &str)
 {
   size_t size;
@@ -99,6 +116,7 @@ void deserializer::operator & (std::stri
   stream.read((char *) str.data(), size);
 }
 
+
 void deserializer::operator & (PID &pid)
 {
   this->operator & ((int32_t &) pid.pipe);

Modified: incubator/mesos/trunk/src/third_party/libprocess/serialization.hpp
URL: http://svn.apache.org/viewvc/incubator/mesos/trunk/src/third_party/libprocess/serialization.hpp?rev=1131831&r1=1131830&r2=1131831&view=diff
==============================================================================
--- incubator/mesos/trunk/src/third_party/libprocess/serialization.hpp (original)
+++ incubator/mesos/trunk/src/third_party/libprocess/serialization.hpp Sun Jun  5 05:38:30 2011
@@ -17,6 +17,7 @@ struct serializer
   void operator & (const bool &);
   void operator & (const int32_t &);
   void operator & (const int64_t &);
+  void operator & (const double &);
   void operator & (const size_t &);
   void operator & (const std::string &);
   void operator & (const PID &);
@@ -31,6 +32,7 @@ struct deserializer
   void operator & (bool &);
   void operator & (int32_t &);
   void operator & (int64_t &);
+  void operator & (double &);
   void operator & (size_t &);
   void operator & (std::string &);
   void operator & (PID &);