Example #1
0
Texture::Texture(std::string path, Renderer& renderer)
{

    sp_logger->info("Loading texture from path '{}'", path);

    SDL_Surface* surface = IMG_Load(path.c_str());
    if (surface == nullptr)
    {
        sdl_throw_error(std::string("IMG_Load"));
    }

    SDL_Texture* texture =
        SDL_CreateTextureFromSurface(renderer.get_pointer(), surface);
    if (texture == nullptr)
    {
        sdl_throw_error(std::string("SDL_CreateTextureFromSurface"));
    }

    m_width = surface->w;
    m_height = surface->h;

    SDL_FreeSurface(surface);

    m_p_texture = texture;
}
Example #2
0
void sdl_init(uint32_t sdl_flags, int img_flags)
{
    sp_logger = common::logging_get_logger("sdlwrap");

    sp_logger->info("Initializing SDL");
    auto result = SDL_Init(sdl_flags);
    if (result){
        sdl_throw_error("SDL_Init");
    }

    sp_logger->info("Initializing SDL image");
    result = IMG_Init(img_flags);
    if (result != img_flags){
        sdl_img_throw_error("IMG_Init");
    }
}
Example #3
0
TEST(inst_suite, MOV_with_bracket)
{
     // Found MOV_with_bracket
     nask_utility::Instructions inst;

     std::istringstream input_stream0("[BITS 32]            \r\n");
     std::istringstream input_stream1("[INSTRSET \"i486p\"] \r\n");
     std::istringstream input_stream2("ECX,[ESP+4]          \r\n");
     std::istringstream input_stream3("AL,[ESP+8]           \r\n");
     TParaTokenizer tokenizer0(input_stream0, &inst.token_table);
     TParaTokenizer tokenizer1(input_stream1, &inst.token_table);
     TParaTokenizer tokenizer2(input_stream2, &inst.token_table);
     TParaTokenizer tokenizer3(input_stream3, &inst.token_table);

     std::vector<uint8_t> test;
     std::vector<uint8_t> answer = { 0x8b, 0x4c, 0x24, 0x04, 0x8a, 0x44, 0x24, 0x08 };

     inst.process_token_BRACKET(tokenizer0, test);
     inst.process_token_BRACKET(tokenizer1, test);
     inst.process_token_MOV(tokenizer2, test);
     inst.process_token_MOV(tokenizer3, test);

     logger->info("output bin: {}", nask_utility::string_to_hex(std::string(test.begin(), test.end())));

     // static member data "support" causes memory leak :<
     EXPECT_N_LEAKS(12);
     CHECK(test == answer);
}
Example #4
0
bool SpriteSheet::WriteTextureAtlas(const std::string& file_name)
{
	if (sub_textures_.size() > 0) {
		double pixel_width=1.0/sheet_width_;
		double pixel_height=1.0/sheet_height_;

		std::string data="tx0,ty0, tx1,ty1, tx2,ty2, tx3,ty3, x0,y0, x1,y1, x2,y2, x3,y3\n";
		for (auto sub_texture : sub_textures_) {
			data += fmt::sprintf ( "%0.8f,%0.8f, %0.8f,%0.8f, %0.8f,%0.8f, %0.8f,%0.8f,  %0.8f,%0.8f, %0.8f,%0.8f, %0.8f,%0.8f, %0.8f,%0.8f\n",
			sub_texture.left * pixel_width, sub_texture.bottom * pixel_height,
			sub_texture.right * pixel_width, sub_texture.bottom * pixel_height,
			sub_texture.left * pixel_width, sub_texture.top * pixel_height,
			sub_texture.right * pixel_width, sub_texture.top * pixel_height,

			sub_texture.offset_x, sub_texture.offset_y,
			sub_texture.offset_x + sub_texture.width, sub_texture.offset_y,
			sub_texture.offset_x, sub_texture.offset_y + sub_texture.height,
			sub_texture.offset_x + sub_texture.width, sub_texture.offset_y + sub_texture.height );
		}

		if (mi::file::Write(file_name, data)) {
			logger->info("Wrote texture atlas file: {}",file_name);
			return (true);
		}
	} else {
		logger->error("WriteTextureAtlas(), no data for texture atlas file");
	}
	return false;
}
Example #5
0
int slaves::tcp_server::load_config( const libconfig::Setting& settings,
                                    const std::shared_ptr<::spdlog::logger>& l,
                                    bool to_file)
{
    const libconfig::Setting& robot_server = settings["TCPServer"];
    robot_server.lookupValue("Address", address);
    uint32_t tmp=port;
    robot_server.lookupValue("Port",tmp);
        if(tmp==0)
        {
            if(to_file)
            {
                l->warn("<{}> port number must not be zero.",tag);
                return CHILD_NEED_WORK;
            }
            else
            {
                std::cerr<<tag<<" port number must not be zero."<<std::endl;
                return -1;
            }
        }
        else if(tmp>65535)
        {
            if(to_file)
            {
                l->warn("<{}> {} port number must be less than 65535.",tag);
                return CHILD_NEED_WORK;
            }
            else
            {
                std::cerr<<tag<<" port number must be less than 65535."<<std::endl;
                return -1;
            }
        }
        port=tmp;
        if(to_file)
        {
            l->info("<{}> TCP Server address: {}",tag, address);
            l->info("<{}> TCP Server port: {}",tag, port);
        }
        else
        {
            std::cout<<tag<<" TCP Server address: "<<address<<std::endl;
            std::cout<<tag<<" TCP Server port: "<<port<<std::endl;
        }
    return 0;
}
Example #6
0
void bench_logger(benchmark::State &state, std::shared_ptr<spdlog::logger> logger)
{
    int i = 0;
    for (auto _ : state)
    {
        logger->info("Hello logger: msg number {}...............", ++i);
    }
}
Example #7
0
    void Initialise()
    {
        logger = spdlog::get("logger");
        logger->info("Hooking Crypt functions");

        ModuleScan APBScan("APB.exe");

        Util::HookLibraryFunction(detCryptGenKey, "Advapi32.dll", "CryptGenKey", &hkCryptGenKey);
        Util::HookLibraryFunction(detCryptImportKey, "Advapi32.dll", "CryptImportKey", &hkCryptImportKey);
        Util::HookLibraryFunction(detCryptEncrypt, "Advapi32.dll", "CryptEncrypt", &hkCryptEncrypt);
        Util::HookLibraryFunction(detCryptDecrypt, "Advapi32.dll", "CryptDecrypt", &hkCryptDecrypt);
        Util::HookLibraryFunction(detRC4SetKey, "LIBEAY32.dll", "RC4_set_key", &hkRC4SetKey);
        Util::HookLibraryFunction(detSHA1Update, "LIBEAY32.dll", "SHA1_Update", &hkSHA1Update);
        Util::HookSignatureFunction(detXXTEADecrypt, APBScan, "\x55\x8B\xEC\x83\xEC\x08\x8B\x55\x14\x56", "xxxxxxxxxx", &hkXXTEADecrypt);

        logger->info("Crypt functions hooked");
    }
