Ejemplo n.º 1
0
	std::future<bool> UserData::SendFriendResponse(const UUID &id, const UUID &requester, const std::string &response,
		BooleanCallback success, APIFailureCallback failure)
	{
		return std::async(std::launch::async, [=]() -> bool {
			std::stringstream url;
			url << "/friends/" << id.toString() << "/response";

			std::map<std::string, std::string> params{
				std::make_pair("requester_id", requester.toString()),
				std::make_pair("action", response)
			};

			std::string error;

			APIRequestManager *manager = APIRequestManager::GetDefaultManager();
			boost::optional<std::string> response = manager->Send(url.str(), "POST", params, error);
			if (response.is_initialized()) {
				Poco::JSON::Parser parser;
				auto jsonObject = parser.parse(response.get()).extract<JSONObject::Ptr>();
				return jsonObject->getValue<bool>("success");
			}
			else {
				if (failure) {
					failure(error);
				}

				return false;
			}
		});
	}
Ejemplo n.º 2
0
	std::future<TUserDataList> UserData::GetPendingFriends(const UUID &id, UserDataListCallback success,
		APIFailureCallback failure)
	{
		return std::async(std::launch::async, [=]() -> TUserDataList {
			std::stringstream url;
			url << "/friends/" << id.toString() << "/pending";

			std::string error;

			APIRequestManager *manager = APIRequestManager::GetDefaultManager();
			boost::optional<std::string> response = manager->Get(url.str(), error);
			if (response.is_initialized()) {
				TUserDataList users;
				HandleResult<UserData>(response.get(), "users", success, failure, users);

				return users;
			}
			else {
				if (failure) {
					failure(error);
				}

				return TUserDataList();
			}
		});
	}
Ejemplo n.º 3
0
int main(int argc, char** argv)
{
	UUID uuid;
	
	std::string arg;
	if (argc > 1)
		arg = argv[1];
	
	try
	{
		if (arg == "-random")
			uuid = UUIDGenerator::defaultGenerator().createRandom();
		else if (arg.empty())
			uuid = UUIDGenerator::defaultGenerator().create();
		else
			uuid = UUIDGenerator::defaultGenerator().createFromName(UUID::uri(), arg);
		
		std::cout << uuid.toString() << std::endl;
	}
	catch (Exception& exc)
	{
		std::cerr << exc.displayText() << std::endl;
		return 1;
	}
	
	return 0;
}
Ejemplo n.º 4
0
void test007() {
  const UUID u0 = {0xe87db3a0, 0x109a, 0x4ecb, {0x86, 0x64, 0x66, 0x85,
						0x45, 0x20, 0xa6, 0xcc}};
  UUID u1;
  const char u2[] = "e87db3a0-109a-4ecb-8664-66854520a6cc";
  char u3[39];
  char u4[39];
  char u5[39];
  char u6[38];
  int rv;

  ASSERT(sizeof(u0) == 16, "UUID structure is of unexpected size");

  ASSERT(sizeof(u2) == 37, "u2 is of unexpected size");

  u1 = UUID_null;
  u1.fromString(u2);
  VERIFY(u1.equals(u0), "u2 was not parsed properly into u1");

  rv = snprintf(u3, 39, "{%s}", u2);
  ASSERT(rv == 38, "copying u2 into u3 with curly braces failed");

  u1 = UUID_null;
  VERIFY(u1.equals(UUID_null), "u1 is not equal to UUID_null after resetting");

  u1.fromString(u3);
  VERIFY(u1.equals(u0), "u3 was not parsed properly into u1");

  rv = snprintf(u4, 39, "{%x-%x-%x-%x%x-%x%x%x%x%x%x}",
		u0.data0, u0.data1, u0.data2,
		u0.data3[0],
		u0.data3[1],
		u0.data3[2],
		u0.data3[3],
		u0.data3[4],
		u0.data3[5],
		u0.data3[6],
		u0.data3[7]);
  ASSERT(rv == 38, "formatting u0 into u4 (with snprintf) failed");

  VERIFY(strncmp(u3, u4, 39) == 0, "result of formatting u0 into u4 was different from u3");

  u0.toString(u5);
  VERIFY(strncmp(u3, u5, 39) == 0, "result of using toString on u0 was different from u3");

  rv = snprintf(u6, 38, "{%s", u2);
  ASSERT(rv == 37, "copying u2 into u6 with starting curly brace failed");

  u1 = u0;
  u1.fromString(u6);
  VERIFY(u1.equals(UUID_null), "fromString wrongfully accepted u6 into u1");

  rv = snprintf(u6, 38, "%s}", u2);
  ASSERT(rv == 37, "copying u2 into u6 with ending curly brace failed");

  u1 = u0;
  u1.fromString(u6);
  VERIFY(u1.equals(UUID_null), "fromString wrongfully accepted u6 into u1");
}
Ejemplo n.º 5
0
void UUIDTest::testTryParse()
{
	UUID uuid;
	assert (uuid.tryParse("6BA7B810-9DAD-11D1-80B4-00C04FD430C8"));
	assert (uuid.toString() == "6ba7b810-9dad-11d1-80b4-00c04fd430c8");

	UUID notUuid;
	assert (!notUuid.tryParse("not a uuid"));
	assert (notUuid.isNull());
}
Ejemplo n.º 6
0
void Broadcast::initiateHandshake(Broadcast::BroadcastStream*stream,const Network::Address&addy,const UUID &name) {
    Protocol::Broadcast message;
    message.set_broadcast_name(name);
    String str;
    if (message.SerializeToString(&str)) {
        (*stream)->send(MemoryReference(str),Network::ReliableOrdered);
        //FIXME
    }else {
        SILOG(broadcast,error,"Cannot send memory reference to UUID "<<name.toString());
    }
}
Ejemplo n.º 7
0
StatusWith<BSONObj> RollbackSourceImpl::getCollectionInfoByUUID(const std::string& db,
                                                                const UUID& uuid) const {
    std::list<BSONObj> info = _getConnection()->getCollectionInfos(db, BSON("info.uuid" << uuid));
    if (info.empty()) {
        return StatusWith<BSONObj>(ErrorCodes::NoSuchKey,
                                   str::stream()
                                       << "No collection info found for collection with uuid: "
                                       << uuid.toString()
                                       << " in db: "
                                       << db);
    }
    invariant(info.size() == 1U);
    return info.front();
}
Ejemplo n.º 8
0
        void LightManager::updateUUID(UUID const& uuid)
        {
            const std::string uuidStr = uuid.toString();
            auto find = m_Lights.find(uuidStr);

            if(find != m_Lights.end())
            {
                auto object = find->second;

                m_Lights.erase(find);

                m_Lights.insert(std::make_pair(object->getUUID().toString(), object));
            }
        }
