本文整理汇总了C++中Future类的典型用法代码示例。如果您正苦于以下问题:C++ Future类的具体用法?C++ Future怎么用?C++ Future使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Future类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: TEST_P
// This test verifies that the scheduler will receive a `BadRequest` response
// when a teardown call is made with an incorrect stream ID header.
TEST_P(SchedulerHttpApiTest, TeardownWrongStreamId)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
// Retrieve the parameter passed as content type to this test.
const string contentType = GetParam();
process::http::Headers headers = createBasicAuthHeaders(DEFAULT_CREDENTIAL);
headers["Accept"] = contentType;
v1::FrameworkID frameworkId;
string streamId;
// Subscribe once to get a valid stream ID.
{
Call call;
call.set_type(Call::SUBSCRIBE);
Call::Subscribe* subscribe = call.mutable_subscribe();
subscribe->mutable_framework_info()->CopyFrom(v1::DEFAULT_FRAMEWORK_INFO);
Future<Response> response = process::http::streaming::post(
master.get()->pid,
"api/v1/scheduler",
headers,
serialize(call, contentType),
contentType);
AWAIT_EXPECT_RESPONSE_STATUS_EQ(OK().status, response);
AWAIT_EXPECT_RESPONSE_HEADER_EQ("chunked", "Transfer-Encoding", response);
ASSERT_EQ(Response::PIPE, response.get().type);
ASSERT_TRUE(response.get().headers.contains("Mesos-Stream-Id"));
streamId = response.get().headers.at("Mesos-Stream-Id");
Option<Pipe::Reader> reader = response.get().reader;
ASSERT_SOME(reader);
auto deserializer = lambda::bind(
&SchedulerHttpApiTest::deserialize, this, contentType, lambda::_1);
Reader<Event> responseDecoder(Decoder<Event>(deserializer), reader.get());
Future<Result<Event>> event = responseDecoder.read();
AWAIT_READY(event);
ASSERT_SOME(event.get());
// Check that the event type is subscribed and the framework ID is set.
ASSERT_EQ(Event::SUBSCRIBED, event.get().get().type());
EXPECT_NE("", event.get().get().subscribed().framework_id().value());
frameworkId = event.get().get().subscribed().framework_id();
}
// Subscribe again to invalidate the first stream ID and acquire another one.
{
Call call;
call.set_type(Call::SUBSCRIBE);
Call::Subscribe* subscribe = call.mutable_subscribe();
subscribe->mutable_framework_info()->CopyFrom(v1::DEFAULT_FRAMEWORK_INFO);
// Set the framework ID in the subscribe call.
call.mutable_framework_id()->CopyFrom(frameworkId);
subscribe->mutable_framework_info()->mutable_id()->CopyFrom(frameworkId);
Future<Response> response = process::http::streaming::post(
master.get()->pid,
"api/v1/scheduler",
headers,
serialize(call, contentType),
contentType);
AWAIT_EXPECT_RESPONSE_STATUS_EQ(OK().status, response);
AWAIT_EXPECT_RESPONSE_HEADER_EQ("chunked", "Transfer-Encoding", response);
ASSERT_EQ(Response::PIPE, response.get().type);
ASSERT_TRUE(response.get().headers.contains("Mesos-Stream-Id"));
// Make sure that the new stream ID is different.
ASSERT_NE(streamId, response.get().headers.at("Mesos-Stream-Id"));
Option<Pipe::Reader> reader = response.get().reader;
ASSERT_SOME(reader);
auto deserializer = lambda::bind(
&SchedulerHttpApiTest::deserialize, this, contentType, lambda::_1);
Reader<Event> responseDecoder(Decoder<Event>(deserializer), reader.get());
Future<Result<Event>> event = responseDecoder.read();
AWAIT_READY(event);
ASSERT_SOME(event.get());
ASSERT_EQ(Event::SUBSCRIBED, event.get().get().type());
EXPECT_NE("", event.get().get().subscribed().framework_id().value());
}
//.........这里部分代码省略.........
示例2: TEST_F
// This test verifies that a framework removal that comes before
// '_launchTasks()' is called results in recovery of resources.
TEST_F(MasterAuthorizationTest, FrameworkRemoved)
{
MockAuthorizer authorizer;
Try<PID<Master> > master = StartMaster(&authorizer);
ASSERT_SOME(master);
MockExecutor exec(DEFAULT_EXECUTOR_ID);
Try<PID<Slave> > slave = StartSlave(&exec);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _))
.Times(1);
Future<vector<Offer> > offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
EXPECT_NE(0u, offers.get().size());
TaskInfo task = createTask(offers.get()[0], "", DEFAULT_EXECUTOR_ID);
vector<TaskInfo> tasks;
tasks.push_back(task);
// Return a pending future from authorizer.
Future<Nothing> future;
Promise<bool> promise;
EXPECT_CALL(authorizer, authorize(An<const mesos::ACL::RunTasks&>()))
.WillOnce(DoAll(FutureSatisfy(&future),
Return(promise.future())));
driver.launchTasks(offers.get()[0].id(), tasks);
// Wait until authorization is in progress.
AWAIT_READY(future);
Future<Nothing> frameworkRemoved =
FUTURE_DISPATCH(_, &AllocatorProcess::frameworkRemoved);
// Now stop the framework.
driver.stop();
driver.join();
AWAIT_READY(frameworkRemoved);
Future<Nothing> resourcesRecovered =
FUTURE_DISPATCH(_, &AllocatorProcess::resourcesRecovered);
// Now complete authorization.
promise.set(true);
// No task launch should happen resulting in all resources being
// returned to the allocator.
AWAIT_READY(resourcesRecovered);
Shutdown(); // Must shutdown before 'containerizer' gets deallocated.
}
示例3: TEST_F
// This test ensures that an implicit reconciliation request results
// in updates for all non-terminal tasks known to the master.
TEST_F(ReconciliationTest, ImplicitNonTerminalTask)
{
Try<PID<Master> > master = StartMaster();
ASSERT_SOME(master);
MockExecutor exec(DEFAULT_EXECUTOR_ID);
TestContainerizer containerizer(&exec);
Try<PID<Slave> > slave = StartSlave(&containerizer);
ASSERT_SOME(slave);
// Launch a framework and get a task running.
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, DEFAULT_FRAMEWORK_INFO, master.get(), DEFAULT_CREDENTIAL);
Future<FrameworkID> frameworkId;
EXPECT_CALL(sched, registered(&driver, _, _))
.WillOnce(FutureArg<1>(&frameworkId));
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(LaunchTasks(DEFAULT_EXECUTOR_INFO, 1, 1, 512, "*"))
.WillRepeatedly(Return()); // Ignore subsequent offers.
EXPECT_CALL(exec, registered(_, _, _, _));
EXPECT_CALL(exec, launchTask(_, _))
.WillOnce(SendStatusUpdateFromTask(TASK_RUNNING));
Future<TaskStatus> update;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&update));
driver.start();
// Wait until the framework is registered.
AWAIT_READY(frameworkId);
AWAIT_READY(update);
EXPECT_EQ(TASK_RUNNING, update.get().state());
EXPECT_TRUE(update.get().has_slave_id());
// When making an implicit reconciliation request, the non-terminal
// task should be sent back.
Future<TaskStatus> update2;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&update2));
vector<TaskStatus> statuses;
driver.reconcileTasks(statuses);
AWAIT_READY(update2);
EXPECT_EQ(TASK_RUNNING, update2.get().state());
EXPECT_CALL(exec, shutdown(_))
.Times(AtMost(1));
driver.stop();
driver.join();
Shutdown(); // Must shutdown before 'containerizer' gets deallocated.
}
示例4: TEST_F
// Ensures that the driver can handle the SUBSCRIBED event
// after a scheduler failover.
TEST_F(SchedulerDriverEventTest, SubscribedSchedulerFailover)
{
Try<PID<Master>> master = StartMaster();
ASSERT_SOME(master);
FrameworkInfo frameworkInfo = DEFAULT_FRAMEWORK_INFO;
frameworkInfo.set_failover_timeout(Weeks(2).secs());
// Make sure the initial registration calls 'registered'.
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, frameworkInfo, master.get(), DEFAULT_CREDENTIAL);
// Intercept the registration message, send a SUBSCRIBED instead.
Future<Message> frameworkRegisteredMessage =
DROP_MESSAGE(Eq(FrameworkRegisteredMessage().GetTypeName()), _, _);
// Ensure that there will be no (re-)registration retries
// from the scheduler driver.
Clock::pause();
driver.start();
AWAIT_READY(frameworkRegisteredMessage);
UPID frameworkPid = frameworkRegisteredMessage.get().to;
FrameworkRegisteredMessage message;
ASSERT_TRUE(message.ParseFromString(frameworkRegisteredMessage.get().body));
FrameworkID frameworkId = message.framework_id();
frameworkInfo.mutable_id()->CopyFrom(frameworkId);
Event event;
event.set_type(Event::SUBSCRIBED);
event.mutable_subscribed()->mutable_framework_id()->CopyFrom(frameworkId);
Future<Nothing> registered;
EXPECT_CALL(sched, registered(&driver, frameworkId, _))
.WillOnce(FutureSatisfy(®istered));
process::post(master.get(), frameworkPid, event);
AWAIT_READY(registered);
// Fail over the scheduler and expect a 'registered' call.
driver.stop(true);
MockScheduler sched2;
MesosSchedulerDriver driver2(
&sched2, frameworkInfo, master.get(), DEFAULT_CREDENTIAL);
frameworkRegisteredMessage =
DROP_MESSAGE(Eq(FrameworkRegisteredMessage().GetTypeName()), _, _);
driver2.start();
AWAIT_READY(frameworkRegisteredMessage);
UPID frameworkPid2 = frameworkRegisteredMessage.get().to;
Future<Nothing> registered2;
EXPECT_CALL(sched2, registered(&driver2, frameworkId, _))
.WillOnce(FutureSatisfy(®istered2));
process::post(master.get(), frameworkPid2, event);
AWAIT_READY(registered2);
}
示例5: TEST_F
TEST_F(MemoryPressureMesosTest, CGROUPS_ROOT_Statistics)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
slave::Flags flags = CreateSlaveFlags();
// We only care about memory cgroup for this test.
flags.isolation = "cgroups/mem";
flags.agent_subsystems = None();
Fetcher fetcher;
Try<MesosContainerizer*> _containerizer =
MesosContainerizer::create(flags, true, &fetcher);
ASSERT_SOME(_containerizer);
Owned<MesosContainerizer> containerizer(_containerizer.get());
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave =
StartSlave(detector.get(), containerizer.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(_, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(_, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
EXPECT_NE(0u, offers.get().size());
Offer offer = offers.get()[0];
// Run a task that triggers memory pressure event. We request 1G
// disk because we are going to write a 512 MB file repeatedly.
TaskInfo task = createTask(
offer.slave_id(),
Resources::parse("cpus:1;mem:256;disk:1024").get(),
"while true; do dd count=512 bs=1M if=/dev/zero of=./temp; done");
Future<TaskStatus> running;
Future<TaskStatus> killed;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&running))
.WillOnce(FutureArg<1>(&killed))
.WillRepeatedly(Return()); // Ignore subsequent updates.
driver.launchTasks(offer.id(), {task});
AWAIT_READY(running);
EXPECT_EQ(task.task_id(), running.get().task_id());
EXPECT_EQ(TASK_RUNNING, running.get().state());
Future<hashset<ContainerID>> containers = containerizer->containers();
AWAIT_READY(containers);
ASSERT_EQ(1u, containers.get().size());
ContainerID containerId = *(containers.get().begin());
// Wait a while for some memory pressure events to occur.
Duration waited = Duration::zero();
do {
Future<ResourceStatistics> usage = containerizer->usage(containerId);
AWAIT_READY(usage);
if (usage.get().mem_low_pressure_counter() > 0) {
// We will check the correctness of the memory pressure counters
// later, because the memory-hammering task is still active
// and potentially incrementing these counters.
break;
}
os::sleep(Milliseconds(100));
waited += Milliseconds(100);
} while (waited < Seconds(5));
EXPECT_LE(waited, Seconds(5));
// Pause the clock to ensure that the reaper doesn't reap the exited
// command executor and inform the containerizer/slave.
Clock::pause();
Clock::settle();
// Stop the memory-hammering task.
driver.killTask(task.task_id());
AWAIT_READY_FOR(killed, Seconds(120));
EXPECT_EQ(task.task_id(), killed->task_id());
EXPECT_EQ(TASK_KILLED, killed->state());
//.........这里部分代码省略.........
示例6: TYPED_TEST
TYPED_TEST(CpuIsolatorTest, SystemCpuUsage)
{
slave::Flags flags;
Try<Isolator*> isolator = TypeParam::create(flags);
CHECK_SOME(isolator);
// A PosixLauncher is sufficient even when testing a cgroups isolator.
Try<Launcher*> launcher = PosixLauncher::create(flags);
ExecutorInfo executorInfo;
executorInfo.mutable_resources()->CopyFrom(
Resources::parse("cpus:1.0").get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
// Use a relative temporary directory so it gets cleaned up
// automatically with the test.
Try<string> dir = os::mkdtemp(path::join(os::getcwd(), "XXXXXX"));
ASSERT_SOME(dir);
ContainerConfig containerConfig;
containerConfig.mutable_executor_info()->CopyFrom(executorInfo);
containerConfig.set_directory(dir.get());
AWAIT_READY(isolator.get()->prepare(
containerId,
containerConfig));
const string& file = path::join(dir.get(), "mesos_isolator_test_ready");
// Generating random numbers is done by the kernel and will max out a single
// core and run almost exclusively in the kernel, i.e., system time.
string command = "cat /dev/urandom > /dev/null & "
"touch " + file + "; " // Signals the command is running.
"sleep 60";
int pipes[2];
ASSERT_NE(-1, ::pipe(pipes));
vector<string> argv(3);
argv[0] = "sh";
argv[1] = "-c";
argv[2] = command;
Try<pid_t> pid = launcher.get()->fork(
containerId,
"sh",
argv,
Subprocess::FD(STDIN_FILENO),
Subprocess::FD(STDOUT_FILENO),
Subprocess::FD(STDERR_FILENO),
None(),
None(),
lambda::bind(&childSetup, pipes),
None());
ASSERT_SOME(pid);
// Reap the forked child.
Future<Option<int> > status = process::reap(pid.get());
// Continue in the parent.
ASSERT_SOME(os::close(pipes[0]));
// Isolate the forked child.
AWAIT_READY(isolator.get()->isolate(containerId, pid.get()));
// Now signal the child to continue.
char dummy;
ASSERT_LT(0, ::write(pipes[1], &dummy, sizeof(dummy)));
ASSERT_SOME(os::close(pipes[1]));
// Wait for the command to start.
while (!os::exists(file));
// Wait up to 1 second for the child process to induce 1/8 of a second of
// system cpu time.
ResourceStatistics statistics;
Duration waited = Duration::zero();
do {
Future<ResourceStatistics> usage = isolator.get()->usage(containerId);
AWAIT_READY(usage);
statistics = usage.get();
// If we meet our usage expectations, we're done!
if (statistics.cpus_system_time_secs() >= 0.125) {
break;
}
os::sleep(Milliseconds(200));
waited += Milliseconds(200);
} while (waited < Seconds(1));
EXPECT_LE(0.125, statistics.cpus_system_time_secs());
// Ensure all processes are killed.
//.........这里部分代码省略.........
示例7: TEST_F
// This test ensures that the command executor sends TASK_KILLING
// to frameworks that support the capability.
TEST_F(CommandExecutorTest, TaskKillingCapability)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get());
ASSERT_SOME(slave);
// Start the framework with the task killing capability.
FrameworkInfo::Capability capability;
capability.set_type(FrameworkInfo::Capability::TASK_KILLING_STATE);
FrameworkInfo frameworkInfo = DEFAULT_FRAMEWORK_INFO;
frameworkInfo.add_capabilities()->CopyFrom(capability);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
EXPECT_EQ(1u, offers->size());
// Launch a task with the command executor.
TaskInfo task = createTask(
offers->front().slave_id(),
offers->front().resources(),
"sleep 1000");
Future<TaskStatus> statusRunning;
EXPECT_CALL(sched, statusUpdate(_, _))
.WillOnce(FutureArg<1>(&statusRunning));
driver.launchTasks(offers->front().id(), {task});
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
Future<TaskStatus> statusKilling, statusKilled;
EXPECT_CALL(sched, statusUpdate(_, _))
.WillOnce(FutureArg<1>(&statusKilling))
.WillOnce(FutureArg<1>(&statusKilled));
driver.killTask(task.task_id());
AWAIT_READY(statusKilling);
EXPECT_EQ(TASK_KILLING, statusKilling->state());
AWAIT_READY(statusKilled);
EXPECT_EQ(TASK_KILLED, statusKilled->state());
driver.stop();
driver.join();
}
示例8: TEST
TEST(HTTP, Endpoints)
{
ASSERT_TRUE(GTEST_IS_THREADSAFE);
HttpProcess process;
spawn(process);
// First hit '/body' (using explicit sockets and HTTP/1.0).
Try<Socket> create = Socket::create();
ASSERT_SOME(create);
Socket socket = create.get();
AWAIT_READY(socket.connect(process.self().address));
std::ostringstream out;
out << "GET /" << process.self().id << "/body"
<< " HTTP/1.0\r\n"
<< "Connection: Keep-Alive\r\n"
<< "\r\n";
const string& data = out.str();
EXPECT_CALL(process, body(_))
.WillOnce(Return(http::OK()));
AWAIT_READY(socket.send(data));
string response = "HTTP/1.1 200 OK";
AWAIT_EXPECT_EQ(response, socket.recv(response.size()));
// Now hit '/pipe' (by using http::get).
int pipes[2];
ASSERT_NE(-1, ::pipe(pipes));
http::OK ok;
ok.type = http::Response::PIPE;
ok.pipe = pipes[0];
Future<Nothing> pipe;
EXPECT_CALL(process, pipe(_))
.WillOnce(DoAll(FutureSatisfy(&pipe),
Return(ok)));
Future<http::Response> future = http::get(process.self(), "pipe");
AWAIT_READY(pipe);
ASSERT_SOME(os::write(pipes[1], "Hello World\n"));
ASSERT_SOME(os::close(pipes[1]));
AWAIT_READY(future);
EXPECT_EQ(http::statuses[200], future.get().status);
EXPECT_SOME_EQ("chunked", future.get().headers.get("Transfer-Encoding"));
EXPECT_EQ("Hello World\n", future.get().body);
terminate(process);
wait(process);
}
示例9: TEST_F
TEST_F(ZooKeeperTest, LeaderContender)
{
Seconds timeout(10);
Group group(server->connectString(), timeout, "/test/");
Owned<LeaderContender> contender(
new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));
// Calling withdraw before contending returns 'false' because there
// is nothing to withdraw.
Future<bool> withdrawn = contender->withdraw();
AWAIT_READY(withdrawn);
EXPECT_FALSE(withdrawn.get());
contender->contend();
// Immediately withdrawing after contending leads to delayed
// cancellation.
withdrawn = contender->withdraw();
AWAIT_READY(withdrawn);
EXPECT_TRUE(withdrawn.get());
// Normal workflow.
contender = Owned<LeaderContender>(
new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));
Future<Future<Nothing> > candidated = contender->contend();
AWAIT_READY(candidated);
Future<Nothing> lostCandidacy = candidated.get();
EXPECT_TRUE(lostCandidacy.isPending());
// Expire the Group session while we are watching for updates from
// the contender and the candidacy will be lost.
Future<Option<int64_t> > session = group.session();
AWAIT_READY(session);
ASSERT_SOME(session.get());
Future<Nothing> connected = FUTURE_DISPATCH(
group.process->self(),
&GroupProcess::connected);
server->expireSession(session.get().get());
AWAIT_READY(lostCandidacy);
// Withdraw directly returns because candidacy is lost and there
// is nothing to cancel.
withdrawn = contender->withdraw();
AWAIT_READY(withdrawn);
EXPECT_FALSE(withdrawn.get());
// Contend again.
contender = Owned<LeaderContender>(
new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));
candidated = contender->contend();
AWAIT_READY(connected);
session = group.session();
AWAIT_READY(session);
ASSERT_SOME(session.get());
server->expireSession(session.get().get());
Clock::pause();
// The retry timeout.
Clock::advance(GroupProcess::RETRY_INTERVAL);
Clock::settle();
Clock::resume();
// The contender weathered the expiration and succeeded in a retry.
AWAIT_READY(candidated);
withdrawn = contender->withdraw();
AWAIT_READY(withdrawn);
// Contend (3) and shutdown the network this time.
contender = Owned<LeaderContender>(
new LeaderContender(&group, "candidate 1", master::MASTER_INFO_LABEL));
candidated = contender->contend();
AWAIT_READY(candidated);
lostCandidacy = candidated.get();
Future<Nothing> reconnecting = FUTURE_DISPATCH(
group.process->self(),
&GroupProcess::reconnecting);
server->shutdownNetwork();
AWAIT_READY(reconnecting);
Clock::pause();
// Settle to make sure 'reconnecting()' schedules the timeout
// before we advance.
Clock::settle();
Clock::advance(timeout);
// Server failure results in candidacy loss.
AWAIT_READY(lostCandidacy);
Clock::resume();
//.........这里部分代码省略.........
示例10: TEST_F
// This test verifies that a framework attempting to subscribe
// after its failover timeout has elapsed is disallowed.
TEST_F(HttpFaultToleranceTest, SchedulerSubscribeAfterFailoverTimeout)
{
master::Flags flags = CreateMasterFlags();
flags.authenticate_frameworks = false;
v1::FrameworkInfo frameworkInfo = v1::DEFAULT_FRAMEWORK_INFO;
frameworkInfo.set_failover_timeout(Weeks(2).secs());
Try<Owned<cluster::Master>> master = StartMaster(flags);
ASSERT_SOME(master);
Future<Nothing> deactivateFramework = FUTURE_DISPATCH(
_, &master::allocator::MesosAllocatorProcess::deactivateFramework);
v1::FrameworkID frameworkId;
ContentType contentType = ContentType::PROTOBUF;
// Launch the first (i.e., failing) scheduler and wait until it receives
// a `SUBSCRIBED` event to launch the second (i.e., failover) scheduler.
{
auto scheduler = std::make_shared<v1::MockHTTPScheduler>();
Future<Nothing> connected;
EXPECT_CALL(*scheduler, connected(_))
.WillOnce(FutureSatisfy(&connected));
v1::scheduler::TestMesos schedulerLibrary(
master.get()->pid,
contentType,
scheduler);
AWAIT_READY(connected);
Future<Event::Subscribed> subscribed;
EXPECT_CALL(*scheduler, subscribed(_, _))
.WillOnce(FutureArg<1>(&subscribed));
EXPECT_CALL(*scheduler, heartbeat(_))
.WillRepeatedly(Return()); // Ignore heartbeats.
{
Call call;
call.set_type(Call::SUBSCRIBE);
Call::Subscribe* subscribe = call.mutable_subscribe();
subscribe->mutable_framework_info()->CopyFrom(frameworkInfo);
schedulerLibrary.send(call);
}
AWAIT_READY(subscribed);
frameworkId = subscribed->framework_id();
}
// Wait until master schedules the framework for removal.
AWAIT_READY(deactivateFramework);
// Simulate framework failover timeout.
Clock::pause();
Clock::settle();
Try<Duration> failoverTimeout =
Duration::create(frameworkInfo.failover_timeout());
ASSERT_SOME(failoverTimeout);
Future<Nothing> frameworkFailoverTimeout =
FUTURE_DISPATCH(_, &Master::frameworkFailoverTimeout);
Clock::advance(failoverTimeout.get());
Clock::resume();
// Wait until master actually marks the framework as completed.
AWAIT_READY(frameworkFailoverTimeout);
// Now launch the second (i.e., failover) scheduler using the
// framework id recorded from the first scheduler.
{
auto scheduler = std::make_shared<v1::MockHTTPScheduler>();
Future<Nothing> connected;
EXPECT_CALL(*scheduler, connected(_))
.WillOnce(FutureSatisfy(&connected))
.WillRepeatedly(Return()); // Ignore future invocations.
v1::scheduler::TestMesos schedulerLibrary(
master.get()->pid,
contentType,
scheduler);
AWAIT_READY(connected);
// Framework should get `Error` event because the framework with this id
// is marked as completed.
Future<Nothing> error;
EXPECT_CALL(*scheduler, error(_, _))
.WillOnce(FutureSatisfy(&error));
//.........这里部分代码省略.........
示例11: TEST_F
TEST_F(LimitedCpuIsolatorTest, ROOT_CGROUPS_CFS_Enable_Cfs)
{
slave::Flags flags;
// Enable CFS to cap CPU utilization.
flags.cgroups_enable_cfs = true;
Try<Isolator*> isolator = CgroupsCpushareIsolatorProcess::create(flags);
CHECK_SOME(isolator);
Try<Launcher*> launcher = LinuxLauncher::create(flags);
CHECK_SOME(launcher);
// Set the executor's resources to 0.5 cpu.
ExecutorInfo executorInfo;
executorInfo.mutable_resources()->CopyFrom(
Resources::parse("cpus:0.5").get());
ContainerID containerId;
containerId.set_value(UUID::random().toString());
// Use a relative temporary directory so it gets cleaned up
// automatically with the test.
Try<string> dir = os::mkdtemp(path::join(os::getcwd(), "XXXXXX"));
ASSERT_SOME(dir);
ContainerConfig containerConfig;
containerConfig.mutable_executor_info()->CopyFrom(executorInfo);
containerConfig.set_directory(dir.get());
Future<Option<ContainerLaunchInfo>> prepare =
isolator.get()->prepare(
containerId,
containerConfig);
AWAIT_READY(prepare);
// Generate random numbers to max out a single core. We'll run this for 0.5
// seconds of wall time so it should consume approximately 250 ms of total
// cpu time when limited to 0.5 cpu. We use /dev/urandom to prevent blocking
// on Linux when there's insufficient entropy.
string command = "cat /dev/urandom > /dev/null & "
"export MESOS_TEST_PID=$! && "
"sleep 0.5 && "
"kill $MESOS_TEST_PID";
int pipes[2];
ASSERT_NE(-1, ::pipe(pipes));
vector<string> argv(3);
argv[0] = "sh";
argv[1] = "-c";
argv[2] = command;
Try<pid_t> pid = launcher.get()->fork(
containerId,
"sh",
argv,
Subprocess::FD(STDIN_FILENO),
Subprocess::FD(STDOUT_FILENO),
Subprocess::FD(STDERR_FILENO),
None(),
None(),
lambda::bind(&childSetup, pipes),
prepare.get().isSome() ? prepare.get().get().namespaces() : 0);
ASSERT_SOME(pid);
// Reap the forked child.
Future<Option<int> > status = process::reap(pid.get());
// Continue in the parent.
ASSERT_SOME(os::close(pipes[0]));
// Isolate the forked child.
AWAIT_READY(isolator.get()->isolate(containerId, pid.get()));
// Now signal the child to continue.
char dummy;
ASSERT_LT(0, ::write(pipes[1], &dummy, sizeof(dummy)));
ASSERT_SOME(os::close(pipes[1]));
// Wait for the command to complete.
AWAIT_READY(status);
Future<ResourceStatistics> usage = isolator.get()->usage(containerId);
AWAIT_READY(usage);
// Expect that no more than 300 ms of cpu time has been consumed. We also
// check that at least 50 ms of cpu time has been consumed so this test will
// fail if the host system is very heavily loaded. This behavior is correct
// because under such conditions we aren't actually testing the CFS cpu
// limiter.
double cpuTime = usage.get().cpus_system_time_secs() +
usage.get().cpus_user_time_secs();
EXPECT_GE(0.30, cpuTime);
EXPECT_LE(0.05, cpuTime);
//.........这里部分代码省略.........
示例12: TEST
TEST(Wait, waitWithDuration) {
{
Promise<int> p;
Future<int> f = p.getFuture();
f.wait(milliseconds(1));
EXPECT_FALSE(f.isReady());
p.setValue(1);
EXPECT_TRUE(f.isReady());
}
{
Promise<int> p;
Future<int> f = p.getFuture();
p.setValue(1);
f.wait(milliseconds(1));
EXPECT_TRUE(f.isReady());
}
{
vector<Future<bool>> v_fb;
v_fb.push_back(makeFuture(true));
v_fb.push_back(makeFuture(false));
auto f = collectAll(v_fb);
f.wait(milliseconds(1));
EXPECT_TRUE(f.isReady());
EXPECT_EQ(2, f.value().size());
}
{
vector<Future<bool>> v_fb;
Promise<bool> p1;
Promise<bool> p2;
v_fb.push_back(p1.getFuture());
v_fb.push_back(p2.getFuture());
auto f = collectAll(v_fb);
f.wait(milliseconds(1));
EXPECT_FALSE(f.isReady());
p1.setValue(true);
EXPECT_FALSE(f.isReady());
p2.setValue(true);
EXPECT_TRUE(f.isReady());
}
{
auto f = makeFuture().wait(milliseconds(1));
EXPECT_TRUE(f.isReady());
}
{
Promise<Unit> p;
auto start = std::chrono::steady_clock::now();
auto f = p.getFuture().wait(milliseconds(100));
auto elapsed = std::chrono::steady_clock::now() - start;
EXPECT_GE(elapsed, milliseconds(100));
EXPECT_FALSE(f.isReady());
p.setValue();
EXPECT_TRUE(f.isReady());
}
{
// Try to trigger the race where the resultant Future is not yet complete
// even if we didn't hit the timeout, and make sure we deal with it properly
Promise<Unit> p;
folly::Baton<> b;
auto t = std::thread([&]{
b.post();
/* sleep override */ std::this_thread::sleep_for(milliseconds(100));
p.setValue();
});
b.wait();
auto f = p.getFuture().wait(std::chrono::seconds(3600));
EXPECT_TRUE(f.isReady());
t.join();
}
}
示例13: stringify
protocol,
stringify(protocol == server_protocol));
}
// Set up the server.
Try<Socket> server = setup_server(server_environment);
ASSERT_SOME(server);
// Launch the client with a POLL socket.
Try<Subprocess> client = launch_client({
{"LIBPROCESS_SSL_ENABLED", "false"}},
server.get(),
false);
ASSERT_SOME(client);
Future<Socket> socket = server->accept();
AWAIT_ASSERT_READY(socket);
// TODO(jmlvanre): Remove const copy.
AWAIT_ASSERT_EQ(data, Socket(socket.get()).recv());
AWAIT_ASSERT_READY(Socket(socket.get()).send(data));
AWAIT_ASSERT_READY(await_subprocess(client.get(), 0));
}
}
// For each protocol: ensure we CANNOT communicate between a POLL
// based socket and an SSL socket if 'SSL_SUPPORT_DOWNGRADE' is not
// enabled.
TEST_F(SSLTest, NoValidDowngradeEachProtocol)