int main(int argc, char** argv)
{
  if (argc != 2) {
    cerr << "Usage: " << argv[0] << " <master>" << endl;
    return -1;
  }

  DockerNoExecutorScheduler scheduler;

  FrameworkInfo framework;
  framework.set_user(""); // Have Mesos fill in the current user.
  framework.set_name("Docker No Executor Framework (C++)");
  framework.set_checkpoint(true);

  MesosSchedulerDriver* driver;
  if (os::getenv("MESOS_AUTHENTICATE_FRAMEWORKS").isSome()) {
    cout << "Enabling authentication for the framework" << endl;

    Option<string> value = os::getenv("DEFAULT_PRINCIPAL");
    if (value.isNone()) {
      EXIT(EXIT_FAILURE)
        << "Expecting authentication principal in the environment";
    }

    Credential credential;
    credential.set_principal(value.get());

    framework.set_principal(value.get());

    value = os::getenv("DEFAULT_SECRET");
    if (value.isNone()) {
      EXIT(EXIT_FAILURE)
        << "Expecting authentication secret in the environment";
    }

    credential.set_secret(value.get());

    driver = new MesosSchedulerDriver(
        &scheduler, framework, argv[1], credential);
  } else {
    framework.set_principal("no-executor-framework-cpp");

    driver = new MesosSchedulerDriver(
        &scheduler, framework, argv[1]);
  }

  int status = driver->run() == DRIVER_STOPPED ? 0 : 1;

  // Ensure that the driver process terminates.
  driver->stop();

  delete driver;
  return status;
}
Exemplo n.º 2
0
Try<Option<Entry> > LevelDBStorageProcess::read(const string& name)
{
  CHECK(error.isNone());

  leveldb::ReadOptions options;

  string value;

  leveldb::Status status = db->Get(options, name, &value);

  if (status.IsNotFound()) {
    return None();
  } else if (!status.ok()) {
    return Error(status.ToString());
  }

  google::protobuf::io::ArrayInputStream stream(value.data(), value.size());

  Entry entry;

  if (!entry.ParseFromZeroCopyStream(&stream)) {
    return Error("Failed to deserialize Entry");
  }

  return Some(entry);
}
Exemplo n.º 3
0
Try<PID<slave::Slave> > MesosTest::StartSlave(
    MasterDetector* detector,
    const Option<slave::Flags>& flags)
{
  return cluster.slaves.start(
      detector, flags.isNone() ? CreateSlaveFlags() : flags.get());
}
Exemplo n.º 4
0
Option<std::string> _check(const Option<T>& o)
{
  if (o.isNone()) {
    return Some("is NONE");
  }
  return None();
}
Exemplo n.º 5
0
Try<bool> create(
    const string& veth,
    const string& peer,
    const Option<pid_t>& pid)
{
  Try<Netlink<struct nl_sock> > sock = routing::socket();
  if (sock.isError()) {
    return Error(sock.error());
  }

  int err = rtnl_link_veth_add(
      sock.get().get(),
      veth.c_str(),
      peer.c_str(),
      (pid.isNone() ? getpid() : pid.get()));

  if (err != 0) {
    if (err == -NLE_EXIST) {
      return false;
    }
    return Error(nl_geterror(err));
  }

  return true;
}
Exemplo n.º 6
0
Future<bool> LeaderContenderProcess::withdraw()
{
  if (contending.isNone()) {
    // Nothing to withdraw because the contender has not contended.
    return false;
  }

  if (withdrawing.isSome()) {
    // Repeated calls to withdraw get the same result.
    return withdrawing.get();
  }

  withdrawing = new Promise<bool>();

  CHECK(!candidacy.isDiscarded());

  if (candidacy.isPending()) {
    // If we have not obtained the candidacy yet, we withdraw after
    // it is obtained.
    LOG(INFO) << "Withdraw requested before the candidacy is obtained; will "
              << "withdraw after it happens";
    candidacy.onAny(defer(self(), &Self::cancel));
  } else if (candidacy.isReady()) {
    cancel();
  } else {
    // We have failed to obtain the candidacy so we do not need to
    // cancel it.
    return false;
  }

  return withdrawing.get()->future();
}
Exemplo n.º 7
0
Try<ContainerLogger*> ContainerLogger::create(const Option<string>& type)
{
  ContainerLogger* logger = nullptr;

  if (type.isNone()) {
    logger = new internal::slave::SandboxContainerLogger();
  } else {
    // Try to load container logger from module.
    Try<ContainerLogger*> module =
      modules::ModuleManager::create<ContainerLogger>(type.get());

    if (module.isError()) {
      return Error(
          "Failed to create container logger module '" + type.get() +
          "': " + module.error());
    }

    logger = module.get();
  }

  // Initialize the module.
  Try<Nothing> initialize = logger->initialize();
  if (initialize.isError()) {
    delete logger;

    return Error(
        "Failed to initialize container logger module: " + initialize.error());
  }

  return logger;
}
Exemplo n.º 8
0
inline ::testing::AssertionResult AwaitAssertResponseHeaderEq(
    const char* expectedExpr,
    const char* keyExpr,
    const char* actualExpr,
    const char* durationExpr,
    const std::string& expected,
    const std::string& key,
    const process::Future<process::http::Response>& actual,
    const Duration& duration)
{
  const ::testing::AssertionResult result =
    AwaitAssertReady(actualExpr, durationExpr, actual, duration);

  if (result) {
    const Option<std::string> value = actual.get().headers.get(key);
    if (value.isNone()) {
      return ::testing::AssertionFailure()
        << "Response does not contain header '" << key << "'";
    } else if (expected == value.get()) {
      return ::testing::AssertionSuccess();
    } else {
      return ::testing::AssertionFailure()
        << "Value of: (" << actualExpr << ").get().headers[" << keyExpr << "]\n"
        << "  Actual: " << ::testing::PrintToString(value.get()) << "\n"
        << "Expected: " << expectedExpr << "\n"
        << "Which is: " << ::testing::PrintToString(expected);
    }
  }

  return result;
}
Exemplo n.º 9
0
double DRFSorter::calculateShare(const string& name)
{
  double share = 0;

  // TODO(benh): This implementation of "dominant resource fairness"
  // currently does not take into account resources that are not
  // scalars.

  // Scalar resources may be spread across multiple 'Resource'
  // objects. E.g. persistent volumes. So we first collect the names
  // of the scalar resources, before computing the totals.
  hashset<string> scalars;
  foreach (const Resource& resource, resources) {
    if (resource.type() == Value::SCALAR) {
      scalars.insert(resource.name());
    }
  }

  foreach (const string& scalar, scalars) {
    Option<Value::Scalar> total = resources.get<Value::Scalar>(scalar);

    if (total.isSome() && total.get().value() > 0) {
      Option<Value::Scalar> allocation =
        allocations[name].get<Value::Scalar>(scalar);

      if (allocation.isNone()) {
        allocation = Value::Scalar();
      }

      share = std::max(share, allocation.get().value() / total.get().value());
    }
  }
Exemplo n.º 10
0
inline Option<std::string> which(const std::string& command)
{
    Option<std::string> path = getenv("PATH");
    if (path.isNone()) {
        return None();
    }

    std::vector<std::string> tokens = strings::tokenize(path.get(), ":");
    foreach (const std::string& token, tokens) {
        const std::string commandPath = path::join(token, command);
        if (!os::exists(commandPath)) {
            continue;
        }

        Try<os::Permissions> permissions = os::permissions(commandPath);
        if (permissions.isError()) {
            continue;
        }

        if (!permissions.get().owner.x &&
                !permissions.get().group.x &&
                !permissions.get().others.x) {
            continue;
        }

        return commandPath;
    }

    return None();
}
Exemplo n.º 11
0
Future<http::Response> Help::help(const http::Request& request)
{
  // Split the path by '/'.
  vector<string> tokens = strings::tokenize(request.path, "/");

  Option<string> id = None();
  Option<string> name = None();

  if (tokens.size() > 3) {
    return http::BadRequest("Malformed URL, expecting '/help/id/name/'\n");
  } else if (tokens.size() == 3) {
    id = tokens[1];
    name = tokens[2];
  } else if (tokens.size() > 1) {
    id = tokens[1];
  }

  string document;
  string references;

  if (id.isNone()) {             // http://ip:port/help
    document += "## HELP\n";
    foreachkey (const string& id, helps) {
      document += "> [/" + id + "][" + id + "]\n";
      references += "[" + id + "]: help/" + id + "\n";
    }
Exemplo n.º 12
0
Try<process::PID<slave::Slave> > MesosTest::StartSlave(
    slave::Containerizer* containerizer,
    const Option<slave::Flags>& flags)
{
  return cluster.slaves.start(
      containerizer, flags.isNone() ? CreateSlaveFlags() : flags.get());
}
Exemplo n.º 13
0
// Wait for a subprocess and test the status code for the following
// conditions of 'expected_status':
//   1. 'None' = Anything but '0'.
//   2. 'Some' = the value of 'expected_status'.
// Returns Nothing if the resulting status code matches the
// expectation otherwise a Failure with the output of the subprocess.
// TODO(jmlvanre): Turn this into a generally useful abstraction for
// gtest where we can have a more straigtforward 'expected_status'.
Future<Nothing> await_subprocess(
    const Subprocess& subprocess,
    const Option<int>& expected_status = None())
{
  // Dup the pipe fd of the subprocess so we can read the output if
  // needed.
  int out = dup(subprocess.out().get());

  // Once we get the status of the process.
  return subprocess.status()
    .then([=](const Option<int>& status) -> Future<Nothing> {
      // If the status is not set, fail out.
      if (status.isNone()) {
        return Failure("Subprocess status is none");
      }

      // If the status is not what we expect then fail out with the
      // output of the subprocess. The failure message will include
      // the assertion failures of the subprocess.
      if ((expected_status.isSome() && status.get() != expected_status.get()) ||
          (expected_status.isNone() && status.get() == 0)) {
        return io::read(out)
          .then([](const string& output) -> Future<Nothing> {
            return Failure("\n[++++++++++] Subprocess output.\n" + output +
                           "[++++++++++]\n");
          });
      }

      // If the subprocess ran successfully then return nothing.
      return Nothing();
    }).onAny([=]() {
      os::close(out);
    });
}
Exemplo n.º 14
0
// Creates a null-terminated array of null-terminated strings that will be
// passed to `CreateProcess` as the `lpEnvironment` argument, as described by
// MSDN[1]. This array needs to be sorted in alphabetical order, but the `map`
// already takes care of that. Note that this function does not handle Unicode
// environments, so it should not be used in conjunction with the
// `CREATE_UNICODE_ENVIRONMENT` flag.
//
// NOTE: This function will add the system's environment variables into
// the returned string. These variables take precedence over the provided
// `env` and are generally necessary in order to launch things on Windows.
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx
inline Option<std::string> createProcessEnvironment(
    const Option<std::map<std::string, std::string>>& env)
{
  if (env.isNone() || (env.isSome() && env.get().size() == 0)) {
    return None();
  }

  Option<std::map<std::string, std::string>> systemEnvironment =
    getSystemEnvironment();

  // The system environment must be non-empty.
  // No subprocesses will be able to launch if the system environment is blank.
  CHECK(systemEnvironment.isSome() && systemEnvironment.get().size() > 0);

  std::map<std::string, std::string> combinedEnvironment = env.get();

  foreachpair (const std::string& key,
               const std::string& value,
               systemEnvironment.get()) {
    combinedEnvironment[key] = value;
  }

  std::string environmentString;
  foreachpair (const std::string& key,
               const std::string& value,
               combinedEnvironment) {
    environmentString += key + '=' + value + '\0';
  }
Exemplo n.º 15
0
// Splits the string using the provided delimiters.
// The string is split each time at the first character
// that matches any of the characters specified in delims.
// Empty tokens are allowed in the result.
// Optionally, maximum number of tokens to be returned
// can be specified.
inline std::vector<std::string> split(
    const std::string& s,
    const std::string& delims,
    const Option<size_t>& maxTokens = None())
{
  size_t offset = 0;
  std::vector<std::string> tokens;

  while (maxTokens.isNone() || maxTokens.get() > 0) {
    size_t next = s.find_first_of(delims, offset);

    // Finish splitting if this is the last token,
    // or we've found enough tokens.
    if (next == std::string::npos ||
        (maxTokens.isSome() && tokens.size() == maxTokens.get() - 1)) {
      tokens.push_back(s.substr(offset));
      break;
    }

    tokens.push_back(s.substr(offset, next - offset));
    offset = next + 1;
  }

  return tokens;
}
Exemplo n.º 16
0
double DRFSorter::calculateShare(const string& name)
{
  double share = 0;

  // TODO(benh): This implementaion of "dominant resource fairness"
  // currently does not take into account resources that are not
  // scalars.

  foreach (const Resource& resource, resources) {
    if (resource.type() == Value::SCALAR) {
      double total = resource.scalar().value();

      if (total > 0) {
        Option<Value::Scalar> scalar =
          allocations[name].get<Value::Scalar>(resource.name());

        if (scalar.isNone()) {
          scalar = Value::Scalar();
        }

        share = std::max(share, scalar.get().value() / total);
      }
    }
  }

  return share / weights[name];
}
Exemplo n.º 17
0
// Tokenizes the string using the delimiters.
// Empty tokens will not be included in the result.
// Optionally, maximum number of tokens to be returned
// can be specified.
inline std::vector<std::string> tokenize(
    const std::string& s,
    const std::string& delims,
    const Option<size_t>& maxTokens = None())
{
  size_t offset = 0;
  std::vector<std::string> tokens;

  while (maxTokens.isNone() || maxTokens.get() > 0) {
    size_t nonDelim = s.find_first_not_of(delims, offset);

    if (nonDelim == std::string::npos) {
      break; // Nothing left
    }

    size_t delim = s.find_first_of(delims, nonDelim);

    // Finish tokenizing if this is the last token,
    // or we've found enough tokens.
    if (delim == std::string::npos ||
        (maxTokens.isSome() && tokens.size() == maxTokens.get() - 1)) {
      tokens.push_back(s.substr(nonDelim));
      break;
    }

    tokens.push_back(s.substr(nonDelim, delim - nonDelim));
    offset = delim;
  }

  return tokens;
}
Exemplo n.º 18
0
Future<Future<Nothing> > ZooKeeperMasterContenderProcess::contend()
{
  if (masterInfo.isNone()) {
    return Failure("Initialize the contender first");
  }

  // Should not recontend if the last election is still ongoing.
  if (candidacy.isSome() && candidacy.get().isPending()) {
    return candidacy.get();
  }

  if (contender != NULL) {
    LOG(INFO) << "Withdrawing the previous membership before recontending";
    delete contender;
  }

  // Serialize the MasterInfo to JSON.
  JSON::Object json = JSON::protobuf(masterInfo.get());

  contender = new LeaderContender(
      group.get(),
      stringify(json),
      master::MASTER_INFO_JSON_LABEL);
  candidacy = contender->contend();
  return candidacy.get();
}
Exemplo n.º 19
0
// Splits the string using the provided delimiters.
// The string is split each time at the first character
// that matches any of the characters specified in delims.
// Empty tokens are allowed in the result.
// Optionally, maximum number of tokens to be returned
// can be specified.
inline std::vector<std::string> split(
    const std::string& s,
    const std::string& delims,
    const Option<unsigned int>& n = None())
{
  std::vector<std::string> tokens;
  size_t offset = 0;
  size_t next = 0;

  while (n.isNone() || n.get() > 0) {
    next = s.find_first_of(delims, offset);
    if (next == std::string::npos) {
      tokens.push_back(s.substr(offset));
      break;
    }

    tokens.push_back(s.substr(offset, next - offset));
    offset = next + 1;

    // Finish splitting if we've found enough tokens.
    if (n.isSome() && tokens.size() == n.get() - 1) {
      tokens.push_back(s.substr(offset));
      break;
    }
  }
  return tokens;
}
Exemplo n.º 20
0
TEST(NoneTest, Test)
{
  Option<string> o = none1();
  EXPECT_TRUE(o.isNone());
  o = none2();
  EXPECT_TRUE(o.isNone());
  o = none3(none1());
  EXPECT_TRUE(o.isNone());

  Result<string> r = none1();
  EXPECT_TRUE(r.isNone());
  r = none4();
  EXPECT_TRUE(r.isNone());
  r = none5(none1());
  EXPECT_TRUE(r.isNone());
}
Exemplo n.º 21
0
Try<MasterContender*> MasterContender::create(
    const Option<string>& zk_,
    const Option<string>& masterContenderModule_,
    const Option<Duration>& zkSessionTimeout_)
{
  if (masterContenderModule_.isSome()) {
    return modules::ModuleManager::create<MasterContender>(
        masterContenderModule_.get());
  }

  if (zk_.isNone()) {
    return new StandaloneMasterContender();
  }

  const string& zk = zk_.get();

  if (strings::startsWith(zk, "zk://")) {
    Try<zookeeper::URL> url = zookeeper::URL::parse(zk);
    if (url.isError()) {
      return Error(url.error());
    }
    if (url->path == "/") {
      return Error(
          "Expecting a (chroot) path for ZooKeeper ('/' is not supported)");
    }
    return new ZooKeeperMasterContender(
        url.get(),
        zkSessionTimeout_.getOrElse(MASTER_CONTENDER_ZK_SESSION_TIMEOUT));
  } else if (strings::startsWith(zk, "file://")) {
    // Load the configuration out of a file. While Mesos and related
    // programs always use <stout/flags> to process the command line
    // arguments (and therefore file://) this entrypoint is exposed by
    // libmesos, with frameworks currently calling it and expecting it
    // to do the argument parsing for them which roughly matches the
    // argument parsing Mesos will do.
    // TODO(cmaloney): Rework the libmesos exposed APIs to expose
    // A "flags" endpoint where the framework can pass the command
    // line arguments and they will be parsed by <stout/flags> and the
    // needed flags extracted, and then change this interface to
    // require final values from the flags. This means that a
    // framework doesn't need to know how the flags are passed to
    // match mesos' command line arguments if it wants, but if it
    // needs to inspect/manipulate arguments, it can.
    LOG(WARNING) << "Specifying master election mechanism / ZooKeeper URL to "
                    "be read out of a file via 'file://' is deprecated inside "
                    "Mesos and will be removed in a future release.";
    const string& path = zk.substr(7);
    const Try<string> read = os::read(path);
    if (read.isError()) {
      return Error("Failed to read from file at '" + path + "'");
    }

    return create(strings::trim(read.get()));
  }

  CHECK(!strings::startsWith(zk, "file://"));

  return Error("Failed to parse '" + zk + "'");
}
Exemplo n.º 22
0
Future<http::Response> Logging::toggle(const http::Request& request)
{
  Option<std::string> level = request.query.get("level");
  Option<std::string> duration = request.query.get("duration");

  if (level.isNone() && duration.isNone()) {
    return http::OK(stringify(FLAGS_v) + "\n");
  }

  if (level.isSome() && duration.isNone()) {
    return http::BadRequest("Expecting 'duration=value' in query.\n");
  } else if (level.isNone() && duration.isSome()) {
    return http::BadRequest("Expecting 'level=value' in query.\n");
  }

  Try<int> v = numify<int>(level.get());

  if (v.isError()) {
    return http::BadRequest(v.error() + ".\n");
  }

  if (v.get() < 0) {
    return http::BadRequest(
        "Invalid level '" + stringify(v.get()) + "'.\n");
  } else if (v.get() < original) {
    return http::BadRequest(
        "'" + stringify(v.get()) + "' < original level.\n");
  }

  Try<Duration> d = Duration::parse(duration.get());

  if (d.isError()) {
    return http::BadRequest(d.error() + ".\n");
  }

  // Set the logging level.
  set(v.get());

  // Start a revert timer (if necessary).
  if (v.get() != original) {
    timeout = d.get();
    delay(timeout.remaining(), this, &This::revert);
  }

  return http::OK();
}
Exemplo n.º 23
0
void CoordinatorProcess::electingFinished(const Option<uint64_t>& position)
{
  CHECK_EQ(state, ELECTING);

  if (position.isNone()) {
    state = INITIAL;
  } else {
    state = ELECTED;
  }
}
Exemplo n.º 24
0
// Overload of os::pids for filtering by groups and sessions.
// A group / session id of 0 will fitler on the group / session ID
// of the calling process.
inline Try<std::set<pid_t>> pids(Option<pid_t> group, Option<pid_t> session)
{
  if (group.isNone() && session.isNone()) {
    return os::pids();
  } else if (group.isSome() && group.get() < 0) {
    return Error("Invalid group");
  } else if (session.isSome() && session.get() < 0) {
    return Error("Invalid session");
  }

  const Try<std::list<Process>> processes = os::processes();

  if (processes.isError()) {
    return Error(processes.error());
  }

  // Obtain the calling process group / session ID when 0 is provided.
  if (group.isSome() && group.get() == 0) {
    group = getpgid(0);
  }
  if (session.isSome() && session.get() == 0) {
    session = getsid(0);
  }

  std::set<pid_t> result;
  foreach (const Process& process, processes.get()) {
    // Group AND Session (intersection).
    if (group.isSome() && session.isSome()) {
      if (group.get() == process.group &&
          process.session.isSome() &&
          session.get() == process.session.get()) {
        result.insert(process.pid);
      }
    } else if (group.isSome() && group.get() == process.group) {
      result.insert(process.pid);
    } else if (session.isSome() && process.session.isSome() &&
               session.get() == process.session.get()) {
      result.insert(process.pid);
    }
  }

  return result;
}
Exemplo n.º 25
0
Future<http::Response> Logging::toggle(
    const http::Request& request,
    const Option<http::authentication::Principal>&)
{
  Option<std::string> level = request.url.query.get("level");
  Option<std::string> duration = request.url.query.get("duration");

  if (level.isNone() && duration.isNone()) {
    return http::OK(stringify(FLAGS_v) + "\n");
  }

  if (level.isSome() && duration.isNone()) {
    return http::BadRequest("Expecting 'duration=value' in query.\n");
  } else if (level.isNone() && duration.isSome()) {
    return http::BadRequest("Expecting 'level=value' in query.\n");
  }

  Try<int> v = numify<int>(level.get());

  if (v.isError()) {
    return http::BadRequest(v.error() + ".\n");
  }

  if (v.get() < 0) {
    return http::BadRequest(
        "Invalid level '" + stringify(v.get()) + "'.\n");
  } else if (v.get() < original) {
    return http::BadRequest(
        "'" + stringify(v.get()) + "' < original level.\n");
  }

  Try<Duration> d = Duration::parse(duration.get());

  if (d.isError()) {
    return http::BadRequest(d.error() + ".\n");
  }

  return set_level(v.get(), d.get())
      .then([]() -> http::Response {
        return http::OK();
      });
}
Exemplo n.º 26
0
inline Result<gid_t> getgid(const Option<std::string>& user = None())
{
  if (user.isNone()) {
    return ::getgid();
  }

  struct passwd passwd;
  struct passwd* result = nullptr;

  int size = sysconf(_SC_GETPW_R_SIZE_MAX);
  if (size == -1) {
    // Initial value for buffer size.
    size = 1024;
  }

  while (true) {
    char* buffer = new char[size];

    if (getpwnam_r(user.get().c_str(), &passwd, buffer, size, &result) == 0) {
      // The usual interpretation of POSIX is that getpwnam_r will
      // return 0 but set result == nullptr if the group is not found.
      if (result == nullptr) {
        delete[] buffer;
        return None();
      }

      gid_t gid = passwd.pw_gid;
      delete[] buffer;
      return gid;
    } else {
      // RHEL7 (and possibly other systems) will return non-zero and
      // set one of the following errors for "The given name or uid
      // was not found." See 'man getpwnam_r'. We only check for the
      // errors explicitly listed, and do not consider the ellipsis.
      if (errno == ENOENT ||
          errno == ESRCH ||
          errno == EBADF ||
          errno == EPERM) {
        delete[] buffer;
        return None();
      }

      if (errno != ERANGE) {
        delete[] buffer;
        return ErrnoError("Failed to get username information");
      }
      // getpwnam_r set ERANGE so try again with a larger buffer.
      size *= 2;
      delete[] buffer;
    }
  }

  UNREACHABLE();
}
Exemplo n.º 27
0
Try<PID<slave::Slave>> MesosTest::StartSlave(
    mesos::slave::ResourceEstimator* resourceEstimator,
    const Option<slave::Flags>& flags)
{
  return cluster.slaves.start(
      flags.isNone() ? CreateSlaveFlags() : flags.get(),
      None(),
      None(),
      None(),
      None(),
      resourceEstimator);
}
Exemplo n.º 28
0
Try<PID<slave::Slave>> MesosTest::StartSlave(
    mesos::slave::QoSController* qoSController,
    const Option<slave::Flags>& flags)
{
  return cluster.slaves.start(
      flags.isNone() ? CreateSlaveFlags() : flags.get(),
      None(),
      None(),
      None(),
      None(),
      None(),
      qoSController);
}
Exemplo n.º 29
0
int main(int argc, char** argv)
{
  // Find this executable's directory to locate executor.
  string path = os::realpath(dirname(argv[0])).get();
  string uri = path + "/test-executor";
  if (getenv("MESOS_BUILD_DIR")) {
    uri = string(getenv("MESOS_BUILD_DIR")) + "/src/test-executor";
  }

  mesos::internal::logging::Flags flags;

  string role;
  flags.add(&role,
            "role",
            "Role to use when registering",
            "*");

  Option<string> master;
  flags.add(&master,
            "master",
            "ip:port of master to connect");

  Try<Nothing> load = flags.load(None(), argc, argv);

  if (load.isError()) {
    cerr << load.error() << endl;
    usage(argv[0], flags);
    exit(1);
  } else if (master.isNone()) {
    cerr << "Missing --master" << endl;
    usage(argv[0], flags);
    exit(1);
  }

  ExecutorInfo executor;
  executor.mutable_executor_id()->set_value("default");
  executor.mutable_command()->set_value(uri);
  executor.set_name("Test Executor (C++)");
  executor.set_source("cpp_test");

  TestScheduler scheduler(executor, role);

  FrameworkInfo framework;
  framework.set_user(""); // Have Mesos fill in the current user.
  framework.set_name("Test Framework (C++)");
  framework.set_role(role);

  MesosSchedulerDriver driver(&scheduler, framework, master.get());

  return driver.run() == DRIVER_STOPPED ? 0 : 1;
}
Exemplo n.º 30
0
// Creates a null-terminated array of null-terminated strings that will be
// passed to `CreateProcess` as the `lpEnvironment` argument, as described by
// MSDN[1]. This array needs to be sorted in alphabetical order, but the `map`
// already takes care of that. Note that this function does not handle Unicode
// environments, so it should not be used in conjunction with the
// `CREATE_UNICODE_ENVIRONMENT` flag.
//
// [1] https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx
inline Option<string> createProcessEnvironment(
    const Option<map<string, string>>& env)
{
  if (env.isNone() || (env.isSome() && env.get().size() == 0)) {
    return None();
  }

  Option<map<string, string>> cuEnv = getCUEnvironment();

  if (cuEnv.isNone() || (cuEnv.isSome() && cuEnv.get().size() == 0)) {
    return None();
  }

  map<string, string> combEnv = env.get();

  foreachpair(const string& key, const string& value, cuEnv.get()) {
    combEnv[key] = value;
  }

  string environmentString;
  foreachpair (const string& key, const string& value, combEnv) {
    environmentString += key + '=' + value + '\0';
  }