Ejemplo n.º 9
0
inline std::string getExecutorSentinelPath(
    const std::string& rootDir,
    const SlaveID& slaveId,
    const FrameworkID& frameworkId,
    const ExecutorID& executorId,
    const UUID& executorUUID)
{
  return strings::format(
      EXECUTOR_SENTINEL_PATH,
      rootDir,
      slaveId,
      frameworkId,
      executorId,
      executorUUID.toString()).get();
}
Ejemplo n.º 10
0
inline std::string getLibprocessPidPath(
    const std::string& rootDir,
    const SlaveID& slaveId,
    const FrameworkID& frameworkId,
    const ExecutorID& executorId,
    const UUID& executorUUID)
{
  return strings::format(
      LIBPROCESS_PID_PATH,
      rootDir,
      slaveId,
      frameworkId,
      executorId,
      executorUUID.toString()).get();
}
Ejemplo n.º 11
0
inline std::string getForkedPidPath(
    const std::string& rootDir,
    const SlaveID& slaveId,
    const FrameworkID& frameworkId,
    const ExecutorID& executorId,
    const UUID& executorUUID)
{
  return strings::format(
      FORKED_PID_PATH,
      rootDir,
      slaveId,
      frameworkId,
      executorId,
      executorUUID.toString()).get();
}
Ejemplo n.º 12
0
int Plugin::replaceWithLink(std::string filepath)
{
    std::cout << "Replacing with link " << filepath.c_str() << std::endl;

    std::ifstream fstr(filepath.c_str());
    MD5Engine md5;
    DigestOutputStream ostr(md5);
    Poco::StreamCopier::copyStream(fstr, ostr);
    ostr.flush();
    const DigestEngine::Digest& digest = md5.digest();
    std::string sourceMd5 = DigestEngine::digestToHex(digest);
    std::cout << "File contents MD5 sum: " << sourceMd5.c_str() << std::endl;

    // Generate new file name
    UUIDGenerator gen;
    UUID tmpUuid = gen.createRandom();
    std::string uuid = tmpUuid.toString(); 
    std::string newFile(Plugin::GIT_CACHE_DIR);
    newFile.append("/");
    newFile.append(uuid);

    Process::Args args;
    args.push_back(filepath);
    args.push_back(newFile);
    Poco::ProcessHandle ph = Process::launch("mv", args, 0, 0, 0);

    // Failback with sudo
    if (ph.wait() != 0)
    {
        args.clear();
        args.push_back("mv");
        args.push_back(filepath);
        args.push_back(newFile);
        ph = Process::launch("sudo", args, 0, 0, 0);
    }

    // Check if file was moved
    File originalFile(filepath);
    if (originalFile.exists())
    {
        std::cout << "Failed to move original file" << std::endl;
        return -1;
    }

    return 1;
}
Ejemplo n.º 13
0
void ASIOSocketWrapper::sendProtocolHeader(const MultiplexedSocketPtr&parentMultiSocket, const Address& address,  const UUID&value, unsigned int numConnections) {
//    if (paerntMultiSocket->isZeroDelim()) {
    std::stringstream header;
    header << "GET /" << value.toString() << " HTTP/1.1\r\n";
    header << "Upgrade: WebSocket\r\n";
    header << "Connection: Upgrade\r\n";

    std::string hostname=address.getHostName();
    for (std::string::iterator hi=hostname.begin(),he=hostname.end(); hi!=he; ++hi) {
        *hi=std::tolower(*hi);
    }
    header << "Host: " << hostname;
    if (address.getService()!="80")
        header << ":" << address.getService();
    header << "\r\n";

    header << "Origin: " << address.getHostName() << "\r\n";

    if (parentMultiSocket->getStreamType()!= TCPStream::RFC_6455) {
        header << "Sec-WebSocket-Key1: x!|6 j9  U 1 guf  36Y04  |   4\r\n";
        header << "Sec-WebSocket-Key2: 3   59   2 E4   _11  x80      \r\n";
    } else {
        header << "Sec-WebSocket-Version: 13\r\n";
        header << "Sec-WebSocket-Key: MTIzNDU2Nzg5MGFiY2RlZg==\r\n";
    }
    header << "Sec-WebSocket-Protocol: "
           << (parentMultiSocket->getStreamType()==TCPStream::BASE64_ZERODELIM?"wssst":"sst")
           << numConnections << "\r\n";
    header << "\r\n";
    if (parentMultiSocket->getStreamType()!= TCPStream::RFC_6455) {
        header << "abcdefgh";
    }

    std::string finalHeader(header.str());
    Chunk * headerData= new Chunk(finalHeader.begin(),finalHeader.end());
    rawSend(parentMultiSocket,headerData,true);
    /*
        }else {
            UUID return_value=(parentMultiSocket->isZeroDelim()?massageUUID(UUID::random()):UUID::random());

            Chunk *headerData=new Chunk(TCPStream::TcpSstHeaderSize);
            copyHeader(&*headerData->begin(),parentMultiSocket->isZeroDelim()?TCPStream::WEBSOCKET_STRING_PREFIX():TCPStream::STRING_PREFIX(),value,numConnections);
            rawSend(parentMultiSocket,headerData,true);
        }
    */
}
Ejemplo n.º 14
0
inline std::string getTaskUpdatesPath(
    const std::string& rootDir,
    const SlaveID& slaveId,
    const FrameworkID& frameworkId,
    const ExecutorID& executorId,
    const UUID& executorUUID,
    const TaskID& taskId)
{
  return strings::format(
      TASK_UPDATES_PATH,
      rootDir,
      slaveId,
      frameworkId,
      executorId,
      executorUUID.toString(),
      taskId).get();
}
Ejemplo n.º 15
0
	void SpellData::GetSpellById(const UUID &id, std::function<void(SpellDataPtr)> success, APIFailureCallback failure)
	{
		APIRequestManager *manager = APIRequestManager::GetDefaultManager();
		std::stringstream url;
		url << "/spell/" << id.toString();

		manager->Send(url.str(), "GET", "", [success](std::istream &stream) {
			Poco::JSON::Parser parser;

			auto object = parser.parse(stream).extract<JSONObject::Ptr>();
			auto data = std::make_shared<SpellData>();
			data->FromJSON(object);

			success(data);

		}, [failure](const std::string &error)  {
			failure(error);
		});
	}