Example #8
0
    void DisableAntiDebug()
    {
        logger = spdlog::get("logger");

        Util::HookLibraryFunction(detNtSIT, "ntdll.dll", "NtSetInformationThread", &hkNtSetInformationThread);
        Util::HookLibraryFunction(detNtQIP, "ntdll.dll", "NtQueryInformationProcess", &hkNtQueryInformationProcess);

        logger->info("Anti-debug APIs hooked successfully");
    }
Example #9
0
Renderer::Renderer(Window& window, int index, Uint32 flags)
{
    sp_logger->info("Constructing renderer");

    m_p_renderer = SDL_CreateRenderer(window.get_pointer(), index, flags);
    if (m_p_renderer == nullptr)
    {
        sdl_throw_error(std::string("SDL_CreateRenderer"));
    }
}
Example #10
0
 // VFALCO TODO This should return boost::optional<uint256>
 LedgerHash getLedgerHash(
     std::shared_ptr<ReadView const>& ledger,
     LedgerIndex index)
 {
     boost::optional<LedgerHash> hash;
     try
     {
         hash = hashOfSeq(*ledger, index, j_);
     }
     catch (SHAMapMissingNode &)
     {
         JLOG (j_.warn()) <<
             "Node missing from ledger " << ledger->info().seq;
         app_.getInboundLedgers().acquire (
             ledger->info().hash, ledger->info().seq,
             InboundLedger::fcGENERIC);
     }
     return hash ? *hash : zero; // kludge
 }
Example #11
0
bool SpriteSheet::SetImage(const std::string& file_name)
{
	image_data_.clear();
  if (lodepng::decode(image_data_, image_width_, image_height_, file_name)==0) {
		logger->info("Loaded image {}",file_name);
	} else  {
		logger->error("lodepng::decode() failed for {}",file_name);
		return false;
	}
	return true;
}
Example #12
0
Window::~Window()
{
    sp_logger->info("Destroying window");

    if (m_p_window != nullptr)
    {
        SDL_DestroyWindow(m_p_window);
    }else{
        sp_logger->error("Window pointer is null!");
    }
}
Example #13
0
extern "C" void logger_init_file_output(const char * path) {
    if(spdlogger.get() != nullptr)
        return;
    
    char filepath[512] = { 0 };
    strcpy(filepath, path);
    
    spdlogger = spdlog::rotating_logger_mt("file_logger", filepath, 1024 * 1024 * 10, 3);
    if (spdlogger.get() != nullptr)
        spdlogger->info("ok");
}
Example #14
0
Renderer::~Renderer()
{
    sp_logger->info("Destroying renderer");

    if (m_p_renderer == nullptr)
    {
        SDL_DestroyRenderer(m_p_renderer);
    }else{
        sp_logger->error("Renderer pointer is null!");
    }
}
Example #15
0
    virtual
    dynamic_t::object_t
    info(app_t::info_policy_t policy) const {
        dynamic_t::object_t info;

        if (policy == app_t::info_policy_t::verbose) {
            info = overseer->info();
        }

        info["state"] = "running";
        return info;
    }
Example #16
0
Window::Window(
    const std::string title, int x, int y, int w, int h, Uint32 flags)
{
    sp_logger->info("Constructing window '{}'", title);

    m_p_window = SDL_CreateWindow(title.c_str(), x, y, w, h, flags);

    if (m_p_window == nullptr)
    {
        sdl_throw_error("SDL_CreateWindow: ");
    }
}
Example #17
0
void bench_c_string(benchmark::State &state, std::shared_ptr<spdlog::logger> logger)
{
    const char *msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra metus cursus "
                      "lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus volutpat mi, eu consequat sem "
                      "libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam non dapibus eros. Donec fringilla dui sed "
                      "augue pretium, nec scelerisque est maximus. Nullam convallis, sem nec blandit maximus, nisi turpis ornare "
                      "nisl, sit amet volutpat neque massa eu odio. Maecenas malesuada quam ex, posuere congue nibh turpis duis.";

    for (auto _ : state)
    {
        logger->info(msg);
    }
}
Example #18
0
    NTSTATUS NTAPI hkNtSetInformationThread(
        __in HANDLE ThreadHandle,
        __in THREAD_INFORMATION_CLASS ThreadInformationClass,
        __in PVOID ThreadInformation,
        __in ULONG ThreadInformationLength)
    {
        // TODO: Check handle is valid and is for a valid thread in this process
        // TODO: Maybe need to hook NtQueryInformationThread in case the process actually checks that ThreadHideFromDebugger is set

        if (ThreadInformationClass == 17 && ThreadInformation == nullptr && ThreadInformationLength == 0) // ThreadHideFromDebugger
        {
            logger->info("NtSetInformationThread called with ThreadHideFromDebugger (Thread ID = %d)\n", GetCurrentThreadId());
            return STATUS_SUCCESS;
        }

        return detNtSIT.GetOriginal<decltype(&hkNtSetInformationThread)>()(ThreadHandle, ThreadInformationClass, ThreadInformation, ThreadInformationLength);
    }
Example #19
0
void bench(int howmany, std::shared_ptr<spdlog::logger> log)
{
    using namespace std::chrono;
    using chrono::high_resolution_clock;
    using chrono::milliseconds;
    using chrono::nanoseconds;

    cout << log->name() << "...\t\t" << flush;
    nanoseconds total_nanos = nanoseconds::zero();
    for (auto i = 0; i < howmany; ++i)
    {
        auto start = high_resolution_clock::now();
        log->info("Hello logger: msg number {}", i);
        auto delta_nanos = chrono::duration_cast<nanoseconds>(high_resolution_clock::now() - start);
        total_nanos += delta_nanos;
    }

    auto avg = total_nanos.count() / howmany;
    cout << format(avg) << " ns/call" << endl;
}
Example #20
0
// The previous version of the lookupLedger command would accept the
// "ledger_index" argument as a string and silently treat it as a request to
// return the current ledger which, while not strictly wrong, could cause a lot
// of confusion.
//
// The code now robustly validates the input and ensures that the only possible
// values for the "ledger_index" parameter are the index of a ledger passed as
// an integer or one of the strings "current", "closed" or "validated".
// Additionally, the code ensures that the value passed in "ledger_hash" is a
// string and a valid hash. Invalid values will return an appropriate error
// code.
//
// In the absence of the "ledger_hash" or "ledger_index" parameters, the code
// assumes that "ledger_index" has the value "current".
//
// Returns a Json::objectValue.  If there was an error, it will be in that
// return value.  Otherwise, the object contains the field "validated" and
// optionally the fields "ledger_hash", "ledger_index" and
// "ledger_current_index", if they are defined.
Status lookupLedger (
    std::shared_ptr<ReadView const>& ledger, Context& context,
    Json::Value& result)
{
    if (auto status = ledgerFromRequest (ledger, context))
        return status;

    auto& info = ledger->info();

    if (!info.open)
    {
        result[jss::ledger_hash] = to_string (info.hash);
        result[jss::ledger_index] = info.seq;
    }
    else
    {
        result[jss::ledger_current_index] = info.seq;
    }

    result[jss::validated] = isValidated (context.ledgerMaster, *ledger, context.app);
    return Status::OK;
}
Example #21
0
    BOOL WINAPI hkCryptGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY* phKey)
    {
        // Ensure we can export the private key
        dwFlags |= CRYPT_ARCHIVABLE | CRYPT_EXPORTABLE;
        BOOL result = detCryptGenKey.GetOriginal<decltype(&hkCryptGenKey)>()(hProv, Algid, dwFlags, phKey);
        if (Algid != AT_KEYEXCHANGE || !result)
        {
            return result;
        }

        logger->info("CryptGenKey:");
        logger->info("    handle = 0x{:X}", *phKey);

        // Export private key
        BYTE keyData[2048];
        DWORD keyLength = 2048;
        if (!CryptExportKey(*phKey, 0, PRIVATEKEYBLOB, 0, keyData, &keyLength))
        {
            logger->error("    CryptExportKey for PRIVATEKEYBLOB failed (Error = {})", GetLastError());
        }
        else
        {
            logger->info("    privKeyLength = {}", keyLength);
            logger->info("    privKey = {}", Util::DataToHex((const char*)keyData, keyLength));
        }

        // Export public key
        keyLength = 2048;
        if (!CryptExportKey(*phKey, 0, PUBLICKEYBLOB, 0, keyData, &keyLength))
        {
            logger->error("    CryptExportKey for PUBLICKEYBLOB failed (Error = {})", GetLastError());
        }
        else
        {
            logger->info("    pubKeyLength = {}", keyLength);
            logger->info("    pubKey = {}", Util::DataToHex((const char*)keyData, keyLength));
        }
        
        return result;
    }