Ejemplo n.º 16
0
/*
  This is the function that we use to add an object.  generateAck is true if you want to generate an ack message to server idServerAckTo

  If you're initially adding an object to the world, you should use the newObjectAdd function instead.
*/
void CraqObjectSegmentation::addMigratedObject(const UUID& obj_id, float radius, ServerID idServerAckTo, bool generateAck)
{
    if (mStopping)
        return;


    if (generateAck)
    {
        CraqDataKey cdk;
        convert_obj_id_to_dht_key(obj_id,cdk);

        CraqDataSetGet cdSetGet(cdk, CraqEntry(mContext->id(),radius) ,true,CraqDataSetGet::SET);

        receivingObjects_m.lock();
        mReceivingObjects.insert(ObjectSet::value_type(obj_id,CraqEntry(mContext->id(),radius)));
        receivingObjects_m.unlock();

        TrackedSetResultsData tsrd;
        tsrd.migAckMsg = generateAcknowledgeMessage(obj_id, radius, idServerAckTo);
        tsrd.dur =  Time::local() - Time::epoch();

        int trackID = getUniqueTrackID();
        craqDhtSet.set(cdSetGet,trackID);
        trackingMessages[trackID] = tsrd;
    }
    else
    {
        //potentially clean up: we should really only be adding objects without generating acks using the newObjectAdd interface
        CraqDataKey cdk;
        convert_obj_id_to_dht_key(obj_id,cdk);

        CraqDataSetGet cdSetGet(cdk, CraqEntry(mContext->id(),radius) ,false,CraqDataSetGet::SET);
        int trackID = getUniqueTrackID();
        craqDhtSet.set(cdSetGet, trackID);


        std::pair<ObjectSet::iterator, bool> inserted = mObjects.insert(ObjectSet::value_type(obj_id,CraqEntry(mContext->id(),radius)));
        if (inserted.second)
        {
            std::cout<<"\n\nAdding object:  "<<obj_id.toString()<<"\n";
        }
    }
}
Ejemplo n.º 17
0
int UUID::compareTo( const UUID& value ) const {
    return apr_strnatcmp( this->toString().c_str(), value.toString().c_str() );
}
Ejemplo n.º 18
0
///gets called when a complete 24 byte header is actually received: uses the UUID within to match up appropriate sockets
void buildStream(TcpSstHeaderArray *buffer,
                 TCPSocket *socket,
                 std::tr1::shared_ptr<TCPStreamListener::Data> data,
                 const boost::system::error_code &error,
                 std::size_t bytes_transferred)
{
    // Buffer always needs to be cleaned up when we get out of this method
    std::auto_ptr<TcpSstHeaderArray> buffer_ptr(buffer);

    // Sanity check start
    if (error || bytes_transferred < 5 || std::string((const char*)buffer->begin(), 5) != std::string("GET /")) {
        SILOG(tcpsst,warning,"Connection received with truncated header: "<<error);
        delete socket;
        return;
    }

    // Sanity check end: 8 bytes from WebSocket spec after headers, then
    // \r\n\r\n before that.
    std::string buffer_str((const char*)buffer->begin(), bytes_transferred);
    if (buffer_str[ bytes_transferred - 12] != '\r' ||
        buffer_str[ bytes_transferred - 11] != '\n' ||
        buffer_str[ bytes_transferred - 10] != '\r' ||
        buffer_str[ bytes_transferred - 9] != '\n')
    {
        SILOG(tcpsst,warning,"Request doesn't end properly:\n" << buffer_str << "\n");
        delete socket;
        return;
    }

    std::string headers_str = buffer_str.substr(0, bytes_transferred - 10);
    // Parse headers
    UUID context;
    std::map<std::string, std::string> headers;
    std::string::size_type offset = 0;
    while(offset < headers_str.size()) {
        std::string::size_type last_offset = offset;
        offset = headers_str.find("\r\n", offset);
        if (offset == std::string::npos) {
            SILOG(tcpsst,warning,"Error parsing headers.");
            delete socket;
            return;
        }

        std::string line = headers_str.substr(last_offset, offset - last_offset);

        // Special case the initial GET line
        if (line.substr(0, 5) == "GET /") {
            std::string::size_type uuid_end = line.find(' ', 5);
            if (uuid_end == std::string::npos) {
                SILOG(tcpsst,warning,"Error parsing headers: invalid get line.");
                delete socket;
                return;
            }
            std::string uuid_str = line.substr(5, uuid_end - 5);
            try {
                context = UUID(uuid_str,UUID::HumanReadable());
            } catch(...) {
                SILOG(tcpsst,warning,"Error parsing headers: invalid get uuid.");
                delete socket;
                return;
            }

            offset += 2;
            continue;
        }

        std::string::size_type colon = line.find(":");
        if (colon == std::string::npos) {
            SILOG(tcpsst,warning,"Error parsing headers: missing colon.");
            delete socket;
            return;
        }
        std::string head = line.substr(0, colon);
        std::string val = line.substr(colon+2);

        headers[head] = val;

        // Advance to get past the \r\n
        offset += 2;
    }

    if (headers.find("Host") == headers.end() ||
        headers.find("Origin") == headers.end() ||
        headers.find("Sec-WebSocket-Key1") == headers.end() ||
        headers.find("Sec-WebSocket-Key2") == headers.end())
    {
        SILOG(tcpsst,warning,"Connection request didn't specify all required fields.");
        delete socket;
        return;
    }

    std::string host = headers["Host"];
    std::string origin = headers["Origin"];
    std::string protocol = "wssst1";
    if (headers.find("Sec-WebSocket-Protocol") != headers.end())
        protocol = headers["Sec-WebSocket-Protocol"];
    std::string key1 = headers["Sec-WebSocket-Key1"];
    std::string key2 = headers["Sec-WebSocket-Key2"];
    std::string key3 = buffer_str.substr(bytes_transferred - 8);
    assert(key3.size() == 8);

    std::string reply_str = getWebSocketSecReply(key1, key2, key3);

    bool binaryStream=protocol.find("sst")==0;
    bool base64Stream=!binaryStream;
    boost::asio::ip::tcp::no_delay option(data->mNoDelay);
    socket->set_option(option);
    IncompleteStreamMap::iterator where=sIncompleteStreams.find(context);

    unsigned int numConnections=1;

    for (std::string::iterator i=protocol.begin(),ie=protocol.end();i!=ie;++i) {
        if (*i>='0'&&*i<='9') {
            char* endptr=NULL;
            const char *start=protocol.c_str();
            size_t offset=(i-protocol.begin());
            start+=offset;
            numConnections=strtol(start,&endptr,10);
            size_t numberlen=endptr-start;
            if (numConnections>data->mMaxSimultaneousSockets) {
                numConnections=data->mMaxSimultaneousSockets;
                char numcon[256];
                sprintf(numcon,"%d",numConnections);
                protocol=protocol.substr(0,offset)+numcon+protocol.substr(offset+numberlen);
            }
            break;
        }
    }

    if (where==sIncompleteStreams.end()){
        sIncompleteStreams[context].mNumSockets=numConnections;
        where=sIncompleteStreams.find(context);
        assert(where!=sIncompleteStreams.end());
        // Setup a timer to clean up the sockets if we don't complete it in time
        data->strand->post(
            Duration::seconds(10),
            std::tr1::bind(&handleBuildStreamTimeout, context)
        );
    }
    if ((int)numConnections!=where->second.mNumSockets) {
        SILOG(tcpsst,warning,"Single client disagrees on number of connections to establish: "<<numConnections<<" != "<<where->second.mNumSockets);
        sIncompleteStreams.erase(where);
    }else {
        where->second.mSockets.push_back(socket);
        where->second.mWebSocketResponses[socket] = reply_str;
        if (numConnections==(unsigned int)where->second.mSockets.size()) {
            MultiplexedSocketPtr shared_socket(
                MultiplexedSocket::construct<MultiplexedSocket>(data->strand,context,data->cb,base64Stream));
            shared_socket->initFromSockets(where->second.mSockets,data->mSendBufferSize);
            std::string port=shared_socket->getASIOSocketWrapper(0).getLocalEndpoint().getService();
            std::string resource_name='/'+context.toString();
            MultiplexedSocket::sendAllProtocolHeaders(shared_socket,origin,host,port,resource_name,protocol, where->second.mWebSocketResponses);
            sIncompleteStreams.erase(where);


            Stream::StreamID newID=Stream::StreamID(1);
            TCPStream * strm=new TCPStream(shared_socket,newID);

            TCPSetCallbacks setCallbackFunctor(&*shared_socket,strm);
            data->cb(strm,setCallbackFunctor);
            if (setCallbackFunctor.mCallbacks==NULL) {
                SILOG(tcpsst,error,"Client code for stream "<<newID.read()<<" did not set listener on socket");
                shared_socket->closeStream(shared_socket,newID);
            }
        }else{
            sStaleUUIDs.push_back(context);
        }
    }
}
Ejemplo n.º 19
0
Try<RunState> RunState::recover(
    const string& rootDir,
    const SlaveID& slaveId,
    const FrameworkID& frameworkId,
    const ExecutorID& executorId,
    const UUID& uuid,
    bool strict)
{
  RunState state;
  state.id = uuid;
  string message;

  // Find the tasks.
  const Try<list<string> >& tasks = os::glob(strings::format(
      paths::TASK_PATH,
      rootDir,
      slaveId,
      frameworkId,
      executorId,
      uuid.toString(),
      "*").get());

  if (tasks.isError()) {
    return Error("Failed to find tasks for executor run " + uuid.toString() +
                 ": " + tasks.error());
  }

  // Recover tasks.
  foreach (const string& path, tasks.get()) {
    TaskID taskId;
    taskId.set_value(os::basename(path).get());

    const Try<TaskState>& task = TaskState::recover(
        rootDir, slaveId, frameworkId, executorId, uuid, taskId, strict);

    if (task.isError()) {
      return Error(
          "Failed to recover task " + taskId.value() + ": " + task.error());
    }

    state.tasks[taskId] = task.get();
  }

  // Read the forked pid.
  string path = paths::getForkedPidPath(
      rootDir, slaveId, frameworkId, executorId, uuid);

  Try<string> pid = os::read(path);

  if (pid.isError()) {
    message = "Failed to read executor's forked pid from '" + path +
              "': " + pid.error();

    if (strict) {
      return Error(message);
    } else {
      LOG(WARNING) << message;
      return state;
    }
  }

  Try<pid_t> forkedPid = numify<pid_t>(pid.get());
  if (forkedPid.isError()) {
    return Error("Failed to parse forked pid " + pid.get() +
                 ": " + forkedPid.error());
  }

  state.forkedPid = forkedPid.get();

  // Read the libprocess pid.
  path = paths::getLibprocessPidPath(
      rootDir, slaveId, frameworkId, executorId, uuid);

  pid = os::read(path);

  if (pid.isError()) {
    message = "Failed to read executor's libprocess pid from '" + path +
              "': " + pid.error();

    if (strict) {
      return Error(message);
    } else {
      LOG(WARNING) << message;
      return state;
    }
  }

  state.libprocessPid = process::UPID(pid.get());

  return state;
}
Ejemplo n.º 20
0
/*
  If we get a message to move an object that our server holds, then we add the object's id to mInTransit.
  Whatever calls this must verify that the object is on this server.
  I can do the check in the function by querrying bambooDht as well
*/
void CraqObjectSegmentation::migrateObject(const UUID& obj_id, const OSegEntry& new_server_id)
{
    if (mStopping)
        return;

    //log the message.
    CONTEXT_SPACETRACE(objectBeginMigrate,
                       obj_id,mContext->id(),
                       new_server_id.server());

    InTransitMap::const_iterator transIter = mInTransitOrLookup.find(obj_id);

    TransLookup tmpTransLookup;
    tmpTransLookup.sID = CraqEntry(new_server_id);

    Duration tmpDurer = Time::local() - Time::epoch();

    tmpTransLookup.timeAdmitted = (int)tmpDurer.toMilliseconds();

    mInTransitOrLookup[obj_id] = tmpTransLookup;

    //erases the local copy of obj_id
    UUID tmp_id = obj_id; //note: can probably delete this line

    //erase the local copy of the object.
    size_t num_erased = mObjects.erase(obj_id);
#ifdef CRAQ_DEBUG
    if (num_erased == 0)
    {
        std::cout<<"\n\nThe object clearly wasn't registered on this server.  This is obj id:  " <<  obj_id.toString() <<  ".  This is time:   " <<mContext->simTime().raw() << " Oh no.   ";

        if (clearToMigrate(obj_id))
            std::cout<<"  Likely a problem with clear to migrate\n\n";
        else
            std::cout<<"\n\n clear to migrate is fine migration is being called from somewhere besides server.cpp\n\n";
    }
#endif
}
Ejemplo n.º 21
0
Try<RunState> RunState::recover(
    const string& rootDir,
    const SlaveID& slaveId,
    const FrameworkID& frameworkId,
    const ExecutorID& executorId,
    const UUID& uuid,
    bool strict)
{
  RunState state;
  state.id = uuid;
  string message;

  // Find the tasks.
  const Try<list<string> >& tasks = os::glob(strings::format(
      paths::TASK_PATH,
      rootDir,
      slaveId,
      frameworkId,
      executorId,
      uuid.toString(),
      "*").get());

  if (tasks.isError()) {
    return Error("Failed to find tasks for executor run " + uuid.toString() +
                 ": " + tasks.error());
  }

  // Recover tasks.
  foreach (const string& path, tasks.get()) {
    TaskID taskId;
    taskId.set_value(os::basename(path).get());

    const Try<TaskState>& task = TaskState::recover(
        rootDir, slaveId, frameworkId, executorId, uuid, taskId, strict);

    if (task.isError()) {
      return Error(
          "Failed to recover task " + taskId.value() + ": " + task.error());
    }

    state.tasks[taskId] = task.get();
    state.errors += task.get().errors;
  }

  // Read the forked pid.
  string path = paths::getForkedPidPath(
      rootDir, slaveId, frameworkId, executorId, uuid);
  if (!os::exists(path)) {
    // This could happen if the slave died before the isolator
    // checkpointed the forked pid.
    LOG(WARNING) << "Failed to find executor forked pid file '" << path << "'";
    return state;
  }

  Try<string> pid = os::read(path);

  if (pid.isError()) {
    message = "Failed to read executor forked pid from '" + path +
              "': " + pid.error();

    if (strict) {
      return Error(message);
    } else {
      LOG(WARNING) << message;
      state.errors++;
      return state;
    }
  }

  if (pid.get().empty()) {
    // This could happen if the slave died after opening the file for
    // writing but before it checkpointed anything.
    LOG(WARNING) << "Found empty executor forked pid file '" << path << "'";
    return state;
  }

  Try<pid_t> forkedPid = numify<pid_t>(pid.get());
  if (forkedPid.isError()) {
    return Error("Failed to parse forked pid " + pid.get() +
                 ": " + forkedPid.error());
  }

  state.forkedPid = forkedPid.get();

  // Read the libprocess pid.
  path = paths::getLibprocessPidPath(
      rootDir, slaveId, frameworkId, executorId, uuid);

  if (!os::exists(path)) {
    // This could happen if the slave died before the executor
    // registered with the slave.
    LOG(WARNING)
      << "Failed to find executor libprocess pid file '" << path << "'";
    return state;
  }

  pid = os::read(path);

  if (pid.isError()) {
    message = "Failed to read executor libprocess pid from '" + path +
              "': " + pid.error();

    if (strict) {
      return Error(message);
    } else {
      LOG(WARNING) << message;
      state.errors++;
      return state;
    }
  }

  if (pid.get().empty()) {
    // This could happen if the slave died after opening the file for
    // writing but before it checkpointed anything.
    LOG(WARNING) << "Found empty executor libprocess pid file '" << path << "'";
    return state;
  }

  state.libprocessPid = process::UPID(pid.get());

  // See if the sentinel file exists.
  path = paths::getExecutorSentinelPath(
      rootDir, slaveId, frameworkId, executorId, uuid);

  state.completed = os::exists(path);

  return state;
}
Ejemplo n.º 22
0
void WpfExporter::exportCsProj(UUID projectUuid) {
	writeFile(directory.resolve(Paths::get(sysdir() + "-build", "Project.csproj")));
	p("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
	p("<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">");
		p("<PropertyGroup>", 1);
			p("<Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>", 2);
			p("<Platform Condition=\" '$(Platform)' == '' \">x86</Platform>", 2);
			p("<ProductVersion>8.0.30703</ProductVersion>", 2);
			p("<SchemaVersion>2.0</SchemaVersion>", 2);
			p("<ProjectGuid>{" + toUpperCase(projectUuid.toString()) + "}</ProjectGuid>", 2);
			p("<OutputType>Library</OutputType>", 2);
			p("<AppDesignerFolder>Properties</AppDesignerFolder>", 2);
			p("<RootNamespace>WpfApplication1</RootNamespace>", 2);
			p("<AssemblyName>WpfApplication1</AssemblyName>", 2);
			p("<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>", 2);
			p("<TargetFrameworkProfile>Client</TargetFrameworkProfile>", 2);
			p("<FileAlignment>512</FileAlignment>", 2);
			p("<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>", 2);
			p("<WarningLevel>4</WarningLevel>", 2);
		p("</PropertyGroup>", 1);
		p("<PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|x86' \">", 1);
			p("<PlatformTarget>x86</PlatformTarget>", 2);
			p("<DebugSymbols>true</DebugSymbols>", 2);
			p("<DebugType>full</DebugType>", 2);
			p("<Optimize>false</Optimize>", 2);
			p("<OutputPath>bin\\Debug\\</OutputPath>", 2);
			p("<DefineConstants>DEBUG;TRACE</DefineConstants>", 2);
			p("<ErrorReport>prompt</ErrorReport>", 2);
			p("<WarningLevel>4</WarningLevel>", 2);
		p("</PropertyGroup>", 1);
		p("<PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|x86' \">", 1);
			p("<PlatformTarget>x86</PlatformTarget>", 2);
			p("<DebugType>pdbonly</DebugType>", 2);
			p("<Optimize>true</Optimize>", 2);
			p("<OutputPath>bin\\Release\\</OutputPath>", 2);
			p("<DefineConstants>TRACE</DefineConstants>", 2);
			p("<ErrorReport>prompt</ErrorReport>", 2);
			p("<WarningLevel>4</WarningLevel>", 2);
		p("</PropertyGroup>", 1);
		p("<ItemGroup>", 1);
			p("<Reference Include=\"System\" />", 2);
			p("<Reference Include=\"System.Data\" />", 2);
			p("<Reference Include=\"System.Xml\" />", 2);
			p("<Reference Include=\"Microsoft.CSharp\" />", 2);
			p("<Reference Include=\"System.Core\" />", 2);
			p("<Reference Include=\"System.Xml.Linq\" />", 2);
			p("<Reference Include=\"System.Data.DataSetExtensions\" />", 2);
			p("<Reference Include=\"System.Xaml\">", 2);
				p("<RequiredTargetFramework>4.0</RequiredTargetFramework>", 3);
			p("</Reference>", 2);
			p("<Reference Include=\"WindowsBase\" />", 2);
			p("<Reference Include=\"PresentationCore\" />", 2);
			p("<Reference Include=\"PresentationFramework\" />", 2);
		p("</ItemGroup>", 1);
		p("<ItemGroup>", 1);
			includeFiles(directory.resolve(Paths::get(sysdir() + "-build", "Sources", "src")), directory.resolve(sysdir() + "-build"));
		p("</ItemGroup>", 1);
		p("<ItemGroup>", 1);
			p("<Compile Include=\"Properties\\AssemblyInfo.cs\">", 2);
				p("<SubType>Code</SubType>", 3);
			p("</Compile>", 2);
			p("<Compile Include=\"Properties\\Resources.Designer.cs\">", 2);
				p("<AutoGen>True</AutoGen>", 3);
				p("<DesignTime>True</DesignTime>", 3);
				p("<DependentUpon>Resources.resx</DependentUpon>", 3);
			p("</Compile>", 2);
			p("<Compile Include=\"Properties\\Settings.Designer.cs\">", 2);
				p("<AutoGen>True</AutoGen>", 3);
				p("<DependentUpon>Settings.settings</DependentUpon>", 3);
				p("<DesignTimeSharedInput>True</DesignTimeSharedInput>", 3);
			p("</Compile>", 2);
			p("<EmbeddedResource Include=\"Properties\\Resources.resx\">", 2);
				p("<Generator>ResXFileCodeGenerator</Generator>", 3);
				p("<LastGenOutput>Resources.Designer.cs</LastGenOutput>", 3);
			p("</EmbeddedResource>", 2);
			p("<None Include=\"Properties\\Settings.settings\">", 2);
				p("<Generator>SettingsSingleFileGenerator</Generator>", 3);
				p("<LastGenOutput>Settings.Designer.cs</LastGenOutput>", 3);
			p("</None>", 2);
			p("<AppDesigner Include=\"Properties\\\" />", 2);
		p("</ItemGroup>", 1);
		p("<Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />", 1);
	p("</Project>");
	closeFile();
}