Example #22
0
void processReadsSingle(single_parser* parser,
        RapMapIndex& rmi,
	CollectorT& hitCollector,
        MutexT* iomutex,
	std::shared_ptr<spdlog::logger> outQueue,
        HitCounters& hctr,
        uint32_t maxNumHits,
        bool noOutput) {

    auto& txpNames = rmi.txpNames;
    auto& txpLens = rmi.txpLens;
    uint32_t n{0};
    uint32_t k = rapmap::utils::my_mer::k();
    std::vector<std::string> transcriptNames;
    constexpr char bases[] = {'A', 'C', 'G', 'T'};

    fmt::MemoryWriter sstream;
    size_t batchSize{1000};
    std::vector<QuasiAlignment> hits;

    SingleAlignmentFormatter<RapMapIndex*> formatter(&rmi);

    size_t readLen{0};

    while(true) {
        typename single_parser::job j(*parser); // Get a job from the parser: a bunch of read (at most max_read_group)
        if(j.is_empty()) break;           // If got nothing, quit
        for(size_t i = 0; i < j->nb_filled; ++i) { // For each sequence
            readLen = j->data[i].seq.length();
            ++hctr.numReads;
            hits.clear();
            hitCollector(j->data[i].seq, hits, MateStatus::SINGLE_END);
            /*
               std::set_intersection(leftHits.begin(), leftHits.end(),
               rightHits.begin(), rightHits.end(),
               std::back_inserter(jointHits));
               */
            auto numHits = hits.size();
            hctr.totHits += numHits;

             if (hits.size() > 0 and !noOutput and hits.size() <= maxNumHits) {
                rapmap::utils::writeAlignmentsToStream(j->data[i], formatter,
                        hctr, hits, sstream);
            }

            if (hctr.numReads > hctr.lastPrint + 1000000) {
		hctr.lastPrint.store(hctr.numReads.load());
                if (iomutex->try_lock()){
                    if (hctr.numReads > 0) {
#if defined(__DEBUG__) || defined(__TRACK_CORRECT__)
                        std::cerr << "\033[F\033[F\033[F";
#else
                        std::cerr << "\033[F\033[F";
#endif // __DEBUG__
                    }
                    std::cerr << "saw " << hctr.numReads << " reads\n";
                    std::cerr << "# hits per read = "
                        << hctr.totHits / static_cast<float>(hctr.numReads) << "\n";
#if defined(__DEBUG__) || defined(__TRACK_CORRECT__)
                    std::cerr << "The true hit was in the returned set of hits "
                        << 100.0 * (hctr.trueHits / static_cast<float>(hctr.numReads))
                        <<  "% of the time\n";
#endif // __DEBUG__
                    iomutex->unlock();
                }
            }
        } // for all reads in this job

	if (!noOutput) {
        std::string outStr(sstream.str());
        // Get rid of last newline
        if (!outStr.empty()) {
            outStr.pop_back();
            outQueue->info() << std::move(outStr);
        }
	    sstream.clear();
	}
	/*
        // DUMP OUTPUT
        iomutex->lock();
        outStream << sstream.str();
        iomutex->unlock();
        sstream.clear();
	*/

    } // processed all reads
}
Example #23
0
void
FeeVoteImpl::doVoting(
    std::shared_ptr<ReadView const> const& lastClosedLedger,
        ValidationSet const& set,
            std::shared_ptr<SHAMap> const& initialPosition)
{
    // LCL must be flag ledger
    assert ((lastClosedLedger->info().seq % 256) == 0);

    detail::VotableInteger<std::uint64_t> baseFeeVote (
        lastClosedLedger->fees().base, target_.reference_fee);

    detail::VotableInteger<std::uint32_t> baseReserveVote (
        lastClosedLedger->fees().accountReserve(0).drops(), target_.account_reserve);

    detail::VotableInteger<std::uint32_t> incReserveVote (
        lastClosedLedger->fees().increment, target_.owner_reserve);

    for (auto const& e : set)
    {
        STValidation const& val = *e.second;

        if (val.isTrusted ())
        {
            if (val.isFieldPresent (sfBaseFee))
            {
                baseFeeVote.addVote (val.getFieldU64 (sfBaseFee));
            }
            else
            {
                baseFeeVote.noVote ();
            }

            if (val.isFieldPresent (sfReserveBase))
            {
                baseReserveVote.addVote (val.getFieldU32 (sfReserveBase));
            }
            else
            {
                baseReserveVote.noVote ();
            }

            if (val.isFieldPresent (sfReserveIncrement))
            {
                incReserveVote.addVote (val.getFieldU32 (sfReserveIncrement));
            }
            else
            {
                incReserveVote.noVote ();
            }
        }
    }

    // choose our positions
    std::uint64_t const baseFee = baseFeeVote.getVotes ();
    std::uint32_t const baseReserve = baseReserveVote.getVotes ();
    std::uint32_t const incReserve = incReserveVote.getVotes ();
    std::uint32_t const feeUnits = target_.reference_fee_units;
    auto const seq = lastClosedLedger->info().seq + 1;

    // add transactions to our position
    if ((baseFee != lastClosedLedger->fees().base) ||
            (baseReserve != lastClosedLedger->fees().accountReserve(0)) ||
            (incReserve != lastClosedLedger->fees().increment))
    {
        if (journal_.warning) journal_.warning <<
            "We are voting for a fee change: " << baseFee <<
            "/" << baseReserve <<
            "/" << incReserve;

        STTx feeTx (ttFEE,
            [seq,baseFee,baseReserve,incReserve,feeUnits](auto& obj)
            {
                obj[sfAccount] = AccountID();
                obj[sfLedgerSequence] = seq;
                obj[sfBaseFee] = baseFee;
                obj[sfReserveBase] = baseReserve;
                obj[sfReserveIncrement] = incReserve;
                obj[sfReferenceFeeUnits] = feeUnits;
            });

        uint256 txID = feeTx.getTransactionID ();

        if (journal_.warning)
            journal_.warning << "Vote: " << txID;

        Serializer s;
        feeTx.add (s);

        auto tItem = std::make_shared<SHAMapItem> (txID, s.peekData ());

        if (!initialPosition->addGiveItem (tItem, true, false))
        {
            if (journal_.warning) journal_.warning <<
                "Ledger already had fee change";
        }
    }
}
Example #24
0
void handle_request(
    std::string request_line, SocketCache& pushers,
    std::vector<Address>& routing_addresses,
    std::unordered_map<Key, std::unordered_set<Address>>& key_address_cache,
    unsigned& seed, std::shared_ptr<spdlog::logger> logger, UserThread& ut,
    zmq::socket_t& response_puller, zmq::socket_t& key_address_puller,
    Address& ip, unsigned& thread_id, unsigned& rid, unsigned& trial) {
  std::vector<std::string> v;
  split(request_line, ' ', v);
  Key key;
  std::string value;

  if (!((v.size() == 2 && v[0] == "GET") || (v.size() == 3 && v[0] == "PUT"))) {
    std::cerr << "Usage: GET <key> | PUT <key> <value>" << std::endl;
    return;
  } else {
    if (v[0] == "GET") {
      key = v[1];
      value = "";
    } else {
      key = v[1];
      value = v[2];
    }
  }

  if (trial > 5) {
    logger->info("Trial #{} for request for key {}.", trial, key);
    logger->info("Waiting 5 seconds.");
    std::chrono::seconds dura(5);
    std::this_thread::sleep_for(dura);
    logger->info("Waited 5s.");
  }

  // get worker address
  Address worker_address;
  if (key_address_cache.find(key) == key_address_cache.end()) {
    // query the routing and update the cache
    Address target_routing_address =
        kHashRingUtil
            ->get_random_routing_thread(routing_addresses, seed,
                                        kRoutingThreadCount)
            .get_key_address_connect_addr();
    bool succeed;
    std::vector<Address> addresses = kHashRingUtil->get_address_from_routing(
        ut, key, pushers[target_routing_address], key_address_puller, succeed,
        ip, thread_id, rid);

    if (succeed) {
      for (const std::string& address : addresses) {
        key_address_cache[key].insert(address);
      }
      worker_address = addresses[rand_r(&seed) % addresses.size()];
    } else {
      logger->error(
          "Request timed out when querying routing. This should never happen!");
      return;
    }
  } else {
    if (key_address_cache[key].size() == 0) {
      logger->error("Address cache for key " + key + " has size 0.");
      return;
    }

    worker_address = *(next(begin(key_address_cache[key]),
                            rand_r(&seed) % key_address_cache[key].size()));
  }

  KeyRequest req;
  req.set_response_address(ut.get_request_pulling_connect_addr());

  std::string req_id =
      ip + ":" + std::to_string(thread_id) + "_" + std::to_string(rid);
  req.set_request_id(req_id);
  rid += 1;

  KeyTuple* tp = req.add_tuples();
  tp->set_key(key);
  tp->set_address_cache_size(key_address_cache[key].size());

  if (value == "") {
    // get request
    req.set_type(get_request_type("GET"));
  } else {
    // put request
    req.set_type(get_request_type("PUT"));
    tp->set_value(value);
    tp->set_timestamp(0);
  }

  bool succeed;
  auto res = send_request<KeyRequest, KeyResponse>(req, pushers[worker_address],
                                                   response_puller, succeed);

  if (succeed) {
    KeyTuple tuple = res.tuples(0);

    // initialize the respond string
    if (tuple.error() == 2) {
      trial += 1;
      if (trial > 5) {
        for (const auto& address : res.tuples(0).addresses()) {
          logger->info("Server's return address for key {} is {}.", key,
                       address);
        }

        for (const std::string& address : key_address_cache[key]) {
          logger->info("My cached address for key {} is {}", key, address);
        }
      }

      // update cache and retry
      key_address_cache.erase(key);
      handle_request(request_line, pushers, routing_addresses,
                     key_address_cache, seed, logger, ut, response_puller,
                     key_address_puller, ip, thread_id, rid, trial);
    } else {
      // succeeded
      if (tuple.has_invalidate() && tuple.invalidate()) {
        // update cache
        key_address_cache.erase(key);
      }
      if (value == "" && tuple.error() == 0) {
        std::cout << "value of key " + tuple.key() + " is " + tuple.value() +
                         "\n";
      } else if (value == "" && tuple.error() == 1) {
        std::cout << "key " + tuple.key() + " does not exist\n";
      } else if (value != "") {
        std::cout << "successfully put key " + tuple.key() + "\n";
      }
    }
  } else {
    logger->info(
        "Request timed out when querying worker: clearing cache due to "
        "possible node membership changes.");
    // likely the node has departed. We clear the entries relavant to the
    // worker_address
    std::vector<std::string> tokens;
    split(worker_address, ':', tokens);
    std::string signature = tokens[1];
    std::unordered_set<Key> remove_set;

    for (const auto& key_pair : key_address_cache) {
      for (const std::string& address : key_pair.second) {
        std::vector<std::string> v;
        split(address, ':', v);

        if (v[1] == signature) {
          remove_set.insert(key_pair.first);
        }
      }
    }

    for (const std::string& key : remove_set) {
      key_address_cache.erase(key);
    }

    trial += 1;
    handle_request(request_line, pushers, routing_addresses, key_address_cache,
                   seed, logger, ut, response_puller, key_address_puller, ip,
                   thread_id, rid, trial);
  }
}
Example #25
0
void terrama2::services::view::core::makeView(ViewId viewId, std::shared_ptr< terrama2::services::view::core::ViewLogger > logger, std::weak_ptr<DataManager> weakDataManager)
{
  auto dataManager = weakDataManager.lock();
  if(!dataManager.get())
  {
    TERRAMA2_LOG_ERROR() << QObject::tr("Unable to access DataManager");
    return;
  }

  try
  {
    RegisterId logId = 0;
    if(logger.get())
      logId = logger->start(viewId);

    TERRAMA2_LOG_DEBUG() << QObject::tr("Starting view %1 generation.").arg(viewId);

    auto lock = dataManager->getLock();

    auto viewPtr = dataManager->findView(viewId);

    if(viewPtr->dataSeriesList.size() != viewPtr->filtersPerDataSeries.size())
    {
      QString message = QObject::tr("View %1 do not have the right number of filters for data.").arg(viewId);
      if(logger.get())
        logger->error(message.toStdString(), viewId);
      TERRAMA2_LOG_ERROR() << message;
      throw Exception() << ErrorDescription(message);
    }

    std::vector<std::unordered_map<terrama2::core::DataSetPtr, terrama2::core::DataSetSeries>> seriesList;

    for(auto dataSeriesId : viewPtr->dataSeriesList)
    {
      terrama2::core::DataSeriesPtr inputDataSeries = dataManager->findDataSeries(dataSeriesId);
      terrama2::core::DataProviderPtr inputDataProvider = dataManager->findDataProvider(inputDataSeries->dataProviderId);

      auto dataAccessor = terrama2::core::DataAccessorFactory::getInstance().make(inputDataProvider, inputDataSeries);

      terrama2::core::Filter filter(viewPtr->filtersPerDataSeries.at(dataSeriesId));
      std::unordered_map<terrama2::core::DataSetPtr, terrama2::core::DataSetSeries > series = dataAccessor->getSeries(filter);

      seriesList.push_back(series);
    }

    lock.unlock();

    if(seriesList.size() > 0)
    {
      drawSeriesList(viewId, logger, seriesList, viewPtr->resolutionWidth, viewPtr->resolutionHeight, viewPtr->srid);

      TERRAMA2_LOG_INFO() << QObject::tr("View %1 generated successfully.").arg(viewId);
    }
    else
    {
      QString message = QObject::tr("View %1 has no associated data to be generated.").arg(viewId);
      if(logger.get())
        logger->info(message.toStdString(), viewId);
      TERRAMA2_LOG_INFO() << message;
    }

    if(logger.get())
      logger->done(terrama2::core::TimeUtils::nowUTC(), logId);
  }
  catch(const terrama2::Exception& e)
  {
    TERRAMA2_LOG_ERROR() << boost::get_error_info<terrama2::ErrorDescription>(e) << std::endl;
    TERRAMA2_LOG_INFO() << QObject::tr("Build of view %1 finished with error(s).").arg(viewId);
  }
  catch(const boost::exception& e)
  {
    TERRAMA2_LOG_ERROR() << boost::get_error_info<terrama2::ErrorDescription>(e);
    TERRAMA2_LOG_INFO() << QObject::tr("Build of view %1 finished with error(s).").arg(viewId);
  }
  catch(const std::exception& e)
  {
    TERRAMA2_LOG_ERROR() << e.what();
    TERRAMA2_LOG_INFO() << QObject::tr("Build of view %1 finished with error(s).").arg(viewId);
  }
  catch(...)
  {
    TERRAMA2_LOG_ERROR() << QObject::tr("Unkown error.");
    TERRAMA2_LOG_INFO() << QObject::tr("Build of view %1 finished with error(s).").arg(viewId);
  }
}
Example #26
0
void processReadsPair(paired_parser* parser,
        RapMapIndex& rmi,
	CollectorT& hitCollector,
        MutexT* iomutex,
	std::shared_ptr<spdlog::logger> outQueue,
        HitCounters& hctr,
        uint32_t maxNumHits,
        bool noOutput) {
    auto& txpNames = rmi.txpNames;
    std::vector<uint32_t>& txpLens = rmi.txpLens;
    uint32_t n{0};
    uint32_t k = rapmap::utils::my_mer::k();
    std::vector<std::string> transcriptNames;
    constexpr char bases[] = {'A', 'C', 'G', 'T'};

    auto logger = spdlog::get("stderrLog");

    fmt::MemoryWriter sstream;
    size_t batchSize{1000};
    std::vector<QuasiAlignment> leftHits;
    std::vector<QuasiAlignment> rightHits;
    std::vector<QuasiAlignment> jointHits;

    PairAlignmentFormatter<RapMapIndex*> formatter(&rmi);

    size_t readLen{0};
	bool tooManyHits{false};

    JumpStats js;
    // 0 means properly aligned
    // 0x1 means only alignments for left read
    // 0x2 means only alignments for right read
    // 0x3 means "orphaned" alignments for left and right
    // (currently not treated as orphan).
    uint32_t orphanStatus{0};
    while(true) {
        typename paired_parser::job j(*parser); // Get a job from the parser: a bunch of read (at most max_read_group)
        if(j.is_empty()) break;           // If got nothing, quit
        for(size_t i = 0; i < j->nb_filled; ++i) { // For each sequence
	    tooManyHits = false;
            readLen = j->data[i].first.seq.length();
            ++hctr.numReads;
            jointHits.clear();
            leftHits.clear();
            rightHits.clear();
    	    hitCollector(j->data[i].first.seq,
                        leftHits, MateStatus::PAIRED_END_LEFT);
            hitCollector(j->data[i].second.seq,
                        rightHits, MateStatus::PAIRED_END_RIGHT);

            rapmap::utils::mergeLeftRightHits(
                    leftHits, rightHits, jointHits,
                    readLen, maxNumHits, tooManyHits, hctr);


            if (jointHits.size() > 0 and !noOutput and jointHits.size() <= maxNumHits) {
                rapmap::utils::writeAlignmentsToStream(j->data[i], formatter,
                                                       hctr, jointHits, sstream);
            }

            if (hctr.numReads > hctr.lastPrint + 1000000) {
		hctr.lastPrint.store(hctr.numReads.load());
                if (iomutex->try_lock()) {
                    if (hctr.numReads > 0) {
#if defined(__DEBUG__) || defined(__TRACK_CORRECT__)
                        std::cerr << "\033[F\033[F\033[F\033[F";
#else
                        std::cerr << "\033[F\033[F\033[F";
#endif // __DEBUG__
                    }
                    std::cerr << "saw " << hctr.numReads << " reads\n";
                    std::cerr << "# pe hits per read = "
                        << hctr.peHits / static_cast<float>(hctr.numReads) << "\n";
                    std::cerr << "# se hits per read = "
                        << hctr.seHits / static_cast<float>(hctr.numReads) << "\n";
#if defined(__DEBUG__) || defined(__TRACK_CORRECT__)
                    std::cerr << "The true hit was in the returned set of hits "
                        << 100.0 * (hctr.trueHits / static_cast<float>(hctr.numReads))
                        <<  "% of the time\n";
		    /*
                    std::cerr << "Average jump size = "
                              << js.jumpSizes / static_cast<double>(js.numJumps) << "\n";
			      */
#endif // __DEBUG__
                    iomutex->unlock();
                }
            }
        } // for all reads in this job

	if (!noOutput) {
        std::string outStr(sstream.str());
        // Get rid of last newline
        if (!outStr.empty()){
            outStr.pop_back();
            outQueue->info() << std::move(outStr);
        }
	    sstream.clear();
	}

        // DUMP OUTPUT
	/*
        if (!noOutput) {
            iomutex->lock();
            outStream << sstream.str();
            iomutex->unlock();
            sstream.clear();
        }
	*/

    } // processed all reads

}
Example #27
0
static bool saveValidatedLedger (
    Application& app,
    std::shared_ptr<Ledger const> const& ledger,
    bool current)
{
    auto j = app.journal ("Ledger");

    if (! app.pendingSaves().startWork (ledger->info().seq))
    {
        // The save was completed synchronously
        JLOG (j.debug()) << "Save aborted";
        return true;
    }

    // TODO(tom): Fix this hard-coded SQL!
    JLOG (j.trace())
        << "saveValidatedLedger "
        << (current ? "" : "fromAcquire ") << ledger->info().seq;
    static boost::format deleteLedger (
        "DELETE FROM Ledgers WHERE LedgerSeq = %u;");
    static boost::format deleteTrans1 (
        "DELETE FROM Transactions WHERE LedgerSeq = %u;");
    static boost::format deleteTrans2 (
        "DELETE FROM AccountTransactions WHERE LedgerSeq = %u;");
    static boost::format deleteAcctTrans (
        "DELETE FROM AccountTransactions WHERE TransID = '%s';");

    auto seq = ledger->info().seq;

    if (! ledger->info().accountHash.isNonZero ())
    {
        JLOG (j.fatal()) << "AH is zero: "
                                   << getJson (*ledger);
        assert (false);
    }

    if (ledger->info().accountHash != ledger->stateMap().getHash ().as_uint256())
    {
        JLOG (j.fatal()) << "sAL: " << ledger->info().accountHash
                                   << " != " << ledger->stateMap().getHash ();
        JLOG (j.fatal()) << "saveAcceptedLedger: seq="
                                   << seq << ", current=" << current;
        assert (false);
    }

    assert (ledger->info().txHash == ledger->txMap().getHash ().as_uint256());

    // Save the ledger header in the hashed object store
    {
        Serializer s (128);
        s.add32 (HashPrefix::ledgerMaster);
        addRaw(ledger->info(), s);
        app.getNodeStore ().store (
            hotLEDGER, std::move (s.modData ()), ledger->info().hash);
    }


    AcceptedLedger::pointer aLedger;
    try
    {
        aLedger = app.getAcceptedLedgerCache().fetch (ledger->info().hash);
        if (! aLedger)
        {
            aLedger = std::make_shared<AcceptedLedger>(ledger, app.accountIDCache(), app.logs());
            app.getAcceptedLedgerCache().canonicalize(ledger->info().hash, aLedger);
        }
    }
    catch (std::exception const&)
    {
        JLOG (j.warn()) << "An accepted ledger was missing nodes";
        app.getLedgerMaster().failedSave(seq, ledger->info().hash);
        // Clients can now trust the database for information about this
        // ledger sequence.
        app.pendingSaves().finishWork(seq);
        return false;
    }

    {
        auto db = app.getLedgerDB ().checkoutDb();
        *db << boost::str (deleteLedger % seq);
    }

    {
        auto db = app.getTxnDB ().checkoutDb ();

        soci::transaction tr(*db);

        *db << boost::str (deleteTrans1 % seq);
        *db << boost::str (deleteTrans2 % seq);

        std::string const ledgerSeq (std::to_string (seq));

        for (auto const& vt : aLedger->getMap ())
        {
            uint256 transactionID = vt.second->getTransactionID ();

            app.getMasterTransaction ().inLedger (
                transactionID, seq);

            std::string const txnId (to_string (transactionID));
            std::string const txnSeq (std::to_string (vt.second->getTxnSeq ()));

            *db << boost::str (deleteAcctTrans % transactionID);

            auto const& accts = vt.second->getAffected ();

            if (!accts.empty ())
            {
                std::string sql (
                    "INSERT INTO AccountTransactions "
                    "(TransID, Account, LedgerSeq, TxnSeq) VALUES ");

                // Try to make an educated guess on how much space we'll need
                // for our arguments. In argument order we have:
                // 64 + 34 + 10 + 10 = 118 + 10 extra = 128 bytes
                sql.reserve (sql.length () + (accts.size () * 128));

                bool first = true;
                for (auto const& account : accts)
                {
                    if (!first)
                        sql += ", ('";
                    else
                    {
                        sql += "('";
                        first = false;
                    }

                    sql += txnId;
                    sql += "','";
                    sql += app.accountIDCache().toBase58(account);
                    sql += "',";
                    sql += ledgerSeq;
                    sql += ",";
                    sql += txnSeq;
                    sql += ")";
                }
                sql += ";";
                JLOG (j.trace()) << "ActTx: " << sql;
                *db << sql;
            }
            else
            {
                JLOG (j.warn())
                    << "Transaction in ledger " << seq
                    << " affects no accounts";
                JLOG (j.warn())
                    << vt.second->getTxn()->getJson(0);
            }

            *db <<
               (STTx::getMetaSQLInsertReplaceHeader () +
                vt.second->getTxn ()->getMetaSQL (
                    seq, vt.second->getEscMeta ()) + ";");
        }

        tr.commit ();
    }

    {
        static std::string addLedger(
            R"sql(INSERT OR REPLACE INTO Ledgers
                (LedgerHash,LedgerSeq,PrevHash,TotalCoins,ClosingTime,PrevClosingTime,
                CloseTimeRes,CloseFlags,AccountSetHash,TransSetHash)
            VALUES
                (:ledgerHash,:ledgerSeq,:prevHash,:totalCoins,:closingTime,:prevClosingTime,
                :closeTimeRes,:closeFlags,:accountSetHash,:transSetHash);)sql");
        static std::string updateVal(
            R"sql(UPDATE Validations SET LedgerSeq = :ledgerSeq, InitialSeq = :initialSeq
                WHERE LedgerHash = :ledgerHash;)sql");

        auto db (app.getLedgerDB ().checkoutDb ());

        soci::transaction tr(*db);

        auto const hash = to_string (ledger->info().hash);
        auto const parentHash = to_string (ledger->info().parentHash);
        auto const drops = to_string (ledger->info().drops);
        auto const closeTime =
            ledger->info().closeTime.time_since_epoch().count();
        auto const parentCloseTime =
            ledger->info().parentCloseTime.time_since_epoch().count();
        auto const closeTimeResolution =
            ledger->info().closeTimeResolution.count();
        auto const closeFlags = ledger->info().closeFlags;
        auto const accountHash = to_string (ledger->info().accountHash);
        auto const txHash = to_string (ledger->info().txHash);

        *db << addLedger,
            soci::use(hash),
            soci::use(seq),
            soci::use(parentHash),
            soci::use(drops),
            soci::use(closeTime),
            soci::use(parentCloseTime),
            soci::use(closeTimeResolution),
            soci::use(closeFlags),
            soci::use(accountHash),
            soci::use(txHash);


        *db << updateVal,
            soci::use(seq),
            soci::use(seq),
            soci::use(hash);

        tr.commit();
    }
Example #28
0
int main(int argc, char *argv[])
{
    qsrand( QTime(0,0,0).secsTo( QTime::currentTime() ) );

    Logging::Config loggingConfig;
    loggingConfig.setName( "server" );
    loggingConfig.setStdoutLogging( true );
    loggingConfig.setLevel( spdlog::level::info );

    gLogger = loggingConfig.createLogger();

    //
    // Create application and parse arguments.
    //

    QCoreApplication app( argc, argv );
    QCoreApplication::setApplicationName( "thicketserver" );
    QCoreApplication::setApplicationVersion( QString::fromStdString( gServerVersion ) );

    QCommandLineParser parser;
    parser.setApplicationDescription( "Creates a Thicket draft server instance.");
    parser.addHelpOption();
    parser.addVersionOption();

    const QCommandLineOption portOption(
            QStringList() << "p" << "port", "Server port number.  (default: 53333)", "port", "53333" );
    parser.addOption( portOption );
    const QCommandLineOption verboseOption(
            QStringList() << "verbose", "Verbose logging output." );
    parser.addOption( verboseOption );
    const QCommandLineOption logfileOption(
            QStringList() << "logfile", "Write log output to <file>.", "file", "" );
    parser.addOption( logfileOption );
    const QCommandLineOption logRotateOption(
            QStringList() << "logrotate", "Rotate logs.  Requires '--logfile'." );
    parser.addOption( logRotateOption );
    const QCommandLineOption logRotateSizeLimitOption(
            QStringList() << "logrotate-size-limit", "Size limit for rotating log files (default 1000000).", "size-limit", "1000000" );
    parser.addOption( logRotateSizeLimitOption );
    const QCommandLineOption logRotateFileCountOption(
            QStringList() << "logrotate-file-count", "Number of files to rotate (default 2).", "file-count", "2" );
    parser.addOption( logRotateFileCountOption );

    parser.process( app );

    // Parse logging-related options and update the logger first so
    // properly-configured logging is in effect ASAP.
    {
        bool loggerUpdated = false;

        if( parser.isSet( verboseOption ) )
        {
            gLogger->debug( "command-line args: verbose={}", parser.value( verboseOption ) );
            loggingConfig.setLevel( spdlog::level::trace );
            gLogger = loggingConfig.createLogger();
        }

        std::string logfile;
        if( parser.isSet( logfileOption ) )
        {
            QString logfile = parser.value( logfileOption );
            gLogger->debug( "command-line args: logfile={}", logfile );
            if( !logfile.isEmpty() )
            {
                if( parser.isSet( logRotateOption ) )
                {
                    bool convertResult = true;

                    int index = logfile.lastIndexOf( '.' );
                    QString base = (index > 0) ? logfile.left( index ) : logfile;
                    QString ext = (index > 0) ? logfile.mid( index + 1 ) : "";

                    gLogger->debug( "command-line args: logRotateSizeLimit={}",
                            parser.value( logRotateSizeLimitOption ) );
                    unsigned int logRotateSizeLimit =
                            parser.value( logRotateSizeLimitOption ).toUInt( &convertResult );
                    if( !convertResult )
                    {
                        gLogger->critical( "invalid argument" );
                        return ERROR_CODE_USAGE;
                    }

                    gLogger->debug( "command-line args: logRotateFileCount={}",
                            parser.value( logRotateFileCountOption ) );
                    unsigned int logRotateFileCount =
                            parser.value( logRotateFileCountOption ).toUInt( &convertResult );
                    if( !convertResult )
                    {
                        gLogger->critical( "invalid argument" );
                        return ERROR_CODE_USAGE;
                    }

                    loggingConfig.setRotatingFileLogging( base.toStdString(),
                            ext.toStdString(), logRotateSizeLimit, logRotateFileCount );
                }
                else
                {
                    QFile( logfile ).remove();
                    loggingConfig.setSimpleFileLogging( logfile.toStdString() );
                }
                loggerUpdated = true;
            }
        }

        // Modify the logger with logging options.
        if( loggerUpdated )
        {
            gLogger = loggingConfig.createLogger();
        }
    }

    // Parse port option.
    gLogger->debug( "command-line args: port={}", parser.value( portOption ) );
    bool convertResult = true;
    bool argsOk = true;
    unsigned int port = parser.value( portOption ).toUInt( &convertResult );
    argsOk &= convertResult;
    if( !argsOk )
    {
        gLogger->critical( "invalid argument" );
        return ERROR_CODE_USAGE;
    }

    gLogger->info( "Server version {}", gServerVersion );
    gLogger->info( "Server protocol version {}.{}", 
            proto::PROTOCOL_VERSION_MAJOR, proto::PROTOCOL_VERSION_MINOR );

    //
    // Open and parse MtgJSON AllSets data.
    //

    // Open JSON set data file.
    const QDir allSetsDir = QDir::current();
    const std::string allSetsFilePath = allSetsDir.filePath( "AllSets.json" ).toStdString();
    FILE* allSetsDataFile = fopen( allSetsFilePath.c_str(), "r" );
    if( allSetsDataFile == NULL )
    {
        gLogger->critical( "failed to open {}!", allSetsFilePath );
        return ERROR_CODE_NOINPUT;
    }

    //
    // Create the JSON set data instance.
    //

    // Raw non-const pointer is for initial parse, shared pointer to const
    // is used later but ensures cleanup on error.
    auto allSetsData = new MtgJsonAllSetsData();
    auto allSetsDataSharedPtr = std::shared_ptr<const AllSetsData>( allSetsData );
    bool parseResult = allSetsData->parse( allSetsDataFile );
    fclose( allSetsDataFile );
    if( !parseResult )
    {
        gLogger->critical( "Failed to parse AllSets.json!" );
        return ERROR_CODE_DATAERR;
    }

    //
    // Instantiate server settings.
    //
    std::shared_ptr<ServerSettings> serverSettings = std::make_shared<ServerSettings>( &app );

    //
    // Instantiate and initialize client notices.
    //
    std::shared_ptr<ClientNotices> clientNotices = std::make_shared<ClientNotices>( &app );
    if( !clientNotices->readAnnouncementsFromDisk() )
    {
        gLogger->warn( "Unable to read client announcements" );
    }

    //
    // Create and start Server.
    //

    Server* server = new Server( port, serverSettings, allSetsDataSharedPtr, clientNotices, loggingConfig, &app );

    // This will cause the application to exit when the server signals finished.    
    QObject::connect(server, SIGNAL(finished()), &app, SLOT(quit()));

    // This will start the server from the application event loop.
    QTimer::singleShot( 0, server, SLOT(start()) );

    //
    // Create and start the admin shell.
    //

    AdminShell* adminShell = new AdminShell( clientNotices, loggingConfig.createChildConfig( "adminshell" ), &app );

    // This will start the admin shell from the application event loop.
    QTimer::singleShot( 0, adminShell, SLOT(start()) );

    return app.exec();
}
int main(int /* argc */, char* argv[]){
  using namespace std::placeholders;
  namespace spd = spdlog;
  std::string app_name(argv[0]);
  Json::Value root = Camerasp::getDOM(configPath + "options.json");
  Json::Value log_config = root["Logging"];
  Json::Value json_path = log_config["path"];
  logpath = json_path.asString();
  int size_mega_bytes = log_config["size"].asInt();
  int count_files = log_config["count"].asInt();
  console = spd::rotating_logger_mt("console", logpath, 1024*1024* size_mega_bytes, count_files);

  Json::Value backup = root["Data"];
  Camerasp::max_file_count = backup["count"].asInt();
  int secs = backup["sample_period"].asInt();
  Camerasp::samplingPeriod = std::chrono::seconds(secs);
  Camerasp::pathname_prefix = backup["path_prefix"].asString();
  //console = spd::stdout_color_mt("console");
  console->set_level(spdlog::level::info);
  unsigned short port_number(8088);
  camerasp::cam_still camera;
  try  {
    console->info("Welcome to spdlog!");
      Json::Value camera_config = root["Camera"];
      if (camera_config.empty())
      {
        console->critical("Unable to read Json");
        return 1;
      }
      Camerasp::processCommandLine(camera_config, camera);
      if (!camera.open()) {
        console->critical("Error opening camera");
        return -1;
      } // The asio io_service.
      asio::io_service io_service;
      pService = &io_service;
      //Begin Camera Capture
      Camerasp::high_resolution_timer timer(io_service);
      Camerasp::setTimer(timer,camera);
      // Create the HTTP server, attach the request handler
      http_server_type http_server(io_service);
      Handlers handler(camera);
      { // todo: refactor to an other function
        http_server.request_received_event(std::bind(&Handlers::request, handler, _1, _2, _3));
        http_server.chunk_received_event(std::bind(&Handlers::chunk, handler, _1, _2, _3));
        http_server.request_expect_continue_event(std::bind(&Handlers::expect_continue, handler, _1, _2, _3));
        http_server.invalid_request_event(std::bind(&Handlers::invalid_request, handler, _1, _2, _3));
        http_server.socket_connected_event(std::bind(&Handlers::connected, handler, _1));

        http_server.socket_disconnected_event(std::bind(&Handlers::disconnected, handler, _1));
        http_server.message_sent_event(std::bind(&Handlers::message_sent, handler, _1));

        // set the connection timeout (10 seconds)
        http_server.set_timeout(10000);

        // set the connection buffer sizes
        http_server.set_rx_buffer_size(16384);
        http_server.tcp_server()->set_receive_buffer_size(16384);
        http_server.tcp_server()->set_send_buffer_size(16384);
      }
      // start accepting http connections on the port
      ASIO_ERROR_CODE error(http_server.accept_connections(port_number));
      if (error)    {
        console->critical ("Error: {0}", error.message());
        return 1;
      }

 #ifdef _WIN32
      SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
#endif
      asio::signal_set signals_(io_service);
      signals_.add(SIGINT);
      signals_.add(SIGTERM);
      #ifndef _WIN32
      signals_.add(SIGQUIT);
      #endif

      // register the handle_stop callback
      signals_.async_wait([&]
      (ASIO_ERROR_CODE const& error, int signal_number)  { 
        Camerasp::stopCapture();
        handle_stop(error, signal_number, http_server); 
        io_service.stop();
      });
      // Start the on two  worker threads server
      std::thread thread1{ [&io_service]() { io_service.run(); } };
      std::thread thread2{ [&io_service]() { io_service.run(); } };
      io_service.run();
      thread1.join();
      thread2.join();
    
    

  }  catch (std::exception& e)  {
    console->error("Exception: {0}", e.what());
    return 1;
  }
  spd::drop_all();
  return 0;
}
Example #30
0
int
start(excmd::parser &parser,
      excmd::option_state &options)
{
   // Print version
   if (options.has("version")) {
      // TODO: print git hash
      std::cout << "Decaf Emulator version 0.0.1" << std::endl;
      std::exit(0);
   }

   // Print help
   if (options.empty() || options.has("help")) {
      if (options.has("help-command")) {
         std::cout << parser.format_help("decaf", options.get<std::string>("help-command")) << std::endl;
      } else {
         std::cout << parser.format_help("decaf") << std::endl;
      }

      std::exit(0);
   }

   if (!options.has("play")) {
      return 0;
   }

   // First thing, load the config!
   std::string configPath;

   if (options.has("config")) {
      configPath = options.get<std::string>("config");
   } else {
      decaf::createConfigDirectory();
      configPath = decaf::makeConfigPath("cli_config.json");
   }

   config::load(configPath);

   // Allow command line options to override config
   if (options.has("jit-verify")) {
      decaf::config::jit::verify = true;
   }

   if (options.has("jit")) {
      decaf::config::jit::enabled = true;
   }

   if (options.has("log-no-stdout")) {
      config::log::to_stdout = true;
   }

   if (options.has("log-file")) {
      config::log::to_file = true;
   }

   if (options.has("log-async")) {
      decaf::config::log::async = true;
   }

   if (options.has("log-level")) {
      config::log::level = options.get<std::string>("log-level");
   }

   if (options.has("region")) {
      const std::string region = options.get<std::string>("region");
      if (region.compare("JAP") == 0) {
         decaf::config::system::region = coreinit::SCIRegion::JAP;
      } else if (region.compare("USA") == 0) {
         decaf::config::system::region = coreinit::SCIRegion::USA;
      } else if (region.compare("EUR") == 0) {
         decaf::config::system::region = coreinit::SCIRegion::EUR;
      } else {
         decaf_abort(fmt::format("Invalid region {}", region));
      }
   }

   if (options.has("mlc-path")) {
      decaf::config::system::mlc_path = options.get<std::string>("mlc-path");
   }

   if (options.has("time-scale")) {
      decaf::config::system::time_scale = options.get<double>("time-scale");
   }

   if (options.has("timeout_ms")) {
      config::system::timeout_ms = options.get<uint32_t>("timeout_ms");
   }

   auto gamePath = options.get<std::string>("game directory");
   auto logFile = getPathBasename(gamePath);
   auto logLevel = spdlog::level::info;
   std::vector<spdlog::sink_ptr> sinks;

   if (config::log::to_stdout) {
      sinks.push_back(spdlog::sinks::stdout_sink_st::instance());
   }

   if (config::log::to_file) {
      sinks.push_back(std::make_shared<spdlog::sinks::daily_file_sink_st>(logFile, "txt", 23, 59));
   }

   if (decaf::config::log::async) {
      spdlog::set_async_mode(1024);
   } else {
      spdlog::set_sync_mode();
   }

   for (int i = spdlog::level::trace; i <= spdlog::level::off; i++) {
      auto level = static_cast<spdlog::level::level_enum>(i);

      if (spdlog::level::to_str(level) == config::log::level) {
         logLevel = level;
         break;
      }
   }

   // Initialise libdecaf logger
   decaf::initialiseLogging(sinks, logLevel);

   // Initialise decaf-cli logger
   gCliLog = std::make_shared<spdlog::logger>("decaf-cli", begin(sinks), end(sinks));
   gCliLog->set_level(logLevel);
   gCliLog->set_pattern("[%l] %v");
   gCliLog->info("Loaded config from {}", configPath);
   gCliLog->info("Game path {}", gamePath);

   DecafCLI cli;
   return cli.run(gamePath);
}