<commit_before>/*!
    \file environment.cpp
    \brief Environment management implementation
    \author Ivan Shynkarenka
    \date 09.07.2015
    \copyright MIT License
*/

#include "benchmark/environment.h"

#include <chrono>
#include <sstream>

#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#elif defined(linux) || defined(__linux) || defined(__linux__)
#include <sys/stat.h>
#include <fstream>
#include <regex>
#endif

namespace CppBenchmark {

bool Environment::Is32BitOS()
{
    return !Is64BitOS();
}

bool Environment::Is64BitOS()
{
#if defined(_WIN32) || defined(_WIN64)
#if defined(_WIN64)
    return true;
#elif defined(_WIN32)
    BOOL bWow64Process = FALSE;
    return IsWow64Process(GetCurrentProcess(), &bWow64Process) && bWow64Process;
#endif
#elif defined(linux) || defined(__linux) || defined(__linux__)
    struct stat buffer;
    return (stat("/lib64/ld-linux-x86-64.so.2", &buffer) == 0);
#endif
}

bool Environment::Is32BitProcess()
{
    return !Is64BitProcess();
}

bool Environment::Is64BitProcess()
{
#if defined(_WIN32) || defined(_WIN64)
#if defined(_WIN64)
    return true;
#elif defined(_WIN32)
    return false;
#endif
#elif defined(unix) || defined(__unix) || defined(__unix__)
#if defined(__x86_64__) || defined(__ppc64__)
    return true;
#else
    return false;
#endif
#endif
}

bool Environment::IsDebug()
{
    return !IsRelease();
}

bool Environment::IsRelease()
{
#if defined(NDEBUG)
    return true;
#else
    return false;
#endif
}

bool Environment::IsBigEndian()
{
    char16_t test = 0x0102;
    return ((char*)&test)[0] == 0x01;
}

bool Environment::IsLittleEndian()
{
    char16_t test = 0x0102;
    return ((char*)&test)[0] == 0x02;
}

std::string Environment::OSVersion()
{
#if defined(_WIN32) || defined(_WIN64)
    static void(__stdcall *GetNativeSystemInfo)(OUT LPSYSTEM_INFO lpSystemInfo) = (void(__stdcall*)(LPSYSTEM_INFO))GetProcAddress(GetModuleHandle("kernel32.dll"), "GetNativeSystemInfo");
    static BOOL(__stdcall *GetProductInfo)(IN DWORD dwOSMajorVersion, IN DWORD dwOSMinorVersion, IN DWORD dwSpMajorVersion, IN DWORD dwSpMinorVersion, OUT PDWORD pdwReturnedProductType) = (BOOL(__stdcall*)(DWORD, DWORD, DWORD, DWORD, PDWORD))GetProcAddress(GetModuleHandle("kernel32.dll"), "GetProductInfo");

    OSVERSIONINFOEX osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

    BOOL bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*)&osvi);
    if (bOsVersionInfoEx == 0)
        return "<windows>";

    SYSTEM_INFO si;
    ZeroMemory(&si, sizeof(SYSTEM_INFO));

    if (GetNativeSystemInfo != nullptr)
        GetNativeSystemInfo(&si);
    else
        GetSystemInfo(&si);

    if ((osvi.dwPlatformId != VER_PLATFORM_WIN32_NT) || (osvi.dwMajorVersion <= 4))
    {
        return "<windows>";
    }

    std::stringstream os;

    // Windows version
    os << "Microsoft ";
    if (osvi.dwMajorVersion >= 6)
    {
        if (osvi.dwMajorVersion == 10)
        {
            if (osvi.dwMinorVersion == 0)
            {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    os << "Windows 10 ";
                else
                    os << "Windows Server 2016 ";
            }
        }
        else if (osvi.dwMajorVersion == 6)
        {
            if (osvi.dwMinorVersion == 3)
            {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    os << "Windows 8.1 ";
                else
                    os << "Windows Server 2012 R2 ";
            }
            else if (osvi.dwMinorVersion == 2)
            {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    os << "Windows 8 ";
                else
                    os << "Windows Server 2012 ";
            }
            else if (osvi.dwMinorVersion == 1)
            {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    os << "Windows 7 ";
                else
                    os << "Windows Server 2008 R2 ";
            }
            else if (osvi.dwMinorVersion == 0)
            {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    os << "Windows Vista ";
                else
                    os << "Windows Server 2008 ";
            }
        }

        DWORD dwType;
        if ((GetProductInfo != nullptr) && GetProductInfo(osvi.dwMajorVersion, osvi.dwMinorVersion, 0, 0, &dwType))
        {
            switch (dwType)
            {
                case PRODUCT_ULTIMATE:
                    os << "Ultimate Edition";
                    break;
                case PRODUCT_PROFESSIONAL:
                    os << "Professional";
                    break;
                case PRODUCT_HOME_PREMIUM:
                    os << "Home Premium Edition";
                    break;
                case PRODUCT_HOME_BASIC:
                    os << "Home Basic Edition";
                    break;
                case PRODUCT_ENTERPRISE:
                    os << "Enterprise Edition";
                    break;
                case PRODUCT_BUSINESS:
                    os << "Business Edition";
                    break;
                case PRODUCT_STARTER:
                    os << "Starter Edition";
                    break;
                case PRODUCT_CLUSTER_SERVER:
                    os << "Cluster Server Edition";
                    break;
                case PRODUCT_DATACENTER_SERVER:
                    os << "Datacenter Edition";
                    break;
                case PRODUCT_DATACENTER_SERVER_CORE:
                    os << "Datacenter Edition (core installation)";
                    break;
                case PRODUCT_ENTERPRISE_SERVER:
                    os << "Enterprise Edition";
                    break;
                case PRODUCT_ENTERPRISE_SERVER_CORE:
                    os << "Enterprise Edition (core installation)";
                    break;
                case PRODUCT_ENTERPRISE_SERVER_IA64:
                    os << "Enterprise Edition for Itanium-based Systems";
                    break;
                case PRODUCT_SMALLBUSINESS_SERVER:
                    os << "Small Business Server";
                    break;
                case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM:
                    os << "Small Business Server Premium Edition";
                    break;
                case PRODUCT_STANDARD_SERVER:
                    os << "Standard Edition";
                    break;
                case PRODUCT_STANDARD_SERVER_CORE:
                    os << "Standard Edition (core installation)";
                    break;
                case PRODUCT_WEB_SERVER:
                    os << "Web Server Edition";
                    break;
            }
        }
    }
    else if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 2))
    {
        if (GetSystemMetrics(SM_SERVERR2))
            os << "Windows Server 2003 R2, ";
        else if (osvi.wSuiteMask & VER_SUITE_STORAGE_SERVER)
            os << "Windows Storage Server 2003";
        else if (osvi.wSuiteMask & VER_SUITE_WH_SERVER)
            os << "Windows Home Server";
        else if ((osvi.wProductType == VER_NT_WORKSTATION) && (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64))
            os << "Windows XP Professional x64 Edition";
        else
            os << "Windows Server 2003, ";
        if (osvi.wProductType != VER_NT_WORKSTATION)
        {
            if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_IA64)
            {
                if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
                    os << "Datacenter Edition for Itanium-based Systems";
                else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
                    os << "Enterprise Edition for Itanium-based Systems";
            }
            else if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64)
            {
                if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
                    os << "Datacenter x64 Edition";
                else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
                    os << "Enterprise x64 Edition";
                else
                    os << "Standard x64 Edition";
            }
            else
            {
                if (osvi.wSuiteMask & VER_SUITE_COMPUTE_SERVER)
                    os << "Compute Cluster Edition";
                else if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
                    os << "Datacenter Edition";
                else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
                    os << "Enterprise Edition";
                else if (osvi.wSuiteMask & VER_SUITE_BLADE)
                    os << "Web Edition";
                else
                    os << "Standard Edition";
            }
        }
    }
    else if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 1))
    {
        os << "Windows XP ";
        if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
            os << "Home Edition";
        else
            os << "Professional";
    }
    else if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 0))
    {
        os << "Windows 2000 ";
        if (osvi.wProductType == VER_NT_WORKSTATION)
            os <<  "Professional";
        else
        {
            if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
                os << "Datacenter Server";
            else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
                os << "Advanced Server";
            else
                os << "Server";
        }
    }

    // Windows Service Pack version
    if (std::strlen(osvi.szCSDVersion) > 0)
        os << " " << osvi.szCSDVersion;

    // Windows build
    os << " (build " << osvi.dwBuildNumber << ")";

    // Windows architecture
    if ( osvi.dwMajorVersion >= 6 )
    {
        if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64)
            os <<  ", 64-bit";
        else if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_INTEL)
            os << ", 32-bit";
    }

    return os.str();
#elif defined(linux) || defined(__linux) || defined(__linux__)
    static std::regex pattern("DISTRIB_DESCRIPTION=\"(.*)\"");

    std::string line;
    std::ifstream stream("/etc/lsb-release");
    while (getline(stream, line))
    {
        std::smatch matches;
        if (std::regex_match(line, matches, pattern))
            return matches[1];
    }

    return "<linux>";
#elif defined(unix) || defined(__unix) || defined(__unix__)
    return "<unix>";
#endif
}

time_t Environment::Timestamp()
{
    return std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
}

} // namespace CppBenchmark
<commit_msg>Bugfix<commit_after>/*!
    \file environment.cpp
    \brief Environment management implementation
    \author Ivan Shynkarenka
    \date 09.07.2015
    \copyright MIT License
*/

#include "benchmark/environment.h"

#include <chrono>
#include <sstream>

#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#elif defined(linux) || defined(__linux) || defined(__linux__)
#include <sys/stat.h>
#include <fstream>
#include <regex>
#endif

namespace CppBenchmark {

bool Environment::Is32BitOS()
{
    return !Is64BitOS();
}

bool Environment::Is64BitOS()
{
#if defined(_WIN32) || defined(_WIN64)
#if defined(_WIN64)
    return true;
#elif defined(_WIN32)
    BOOL bWow64Process = FALSE;
    return IsWow64Process(GetCurrentProcess(), &bWow64Process) && bWow64Process;
#endif
#elif defined(linux) || defined(__linux) || defined(__linux__)
    struct stat buffer;
    return (stat("/lib64/ld-linux-x86-64.so.2", &buffer) == 0);
#endif
}

bool Environment::Is32BitProcess()
{
    return !Is64BitProcess();
}

bool Environment::Is64BitProcess()
{
#if defined(_WIN32) || defined(_WIN64)
#if defined(_WIN64)
    return true;
#elif defined(_WIN32)
    return false;
#endif
#elif defined(unix) || defined(__unix) || defined(__unix__)
#if defined(__x86_64__) || defined(__ppc64__)
    return true;
#else
    return false;
#endif
#endif
}

bool Environment::IsDebug()
{
    return !IsRelease();
}

bool Environment::IsRelease()
{
#if defined(NDEBUG)
    return true;
#else
    return false;
#endif
}

bool Environment::IsBigEndian()
{
    char16_t test = 0x0102;
    return ((char*)&test)[0] == 0x01;
}

bool Environment::IsLittleEndian()
{
    char16_t test = 0x0102;
    return ((char*)&test)[0] == 0x02;
}

std::string Environment::OSVersion()
{
#if defined(_WIN32) || defined(_WIN64)
    static void(__stdcall *GetNativeSystemInfo)(OUT LPSYSTEM_INFO lpSystemInfo) = (void(__stdcall*)(LPSYSTEM_INFO))GetProcAddress(GetModuleHandle("kernel32.dll"), "GetNativeSystemInfo");
    static BOOL(__stdcall *GetProductInfo)(IN DWORD dwOSMajorVersion, IN DWORD dwOSMinorVersion, IN DWORD dwSpMajorVersion, IN DWORD dwSpMinorVersion, OUT PDWORD pdwReturnedProductType) = (BOOL(__stdcall*)(DWORD, DWORD, DWORD, DWORD, PDWORD))GetProcAddress(GetModuleHandle("kernel32.dll"), "GetProductInfo");

    OSVERSIONINFOEX osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

    BOOL bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*)&osvi);
    if (bOsVersionInfoEx == 0)
        return "<windows>";

    SYSTEM_INFO si;
    ZeroMemory(&si, sizeof(SYSTEM_INFO));

    if (GetNativeSystemInfo != nullptr)
        GetNativeSystemInfo(&si);
    else
        GetSystemInfo(&si);

    if ((osvi.dwPlatformId != VER_PLATFORM_WIN32_NT) || (osvi.dwMajorVersion <= 4))
    {
        return "<windows>";
    }

    std::stringstream os;

    // Windows version
    os << "Microsoft ";
    if (osvi.dwMajorVersion >= 6)
    {
        if (osvi.dwMajorVersion == 10)
        {
            if (osvi.dwMinorVersion == 0)
            {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    os << "Windows 10 ";
                else
                    os << "Windows Server 2016 ";
            }
        }
        else if (osvi.dwMajorVersion == 6)
        {
            if (osvi.dwMinorVersion == 3)
            {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    os << "Windows 8.1 ";
                else
                    os << "Windows Server 2012 R2 ";
            }
            else if (osvi.dwMinorVersion == 2)
            {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    os << "Windows 8 ";
                else
                    os << "Windows Server 2012 ";
            }
            else if (osvi.dwMinorVersion == 1)
            {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    os << "Windows 7 ";
                else
                    os << "Windows Server 2008 R2 ";
            }
            else if (osvi.dwMinorVersion == 0)
            {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    os << "Windows Vista ";
                else
                    os << "Windows Server 2008 ";
            }
        }

        DWORD dwType;
        if ((GetProductInfo != nullptr) && GetProductInfo(osvi.dwMajorVersion, osvi.dwMinorVersion, 0, 0, &dwType))
        {
            switch (dwType)
            {
                case PRODUCT_ULTIMATE:
                    os << "Ultimate Edition";
                    break;
                case PRODUCT_PROFESSIONAL:
                    os << "Professional";
                    break;
                case PRODUCT_HOME_PREMIUM:
                    os << "Home Premium Edition";
                    break;
                case PRODUCT_HOME_BASIC:
                    os << "Home Basic Edition";
                    break;
                case PRODUCT_ENTERPRISE:
                    os << "Enterprise Edition";
                    break;
                case PRODUCT_BUSINESS:
                    os << "Business Edition";
                    break;
                case PRODUCT_STARTER:
                    os << "Starter Edition";
                    break;
                case PRODUCT_CLUSTER_SERVER:
                    os << "Cluster Server Edition";
                    break;
                case PRODUCT_DATACENTER_SERVER:
                    os << "Datacenter Edition";
                    break;
                case PRODUCT_DATACENTER_SERVER_CORE:
                    os << "Datacenter Edition (core installation)";
                    break;
                case PRODUCT_ENTERPRISE_SERVER:
                    os << "Enterprise Edition";
                    break;
                case PRODUCT_ENTERPRISE_SERVER_CORE:
                    os << "Enterprise Edition (core installation)";
                    break;
                case PRODUCT_ENTERPRISE_SERVER_IA64:
                    os << "Enterprise Edition for Itanium-based Systems";
                    break;
                case PRODUCT_SMALLBUSINESS_SERVER:
                    os << "Small Business Server";
                    break;
                case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM:
                    os << "Small Business Server Premium Edition";
                    break;
                case PRODUCT_STANDARD_SERVER:
                    os << "Standard Edition";
                    break;
                case PRODUCT_STANDARD_SERVER_CORE:
                    os << "Standard Edition (core installation)";
                    break;
                case PRODUCT_WEB_SERVER:
                    os << "Web Server Edition";
                    break;
            }
        }
    }
    else if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 2))
    {
        if (GetSystemMetrics(SM_SERVERR2))
            os << "Windows Server 2003 R2, ";
        else if (osvi.wSuiteMask & VER_SUITE_STORAGE_SERVER)
            os << "Windows Storage Server 2003";
        else if (osvi.wSuiteMask & VER_SUITE_WH_SERVER)
            os << "Windows Home Server";
        else if ((osvi.wProductType == VER_NT_WORKSTATION) && (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64))
            os << "Windows XP Professional x64 Edition";
        else
            os << "Windows Server 2003, ";
        if (osvi.wProductType != VER_NT_WORKSTATION)
        {
            if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_IA64)
            {
                if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
                    os << "Datacenter Edition for Itanium-based Systems";
                else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
                    os << "Enterprise Edition for Itanium-based Systems";
            }
            else if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64)
            {
                if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
                    os << "Datacenter x64 Edition";
                else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
                    os << "Enterprise x64 Edition";
                else
                    os << "Standard x64 Edition";
            }
            else
            {
                if (osvi.wSuiteMask & VER_SUITE_COMPUTE_SERVER)
                    os << "Compute Cluster Edition";
                else if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
                    os << "Datacenter Edition";
                else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
                    os << "Enterprise Edition";
                else if (osvi.wSuiteMask & VER_SUITE_BLADE)
                    os << "Web Edition";
                else
                    os << "Standard Edition";
            }
        }
    }
    else if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 1))
    {
        os << "Windows XP ";
        if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
            os << "Home Edition";
        else
            os << "Professional";
    }
    else if ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 0))
    {
        os << "Windows 2000 ";
        if (osvi.wProductType == VER_NT_WORKSTATION)
            os <<  "Professional";
        else
        {
            if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
                os << "Datacenter Server";
            else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
                os << "Advanced Server";
            else
                os << "Server";
        }
    }

    // Windows Service Pack version
    if (strlen(osvi.szCSDVersion) > 0)
        os << " " << osvi.szCSDVersion;

    // Windows build
    os << " (build " << osvi.dwBuildNumber << ")";

    // Windows architecture
    if ( osvi.dwMajorVersion >= 6 )
    {
        if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64)
            os <<  ", 64-bit";
        else if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_INTEL)
            os << ", 32-bit";
    }

    return os.str();
#elif defined(linux) || defined(__linux) || defined(__linux__)
    static std::regex pattern("DISTRIB_DESCRIPTION=\"(.*)\"");

    std::string line;
    std::ifstream stream("/etc/lsb-release");
    while (getline(stream, line))
    {
        std::smatch matches;
        if (std::regex_match(line, matches, pattern))
            return matches[1];
    }

    return "<linux>";
#elif defined(unix) || defined(__unix) || defined(__unix__)
    return "<unix>";
#endif
}

time_t Environment::Timestamp()
{
    return std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
}

} // namespace CppBenchmark
<|endoftext|>


<commit_before>/*
*   Copyright 2020 Google LLC
*
*   Licensed under the Apache License, Version 2.0 (the "License");
*   you may not use this file except in compliance with the License.
*   You may obtain a copy of the License at
*
*       https://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*   limitations under the License.
*/

#include "request_handler.h"

#include <vector>
#include <sstream>

namespace wireless_android_play_analytics {

void RequestHandler::GetLastRefreshed(const Pistache::Rest::Request& request,
    Pistache::Http::ResponseWriter response) {
    // Information within the request is unnecessary.
    UNUSED(request);
    response.send(Pistache::Http::Code::Ok, "Wed May 19 15:46:11 2020");
}

void RequestHandler::GetDashboard(const Pistache::Rest::Request& request,
    Pistache::Http::ResponseWriter response) {
    // TODO(alexanderlin): Use real data once I get access to them.
    std::vector<std::string> dataSources {"SPAM", "PLAY_COUNTRY",
        "APP_COUNTRY_PUBLISH_TIME", "QUERY_CATEGORY_SOURCE",
            "UNIFIED_USER_DATA_SOURCE"};
    std::vector<std::string> dates {"5/19/2020", "5/18/2020", "5/17/2020", "5/16/2020",
        "5/15/2020", "5/14/2020", "5/13/2020"};
    std::string system_in = request.param(":system").as<std::string>();
    std::string status = "111010111110001011100100111000100110001010000010100111010";

    nlohmann::json message;

    auto stream = response.stream(Pistache::Http::Code::Ok);
    if (system_in == "Chipper") {
        int status_idx = 0;
        for (const std::string& data : dataSources) {
            message[data] = nlohmann::json::array();
            for (const std::string& date : dates) {
                message[data].push_back({date, status[status_idx++] == '1'});
            }
        }
    } else {
        int status_idx = status.size() - 1;
        for (const std::string& data : dataSources) {
            message[data] = nlohmann::json::array();
            for (const std::string& date : dates) {
                message[data].push_back({date, status[status_idx--] == '1'});
            }
        }
    }

    response.send(Pistache::Http::Code::Ok, message.dump());
}

void RequestHandler::PopulateBackfillCommand
    (const Pistache::Rest::Request& request,
        Pistache::Http::ResponseWriter response) {
        std::string date = request.param(":date").as<std::string>();
        std::string system = request.param(":system").as<std::string>();
        std::string source = request.param(":source").as<std::string>();
        std::string command = "sample command to run backfill for " + source
            + " on " + system + " for " + date;
        response.send(Pistache::Http::Code::Ok, command);
}

} // namespace wireless_android_play_analytics<commit_msg>added comment for more clarity<commit_after>/*
*   Copyright 2020 Google LLC
*
*   Licensed under the Apache License, Version 2.0 (the "License");
*   you may not use this file except in compliance with the License.
*   You may obtain a copy of the License at
*
*       https://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*   limitations under the License.
*/

#include "request_handler.h"

#include <vector>
#include <sstream>

namespace wireless_android_play_analytics {

void RequestHandler::GetLastRefreshed(const Pistache::Rest::Request& request,
    Pistache::Http::ResponseWriter response) {
    // Information within the request is unnecessary.
    UNUSED(request);
    response.send(Pistache::Http::Code::Ok, "Wed May 19 15:46:11 2020");
}

void RequestHandler::GetDashboard(const Pistache::Rest::Request& request,
    Pistache::Http::ResponseWriter response) {
    // TODO(alexanderlin): Use real data once I get access to them.
    std::vector<std::string> data_sources {"SPAM", "PLAY_COUNTRY",
        "APP_COUNTRY_PUBLISH_TIME", "QUERY_CATEGORY_SOURCE",
            "UNIFIED_USER_DATA_SOURCE"};
    std::vector<std::string> dates {"5/19/2020", "5/18/2020", "5/17/2020",
            "5/16/2020", "5/15/2020", "5/14/2020", "5/13/2020"};
    std::string system_in = request.param(":system").as<std::string>();
    // Randomly generated bits that hardcodes whether the data source is online
    // or not for specific dates since real data not available yet.
    std::string status =
            "111010111110001011100100111000100110001010000010100111010";

    nlohmann::json message;

    auto stream = response.stream(Pistache::Http::Code::Ok);
    if (system_in == "Chipper") {
        int status_idx = 0;
        for (const std::string& data : data_sources) {
            message[data] = nlohmann::json::array();
            for (const std::string& date : dates) {
                message[data].push_back({date, status[status_idx++] == '1'});
            }
        }
    } else {
        // Reverse ordering so that Chipper and Chipper GDPR has different
        // hardcoded values.
        int status_idx = status.size() - 1;
        for (const std::string& data : data_sources) {
            message[data] = nlohmann::json::array();
            for (const std::string& date : dates) {
                message[data].push_back({date, status[status_idx--] == '1'});
            }
        }
    }

    response.send(Pistache::Http::Code::Ok, message.dump());
}

void RequestHandler::PopulateBackfillCommand
    (const Pistache::Rest::Request& request,
        Pistache::Http::ResponseWriter response) {
        std::string date = request.param(":date").as<std::string>();
        std::string system = request.param(":system").as<std::string>();
        std::string source = request.param(":source").as<std::string>();
        std::string command = "sample command to run backfill for " + source
            + " on " + system + " for " + date;
        response.send(Pistache::Http::Code::Ok, command);
}

} // namespace wireless_android_play_analytics<|endoftext|>


<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastracture and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include <functional>
#include <utility>
#include <vector>
#include "bit_vector_ranking.hpp"

#include "../storage/fixed_size_heap.hpp"

using std::make_pair;
using std::pair;
using std::vector;
using jubatus::core::table::bit_vector;
using jubatus::core::table::const_bit_vector_column;

namespace jubatus {
namespace core {
namespace nearest_neighbor {

void ranking_hamming_bit_vectors(
    const bit_vector& query,
    const const_bit_vector_column& bvs,
    vector<pair<uint64_t, float> >& ret,
    uint64_t ret_num) {
  storage::fixed_size_heap<pair<uint32_t, uint64_t> > heap(ret_num);
  for (uint64_t i = 0; i< bvs.size(); ++i) {
    const size_t dist = query.calc_hamming_distance(bvs[i]);
    heap.push(make_pair(dist, i));
  }

  vector<pair<uint32_t, uint64_t> > sorted;
  heap.get_sorted(sorted);

  ret.clear();
  const float denom = query.bit_num();
  for (size_t i = 0; i < sorted.size(); ++i) {
    ret.push_back(make_pair(sorted[i].second, sorted[i].first / denom));
  }
}

}  // namespace nearest_neighbor
}  // namespace core
}  // namespace jubatus
<commit_msg>Fix format of bit_vector_ranking.cpp<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastracture and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include <functional>
#include <utility>
#include <vector>
#include "bit_vector_ranking.hpp"

#include "../storage/fixed_size_heap.hpp"

using std::make_pair;
using std::pair;
using std::vector;
using jubatus::core::table::bit_vector;
using jubatus::core::table::const_bit_vector_column;

namespace jubatus {
namespace core {
namespace nearest_neighbor {

void ranking_hamming_bit_vectors(
    const bit_vector& query,
    const const_bit_vector_column& bvs,
    vector<pair<uint64_t, float> >& ret,
    uint64_t ret_num) {
  storage::fixed_size_heap<pair<uint32_t, uint64_t> > heap(ret_num);
  for (uint64_t i = 0; i < bvs.size(); ++i) {
    const size_t dist = query.calc_hamming_distance(bvs[i]);
    heap.push(make_pair(dist, i));
  }

  vector<pair<uint32_t, uint64_t> > sorted;
  heap.get_sorted(sorted);

  ret.clear();
  const float denom = query.bit_num();
  for (size_t i = 0; i < sorted.size(); ++i) {
    ret.push_back(make_pair(sorted[i].second, sorted[i].first / denom));
  }
}

}  // namespace nearest_neighbor
}  // namespace core
}  // namespace jubatus
<|endoftext|>


<commit_before>/*
 * Implementation of FlowReader class
 *
 * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

#include <boost/shared_ptr.hpp>
#include <boost/foreach.hpp>
#include <boost/thread/mutex.hpp>

#include "logging.h"
#include "ovs.h"
#include "FlowReader.h"
#include "ActionBuilder.h"

using namespace std;
using namespace boost;
using namespace opflex::enforcer;
using namespace opflex::enforcer::flow;
using namespace ovsagent;

typedef lock_guard<mutex> mutex_guard;

namespace ovsagent {

FlowReader::FlowReader() : swConn(NULL) {
}

FlowReader::~FlowReader() {
}

void FlowReader::installListenersForConnection(SwitchConnection *conn) {
    swConn = conn;
    conn->RegisterMessageHandler(OFPTYPE_FLOW_STATS_REPLY, this);
    conn->RegisterMessageHandler(OFPTYPE_GROUP_DESC_STATS_REPLY, this);
}

void FlowReader::uninstallListenersForConnection(SwitchConnection *conn) {
    conn->UnregisterMessageHandler(OFPTYPE_FLOW_STATS_REPLY, this);
    conn->RegisterMessageHandler(OFPTYPE_GROUP_DESC_STATS_REPLY, this);
}

bool FlowReader::getFlows(uint8_t tableId, const FlowCb& cb) {
    ofpbuf *req = createFlowRequest(tableId);
    return sendRequest<FlowCb, FlowCbMap>(req, cb, flowRequests);
}

bool FlowReader::getGroups(const GroupCb& cb) {
    ofpbuf *req = createGroupRequest();
    return sendRequest<GroupCb, GroupCbMap>(req, cb, groupRequests);
}

ofpbuf *FlowReader::createFlowRequest(uint8_t tableId) {
    ofp_version ofVer = swConn->GetProtocolVersion();
    ofputil_protocol proto = ofputil_protocol_from_ofp_version(ofVer);

    ofputil_flow_stats_request fsr;
    fsr.aggregate = false;
    match_init_catchall(&fsr.match);
    fsr.table_id = tableId;
    fsr.out_port = OFPP_ANY;
    fsr.out_group = OFPG11_ANY;
    fsr.cookie = fsr.cookie_mask = htonll(0);

    ofpbuf *req = ofputil_encode_flow_stats_request(&fsr, proto);
    return req;
}

ofpbuf *FlowReader::createGroupRequest() {
    return ofputil_encode_group_desc_request(swConn->GetProtocolVersion(),
                                             OFPG_ALL);
}

template <typename U, typename V>
bool FlowReader::sendRequest(ofpbuf *req, const U& cb, V& reqMap) {
    ovs_be32 reqXid = ((ofp_header *)ofpbuf_data(req))->xid;
    LOG(DEBUG) << "Sending flow/group read request xid=" << reqXid;

    {
        mutex_guard lock(reqMtx);
        reqMap[reqXid] = cb;
    }
    int err = swConn->SendMessage(req);
    if (err != 0) {
        LOG(ERROR) << "Failed to send flow/group read request: "
            << ovs_strerror(err);
        mutex_guard lock(reqMtx);
        reqMap.erase(reqXid);
    }
    return (err == 0);
}

void FlowReader::Handle(SwitchConnection *c, ofptype msgType, ofpbuf *msg) {
    if (msgType == OFPTYPE_FLOW_STATS_REPLY) {
        handleReply<FlowEntryList, FlowCb, FlowCbMap>(
            msgType, msg, flowRequests);
    } else if (msgType == OFPTYPE_GROUP_DESC_STATS_REPLY) {
        handleReply<GroupEdit::EntryList, GroupCb, GroupCbMap>(
            msgType, msg, groupRequests);
    }
}

template<typename T, typename U, typename V>
void FlowReader::handleReply(ofptype msgType, ofpbuf *msg, V& reqMap) {
    ofp_header *msgHdr = (ofp_header *)ofpbuf_data(msg);
    ovs_be32 recvXid = msgHdr->xid;

    U cb;
    {
        mutex_guard lock(reqMtx);
        typename V::iterator itr = reqMap.find(recvXid);
        if (itr == reqMap.end()) {
            return;
        }
        cb = itr->second;
    }

    T recv;
    bool replyDone = false;

    decodeReply<T>(msg, recv, replyDone);

    if (replyDone) {
        mutex_guard lock(reqMtx);
        reqMap.erase(recvXid);
    }
    cb(recv, replyDone);
}

template<>
void FlowReader::decodeReply(ofpbuf *msg, FlowEntryList& recvFlows,
        bool& replyDone) {
    do {
        FlowEntryPtr entry(new FlowEntry());

        ofpbuf actsBuf;
        ofpbuf_init(&actsBuf, 32);
        int ret = ofputil_decode_flow_stats_reply(entry->entry, msg, false,
                &actsBuf);
        entry->entry->ofpacts = ActionBuilder::GetActionsFromBuffer(&actsBuf,
                entry->entry->ofpacts_len);
        ofpbuf_uninit(&actsBuf);

        /* HACK: override the "raw" field so that our comparisons work properly */
        ofpact *act;
        OFPACT_FOR_EACH(act, entry->entry->ofpacts, entry->entry->ofpacts_len) {
            if (act->type == OFPACT_OUTPUT_REG) {
                act->raw = (uint8_t)(-1);
            }
        }

        if (ret != 0) {
            if (ret == EOF) {
                replyDone = !ofpmp_more((ofp_header*)msg->frame);
            } else {
                LOG(ERROR) << "Failed to decode flow stats reply: "
                    << ovs_strerror(ret);
                replyDone = true;
            }
            break;
        }
        recvFlows.push_back(entry);
        LOG(DEBUG) << "Got flow: " << *entry;
    } while (true);
}

template<>
void FlowReader::decodeReply(ofpbuf *msg, GroupEdit::EntryList& recv,
        bool& replyDone) {
    ofp_version ver = (ofp_version)((ofp_header *)ofpbuf_data(msg))->version;
    while (true) {
        ofputil_group_desc gd;
        int ret = ofputil_decode_group_desc_reply(&gd, msg, ver);
        if (ret != 0) {
            if (ret != EOF) {
                LOG(ERROR) << "Failed to decode group desc reply: "
                    << ovs_strerror(ret);
            }
            replyDone = true;
            break;
        }

        GroupEdit::Entry entry(new GroupEdit::GroupMod());
        entry->mod->group_id = gd.group_id;
        entry->mod->type = gd.type;
        list_move(&entry->mod->buckets, &gd.buckets);
        recv.push_back(entry);

        LOG(DEBUG) << "Got group: " << entry;
     }
}

}   // namespace ovsagent

<commit_msg>Properly read multi-message group desc replies<commit_after>/*
 * Implementation of FlowReader class
 *
 * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

#include <boost/shared_ptr.hpp>
#include <boost/foreach.hpp>
#include <boost/thread/mutex.hpp>

#include "logging.h"
#include "ovs.h"
#include "FlowReader.h"
#include "ActionBuilder.h"

using namespace std;
using namespace boost;
using namespace opflex::enforcer;
using namespace opflex::enforcer::flow;
using namespace ovsagent;

typedef lock_guard<mutex> mutex_guard;

namespace ovsagent {

FlowReader::FlowReader() : swConn(NULL) {
}

FlowReader::~FlowReader() {
}

void FlowReader::installListenersForConnection(SwitchConnection *conn) {
    swConn = conn;
    conn->RegisterMessageHandler(OFPTYPE_FLOW_STATS_REPLY, this);
    conn->RegisterMessageHandler(OFPTYPE_GROUP_DESC_STATS_REPLY, this);
}

void FlowReader::uninstallListenersForConnection(SwitchConnection *conn) {
    conn->UnregisterMessageHandler(OFPTYPE_FLOW_STATS_REPLY, this);
    conn->RegisterMessageHandler(OFPTYPE_GROUP_DESC_STATS_REPLY, this);
}

bool FlowReader::getFlows(uint8_t tableId, const FlowCb& cb) {
    ofpbuf *req = createFlowRequest(tableId);
    return sendRequest<FlowCb, FlowCbMap>(req, cb, flowRequests);
}

bool FlowReader::getGroups(const GroupCb& cb) {
    ofpbuf *req = createGroupRequest();
    return sendRequest<GroupCb, GroupCbMap>(req, cb, groupRequests);
}

ofpbuf *FlowReader::createFlowRequest(uint8_t tableId) {
    ofp_version ofVer = swConn->GetProtocolVersion();
    ofputil_protocol proto = ofputil_protocol_from_ofp_version(ofVer);

    ofputil_flow_stats_request fsr;
    fsr.aggregate = false;
    match_init_catchall(&fsr.match);
    fsr.table_id = tableId;
    fsr.out_port = OFPP_ANY;
    fsr.out_group = OFPG11_ANY;
    fsr.cookie = fsr.cookie_mask = htonll(0);

    ofpbuf *req = ofputil_encode_flow_stats_request(&fsr, proto);
    return req;
}

ofpbuf *FlowReader::createGroupRequest() {
    return ofputil_encode_group_desc_request(swConn->GetProtocolVersion(),
                                             OFPG_ALL);
}

template <typename U, typename V>
bool FlowReader::sendRequest(ofpbuf *req, const U& cb, V& reqMap) {
    ovs_be32 reqXid = ((ofp_header *)ofpbuf_data(req))->xid;
    LOG(DEBUG) << "Sending flow/group read request xid=" << reqXid;

    {
        mutex_guard lock(reqMtx);
        reqMap[reqXid] = cb;
    }
    int err = swConn->SendMessage(req);
    if (err != 0) {
        LOG(ERROR) << "Failed to send flow/group read request: "
            << ovs_strerror(err);
        mutex_guard lock(reqMtx);
        reqMap.erase(reqXid);
    }
    return (err == 0);
}

void FlowReader::Handle(SwitchConnection *c, ofptype msgType, ofpbuf *msg) {
    if (msgType == OFPTYPE_FLOW_STATS_REPLY) {
        handleReply<FlowEntryList, FlowCb, FlowCbMap>(
            msgType, msg, flowRequests);
    } else if (msgType == OFPTYPE_GROUP_DESC_STATS_REPLY) {
        handleReply<GroupEdit::EntryList, GroupCb, GroupCbMap>(
            msgType, msg, groupRequests);
    }
}

template<typename T, typename U, typename V>
void FlowReader::handleReply(ofptype msgType, ofpbuf *msg, V& reqMap) {
    ofp_header *msgHdr = (ofp_header *)ofpbuf_data(msg);
    ovs_be32 recvXid = msgHdr->xid;

    U cb;
    {
        mutex_guard lock(reqMtx);
        typename V::iterator itr = reqMap.find(recvXid);
        if (itr == reqMap.end()) {
            return;
        }
        cb = itr->second;
    }

    T recv;
    bool replyDone = false;

    decodeReply<T>(msg, recv, replyDone);

    if (replyDone) {
        mutex_guard lock(reqMtx);
        reqMap.erase(recvXid);
    }
    cb(recv, replyDone);
}

template<>
void FlowReader::decodeReply(ofpbuf *msg, FlowEntryList& recvFlows,
        bool& replyDone) {
    do {
        FlowEntryPtr entry(new FlowEntry());

        ofpbuf actsBuf;
        ofpbuf_init(&actsBuf, 32);
        int ret = ofputil_decode_flow_stats_reply(entry->entry, msg, false,
                &actsBuf);
        entry->entry->ofpacts = ActionBuilder::GetActionsFromBuffer(&actsBuf,
                entry->entry->ofpacts_len);
        ofpbuf_uninit(&actsBuf);

        /* HACK: override the "raw" field so that our comparisons work properly */
        ofpact *act;
        OFPACT_FOR_EACH(act, entry->entry->ofpacts, entry->entry->ofpacts_len) {
            if (act->type == OFPACT_OUTPUT_REG) {
                act->raw = (uint8_t)(-1);
            }
        }

        if (ret != 0) {
            if (ret == EOF) {
                replyDone = !ofpmp_more((ofp_header*)msg->frame);
            } else {
                LOG(ERROR) << "Failed to decode flow stats reply: "
                    << ovs_strerror(ret);
                replyDone = true;
            }
            break;
        }
        recvFlows.push_back(entry);
        LOG(DEBUG) << "Got flow: " << *entry;
    } while (true);
}

template<>
void FlowReader::decodeReply(ofpbuf *msg, GroupEdit::EntryList& recv,
        bool& replyDone) {
    ofp_version ver = (ofp_version)((ofp_header *)ofpbuf_data(msg))->version;
    while (true) {
        ofputil_group_desc gd;
        int ret = ofputil_decode_group_desc_reply(&gd, msg, ver);
        if (ret != 0) {
            if (ret == EOF) {
                replyDone = !ofpmp_more((ofp_header*)msg->frame);
            } else {
                LOG(ERROR) << "Failed to decode group desc reply: "
                    << ovs_strerror(ret);
                replyDone = true;
            }
            break;
        }

        GroupEdit::Entry entry(new GroupEdit::GroupMod());
        entry->mod->group_id = gd.group_id;
        entry->mod->type = gd.type;
        list_move(&entry->mod->buckets, &gd.buckets);
        recv.push_back(entry);

        LOG(DEBUG) << "Got group: " << entry;
     }
}

}   // namespace ovsagent

<|endoftext|>


<commit_before><commit_msg>Format: clang-format.sh run<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2007-2017 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef ACCESS_LOG_CONFIG_HXX
#define ACCESS_LOG_CONFIG_HXX

#include "net/AllocatedSocketAddress.hxx"

#include <string>
#include <set>

/**
 * Configuration which describes whether and how to log HTTP requests.
 */
struct AccessLogConfig {
    enum class Type {
        DISABLED,
        INTERNAL,
        SEND,
        EXECUTE,
    } type = Type::INTERNAL;

    /**
     * An address where we will send access log datagrams.
     */
    AllocatedSocketAddress send_to;

    /**
     * A command to be executed with a shell, where fd0 is a socket
     * which receives access log datagrams.
     *
     * Special value "null" specifies that access logging is disabled
     * completely, and "" (empty string) specifies that one-line
     * logging is performed directly to stdandard output.
     */
    std::string command;

    /**
     * Don't log this request URI if host=="localhost" and
     * status==200.
     */
    std::string ignore_localhost_200;

    /**
     * A list of proxy servers whose "X-Forwarded-For" header will be
     * trusted.
     */
    std::set<std::string> trust_xff;

    /**
     * Setter for the deprecated "--access-logger" command-line
     * option, which has a few special cases.
     */
    void SetLegacy(const char *new_value) {
        command = new_value;

        if (command.empty() || command == "internal")
            type = Type::INTERNAL;
        else if (command == "null")
            type = Type::DISABLED;
        else
            type = Type::EXECUTE;
    }
};

#endif
<commit_msg>access_log/Config: fix typo in comment<commit_after>/*
 * Copyright 2007-2017 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef ACCESS_LOG_CONFIG_HXX
#define ACCESS_LOG_CONFIG_HXX

#include "net/AllocatedSocketAddress.hxx"

#include <string>
#include <set>

/**
 * Configuration which describes whether and how to log HTTP requests.
 */
struct AccessLogConfig {
    enum class Type {
        DISABLED,
        INTERNAL,
        SEND,
        EXECUTE,
    } type = Type::INTERNAL;

    /**
     * An address where we will send access log datagrams.
     */
    AllocatedSocketAddress send_to;

    /**
     * A command to be executed with a shell, where fd0 is a socket
     * which receives access log datagrams.
     *
     * Special value "null" specifies that access logging is disabled
     * completely, and "" (empty string) specifies that one-line
     * logging is performed directly to standard output.
     */
    std::string command;

    /**
     * Don't log this request URI if host=="localhost" and
     * status==200.
     */
    std::string ignore_localhost_200;

    /**
     * A list of proxy servers whose "X-Forwarded-For" header will be
     * trusted.
     */
    std::set<std::string> trust_xff;

    /**
     * Setter for the deprecated "--access-logger" command-line
     * option, which has a few special cases.
     */
    void SetLegacy(const char *new_value) {
        command = new_value;

        if (command.empty() || command == "internal")
            type = Type::INTERNAL;
        else if (command == "null")
            type = Type::DISABLED;
        else
            type = Type::EXECUTE;
    }
};

#endif
<|endoftext|>


<commit_before>//===-- OProfileJITEventListener.cpp - Tell OProfile about JITted code ----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a JITEventListener object that calls into OProfile to tell
// it about JITted functions.  For now, we only record function names and sizes,
// but eventually we'll also record line number information.
//
// See http://oprofile.sourceforge.net/doc/devel/jit-interface.html for the
// definition of the interface we're using.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "oprofile-jit-event-listener"
#include "llvm/Function.h"
#include "llvm/Analysis/DebugInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Errno.h"
#include "llvm/Config/config.h"
#include <stddef.h>
using namespace llvm;

#if USE_OPROFILE

#include <opagent.h>

namespace {

class OProfileJITEventListener : public JITEventListener {
  op_agent_t Agent;
public:
  OProfileJITEventListener();
  ~OProfileJITEventListener();

  virtual void NotifyFunctionEmitted(const Function &F,
                                     void *FnStart, size_t FnSize,
                                     const EmittedFunctionDetails &Details);
  virtual void NotifyFreeingMachineCode(void *OldPtr);
};

OProfileJITEventListener::OProfileJITEventListener()
    : Agent(op_open_agent()) {
  if (Agent == NULL) {
    const std::string err_str = sys::StrError();
    DEBUG(errs() << "Failed to connect to OProfile agent: " << err_str << "\n");
  } else {
    DEBUG(errs() << "Connected to OProfile agent.\n");
  }
}

OProfileJITEventListener::~OProfileJITEventListener() {
  if (Agent != NULL) {
    if (op_close_agent(Agent) == -1) {
      const std::string err_str = sys::StrError();
      DEBUG(errs() << "Failed to disconnect from OProfile agent: "
                   << err_str << "\n");
    } else {
      DEBUG(errs() << "Disconnected from OProfile agent.\n");
    }
  }
}

class FilenameCache {
  // Holds the filename of each Scope, so that we can pass a null-terminated
  // string into oprofile.
  DenseMap<MDNode*, std::string> Filenames;

 public:
  const char *getFilename(MDNode *Scope) {
    std::string &Filename = Filenames[Scope];
    if (Filename == NULL) {
      DIScope S(Scope);
      Filename = S.getFilename();
    }
    return Filename.c_str();
  }
};

static debug_line_info LineStartToOProfileFormat(
    const MachineFunction &MF, FilenameCache &Filenames,
    uintptr_t Address, DebugLoc Loc) {
  debug_line_info Result;
  Result.vma = Address;
  const DebugLocTuple &tuple = MF.getDebugLocTuple(Loc);
  Result.lineno = tuple.Line;
  Result.filename = Filenames.getFilename(tuple.Scope);
  DEBUG(errs() << "Mapping " << reinterpret_cast<void*>(Result.vma) << " to "
               << Result.filename << ":" << Result.lineno << "\n");
  return Result;
}

// Adds the just-emitted function to the symbol table.
void OProfileJITEventListener::NotifyFunctionEmitted(
    const Function &F, void *FnStart, size_t FnSize,
    const EmittedFunctionDetails &Details) {
  assert(F.hasName() && FnStart != 0 && "Bad symbol to add");
  if (op_write_native_code(Agent, F.getName().data(),
                           reinterpret_cast<uint64_t>(FnStart),
                           FnStart, FnSize) == -1) {
    DEBUG(errs() << "Failed to tell OProfile about native function "
          << F.getName() << " at ["
          << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n");
    return;
  }

  // Now we convert the line number information from the address/DebugLoc format
  // in Details to the address/filename/lineno format that OProfile expects.
  // OProfile 0.9.4 (and maybe later versions) has a bug that causes it to
  // ignore line numbers for addresses above 4G.
  FilenameCache Filenames;
  std::vector<debug_line_info> LineInfo;
  LineInfo.reserve(1 + Details.LineStarts.size());
  if (!Details.MF->getDefaultDebugLoc().isUnknown()) {
    LineInfo.push_back(LineStartToOProfileFormat(
        *Details.MF, Filenames,
        reinterpret_cast<uintptr_t>(FnStart),
        Details.MF->getDefaultDebugLoc()));
  }
  for (std::vector<EmittedFunctionDetails::LineStart>::const_iterator
           I = Details.LineStarts.begin(), E = Details.LineStarts.end();
       I != E; ++I) {
    LineInfo.push_back(LineStartToOProfileFormat(
        *Details.MF, Filenames, I->Address, I->Loc));
  }
  if (!LineInfo.empty()) {
    if (op_write_debug_line_info(Agent, FnStart,
                                 LineInfo.size(), &*LineInfo.begin()) == -1) {
      DEBUG(errs()
            << "Failed to tell OProfile about line numbers for native function "
            << F.getName() << " at ["
            << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n");
    }
  }
}

// Removes the being-deleted function from the symbol table.
void OProfileJITEventListener::NotifyFreeingMachineCode(void *FnStart) {
  assert(FnStart && "Invalid function pointer");
  if (op_unload_native_code(Agent, reinterpret_cast<uint64_t>(FnStart)) == -1) {
    DEBUG(errs()
          << "Failed to tell OProfile about unload of native function at "
          << FnStart << "\n");
  }
}

}  // anonymous namespace.

namespace llvm {
JITEventListener *createOProfileJITEventListener() {
  return new OProfileJITEventListener;
}
}

#else  // USE_OPROFILE

namespace llvm {
// By defining this to return NULL, we can let clients call it unconditionally,
// even if they haven't configured with the OProfile libraries.
JITEventListener *createOProfileJITEventListener() {
  return NULL;
}
}  // namespace llvm

#endif  // USE_OPROFILE
<commit_msg>Comparing std::string with NULL is a bad idea, so just check whether its empty.<commit_after>//===-- OProfileJITEventListener.cpp - Tell OProfile about JITted code ----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a JITEventListener object that calls into OProfile to tell
// it about JITted functions.  For now, we only record function names and sizes,
// but eventually we'll also record line number information.
//
// See http://oprofile.sourceforge.net/doc/devel/jit-interface.html for the
// definition of the interface we're using.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "oprofile-jit-event-listener"
#include "llvm/Function.h"
#include "llvm/Analysis/DebugInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Errno.h"
#include "llvm/Config/config.h"
#include <stddef.h>
using namespace llvm;

#if USE_OPROFILE

#include <opagent.h>

namespace {

class OProfileJITEventListener : public JITEventListener {
  op_agent_t Agent;
public:
  OProfileJITEventListener();
  ~OProfileJITEventListener();

  virtual void NotifyFunctionEmitted(const Function &F,
                                     void *FnStart, size_t FnSize,
                                     const EmittedFunctionDetails &Details);
  virtual void NotifyFreeingMachineCode(void *OldPtr);
};

OProfileJITEventListener::OProfileJITEventListener()
    : Agent(op_open_agent()) {
  if (Agent == NULL) {
    const std::string err_str = sys::StrError();
    DEBUG(errs() << "Failed to connect to OProfile agent: " << err_str << "\n");
  } else {
    DEBUG(errs() << "Connected to OProfile agent.\n");
  }
}

OProfileJITEventListener::~OProfileJITEventListener() {
  if (Agent != NULL) {
    if (op_close_agent(Agent) == -1) {
      const std::string err_str = sys::StrError();
      DEBUG(errs() << "Failed to disconnect from OProfile agent: "
                   << err_str << "\n");
    } else {
      DEBUG(errs() << "Disconnected from OProfile agent.\n");
    }
  }
}

class FilenameCache {
  // Holds the filename of each Scope, so that we can pass a null-terminated
  // string into oprofile.
  DenseMap<MDNode*, std::string> Filenames;

 public:
  const char *getFilename(MDNode *Scope) {
    std::string &Filename = Filenames[Scope];
    if (Filename.empty()) {
      DIScope S(Scope);
      Filename = S.getFilename();
    }
    return Filename.c_str();
  }
};

static debug_line_info LineStartToOProfileFormat(
    const MachineFunction &MF, FilenameCache &Filenames,
    uintptr_t Address, DebugLoc Loc) {
  debug_line_info Result;
  Result.vma = Address;
  const DebugLocTuple &tuple = MF.getDebugLocTuple(Loc);
  Result.lineno = tuple.Line;
  Result.filename = Filenames.getFilename(tuple.Scope);
  DEBUG(errs() << "Mapping " << reinterpret_cast<void*>(Result.vma) << " to "
               << Result.filename << ":" << Result.lineno << "\n");
  return Result;
}

// Adds the just-emitted function to the symbol table.
void OProfileJITEventListener::NotifyFunctionEmitted(
    const Function &F, void *FnStart, size_t FnSize,
    const EmittedFunctionDetails &Details) {
  assert(F.hasName() && FnStart != 0 && "Bad symbol to add");
  if (op_write_native_code(Agent, F.getName().data(),
                           reinterpret_cast<uint64_t>(FnStart),
                           FnStart, FnSize) == -1) {
    DEBUG(errs() << "Failed to tell OProfile about native function "
          << F.getName() << " at ["
          << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n");
    return;
  }

  // Now we convert the line number information from the address/DebugLoc format
  // in Details to the address/filename/lineno format that OProfile expects.
  // OProfile 0.9.4 (and maybe later versions) has a bug that causes it to
  // ignore line numbers for addresses above 4G.
  FilenameCache Filenames;
  std::vector<debug_line_info> LineInfo;
  LineInfo.reserve(1 + Details.LineStarts.size());
  if (!Details.MF->getDefaultDebugLoc().isUnknown()) {
    LineInfo.push_back(LineStartToOProfileFormat(
        *Details.MF, Filenames,
        reinterpret_cast<uintptr_t>(FnStart),
        Details.MF->getDefaultDebugLoc()));
  }
  for (std::vector<EmittedFunctionDetails::LineStart>::const_iterator
           I = Details.LineStarts.begin(), E = Details.LineStarts.end();
       I != E; ++I) {
    LineInfo.push_back(LineStartToOProfileFormat(
        *Details.MF, Filenames, I->Address, I->Loc));
  }
  if (!LineInfo.empty()) {
    if (op_write_debug_line_info(Agent, FnStart,
                                 LineInfo.size(), &*LineInfo.begin()) == -1) {
      DEBUG(errs()
            << "Failed to tell OProfile about line numbers for native function "
            << F.getName() << " at ["
            << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n");
    }
  }
}

// Removes the being-deleted function from the symbol table.
void OProfileJITEventListener::NotifyFreeingMachineCode(void *FnStart) {
  assert(FnStart && "Invalid function pointer");
  if (op_unload_native_code(Agent, reinterpret_cast<uint64_t>(FnStart)) == -1) {
    DEBUG(errs()
          << "Failed to tell OProfile about unload of native function at "
          << FnStart << "\n");
  }
}

}  // anonymous namespace.

namespace llvm {
JITEventListener *createOProfileJITEventListener() {
  return new OProfileJITEventListener;
}
}

#else  // USE_OPROFILE

namespace llvm {
// By defining this to return NULL, we can let clients call it unconditionally,
// even if they haven't configured with the OProfile libraries.
JITEventListener *createOProfileJITEventListener() {
  return NULL;
}
}  // namespace llvm

#endif  // USE_OPROFILE
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>

#include "../include/extract_objects.hpp"

#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/optional.hpp>
#include <boost/none.hpp>
using boost::optional;
using boost::none;
namespace po = boost::program_options;
namespace fs = boost::filesystem;

boost::filesystem::path make_relative(boost::filesystem::path a_From,
                                      boost::filesystem::path a_To) {
  a_From = boost::filesystem::absolute(a_From);
  a_To = boost::filesystem::absolute(a_To);
  boost::filesystem::path ret;
  boost::filesystem::path::const_iterator itrFrom(a_From.begin()),
      itrTo(a_To.begin());
  // Find common base
  for (boost::filesystem::path::const_iterator toEnd(a_To.end()),
       fromEnd(a_From.end());
       itrFrom != fromEnd && itrTo != toEnd && *itrFrom == *itrTo;
       ++itrFrom, ++itrTo)
    ;
  // Navigate backwards in directory to reach previously found base
  for (boost::filesystem::path::const_iterator fromEnd(a_From.end());
       itrFrom != fromEnd; ++itrFrom) {
    if ((*itrFrom) != ".")
      ret /= "..";
  }
  // Now navigate down the directory branch
  // ret.append( itrTo, a_To.end() );
  for (; itrTo != a_To.end(); ++itrTo) {
    ret /= *itrTo;
  }
  return ret;
}

int main(int argc, char const *argv[]) {
  std::string file_in;
  std::string dir_out;
  std::string json_out;

  po::options_description desc("Graphene command line options");
  desc.add_options()("help,h", "Help message")(
      "input,i", po::value<std::string>(&file_in)->required(),
      "Input ifc file")("output,o", po::value<std::string>(&dir_out),
                        "Output directory")(
      "json,j", po::value<std::string>(&json_out)->default_value(""),
      "Optional JSON index file")("shared,s",
                                  "Make vertices shared between faces");

  // Check for required options.
  po::variables_map vm;
  bool optionsException = false;
  try {
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);
  } catch (std::exception &e) {
    if (!vm.count("help")) {
      std::cout << e.what() << "\n";
    }
    optionsException = true;
  }
  if (optionsException || vm.count("help")) {
    std::cout << desc << "\n";
    return optionsException ? 1 : 0;
  }

  fs::path path_in(file_in);
  if (!fs::exists(path_in)) {
    std::cerr << "File \"" << file_in << "\" does not exist. Aborting.\n";
    return 1;
  }

  bool json = json_out != "";

  fs::path path_out(dir_out);
  if (!fs::exists(path_out)) {
    fs::create_directories(path_out);
  }

  std::string root_guid;
  auto objects =
      ifc_mesh_extract::extract_objects(root_guid, path_in, vm.count("shared"));

  auto filename_out = [=](std::string guid, std::string type) {
    std::string file_part =
        root_guid + "__GUID_" + guid + "__TYPE_" + type + ".obj";
    return (path_out / file_part).string();
  };

  if (!objects.size()) {
    std::cerr << "No objects extracted. Aborting."
              << "\n";
    return 1;
  }

  std::vector<ifc_mesh_extract::object_info> obj_infos;
  fs::path json_path(json_out);
  for (const auto &obj : objects) {
    std::string fname = filename_out(std::get<1>(obj), std::get<2>(obj));
    if (!OpenMesh::IO::write_mesh(std::get<0>(obj), fname)) {
      std::cerr << "Unable to write mesh to \"" + fname + "\"";
    }
    if (json) {
      ifc_mesh_extract::object_info info;
      info.path =
          make_relative(json_path.parent_path(), fs::path(fname)).string();
      info.guid = std::get<1>(obj);
      info.type = std::get<2>(obj);
      obj_infos.push_back(info);
    }
  }

  if (json && !obj_infos.empty()) {
    std::ofstream out(json_out.c_str());
    if (!out.good()) {
      std::cout << "Unable to open file \"" << json_out
                << "\" for writing. No JSON output written."
                << "\n";
    }

    {
      cereal::JSONOutputArchive ar(out);
      ar(cereal::make_nvp("guid", root_guid));
      ar(cereal::make_nvp("objects", obj_infos));
    }

    out.close();
  }

  return 0;
}
<commit_msg>trying to write normals<commit_after>#include <iostream>
#include <fstream>

#include "../include/extract_objects.hpp"

#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/optional.hpp>
#include <boost/none.hpp>
using boost::optional;
using boost::none;
namespace po = boost::program_options;
namespace fs = boost::filesystem;

boost::filesystem::path make_relative(boost::filesystem::path a_From,
                                      boost::filesystem::path a_To) {
  a_From = boost::filesystem::absolute(a_From);
  a_To = boost::filesystem::absolute(a_To);
  boost::filesystem::path ret;
  boost::filesystem::path::const_iterator itrFrom(a_From.begin()),
      itrTo(a_To.begin());
  // Find common base
  for (boost::filesystem::path::const_iterator toEnd(a_To.end()),
       fromEnd(a_From.end());
       itrFrom != fromEnd && itrTo != toEnd && *itrFrom == *itrTo;
       ++itrFrom, ++itrTo)
    ;
  // Navigate backwards in directory to reach previously found base
  for (boost::filesystem::path::const_iterator fromEnd(a_From.end());
       itrFrom != fromEnd; ++itrFrom) {
    if ((*itrFrom) != ".")
      ret /= "..";
  }
  // Now navigate down the directory branch
  // ret.append( itrTo, a_To.end() );
  for (; itrTo != a_To.end(); ++itrTo) {
    ret /= *itrTo;
  }
  return ret;
}

int main(int argc, char const *argv[]) {
  std::string file_in;
  std::string dir_out;
  std::string json_out;

  po::options_description desc("Graphene command line options");
  desc.add_options()("help,h", "Help message")(
      "input,i", po::value<std::string>(&file_in)->required(),
      "Input ifc file")("output,o", po::value<std::string>(&dir_out),
                        "Output directory")(
      "json,j", po::value<std::string>(&json_out)->default_value(""),
      "Optional JSON index file")("shared,s",
                                  "Make vertices shared between faces");

  // Check for required options.
  po::variables_map vm;
  bool optionsException = false;
  try {
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);
  } catch (std::exception &e) {
    if (!vm.count("help")) {
      std::cout << e.what() << "\n";
    }
    optionsException = true;
  }
  if (optionsException || vm.count("help")) {
    std::cout << desc << "\n";
    return optionsException ? 1 : 0;
  }

  fs::path path_in(file_in);
  if (!fs::exists(path_in)) {
    std::cerr << "File \"" << file_in << "\" does not exist. Aborting.\n";
    return 1;
  }

  bool json = json_out != "";

  fs::path path_out(dir_out);
  if (!fs::exists(path_out)) {
    fs::create_directories(path_out);
  }

  std::string root_guid;
  auto objects =
      ifc_mesh_extract::extract_objects(root_guid, path_in, vm.count("shared"));

  auto filename_out = [=](std::string guid, std::string type) {
    std::string file_part =
        root_guid + "__GUID_" + guid + "__TYPE_" + type + ".obj";
    return (path_out / file_part).string();
  };

  if (!objects.size()) {
    std::cerr << "No objects extracted. Aborting."
              << "\n";
    return 1;
  }

  std::vector<ifc_mesh_extract::object_info> obj_infos;
  fs::path json_path(json_out);
  for (const auto &obj : objects) {
    std::string fname = filename_out(std::get<1>(obj), std::get<2>(obj));
    OpenMesh::IO::Options wopts;
    wopts += OpenMesh::IO::Options::VertexNormal;
    wopts += OpenMesh::IO::Options::FaceNormal;
    if (!OpenMesh::IO::write_mesh(std::get<0>(obj), fname, wopts)) {
      std::cerr << "Unable to write mesh to \"" + fname + "\"";
    }
    if (json) {
      ifc_mesh_extract::object_info info;
      info.path =
          make_relative(json_path.parent_path(), fs::path(fname)).string();
      info.guid = std::get<1>(obj);
      info.type = std::get<2>(obj);
      obj_infos.push_back(info);
    }
  }

  if (json && !obj_infos.empty()) {
    std::ofstream out(json_out.c_str());
    if (!out.good()) {
      std::cout << "Unable to open file \"" << json_out
                << "\" for writing. No JSON output written."
                << "\n";
    }

    {
      cereal::JSONOutputArchive ar(out);
      ar(cereal::make_nvp("guid", root_guid));
      ar(cereal::make_nvp("objects", obj_infos));
    }

    out.close();
  }

  return 0;
}
<|endoftext|>


<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "mojo/public/cpp/application/service_provider_impl.h"

#include "mojo/public/cpp/application/service_connector.h"
#include "mojo/public/cpp/environment/logging.h"

namespace mojo {

ServiceProviderImpl::ServiceProviderImpl() : binding_(this) {
}

ServiceProviderImpl::ServiceProviderImpl(
    InterfaceRequest<ServiceProvider> request)
    : binding_(this, request.Pass()) {
}

ServiceProviderImpl::~ServiceProviderImpl() {
}

void ServiceProviderImpl::Bind(InterfaceRequest<ServiceProvider> request) {
  binding_.Bind(request.Pass());
}

void ServiceProviderImpl::Close() {
  if (binding_.is_bound())
    binding_.Close();
}

void ServiceProviderImpl::ConnectToService(
    const String& service_name,
    ScopedMessagePipeHandle client_handle) {
  // TODO(beng): perhaps take app connection thru ctor so that we can pass
  // ApplicationConnection through?
  bool service_found = service_connector_registry_.ConnectToService(
      nullptr, service_name, &client_handle);
  if (!service_found && fallback_service_provider_) {
    fallback_service_provider_->ConnectToService(service_name,
                                                 client_handle.Pass());
  }
}

void ServiceProviderImpl::SetServiceConnectorForName(
    ServiceConnector* service_connector,
    const std::string& interface_name) {
  service_connector_registry_.SetServiceConnectorForName(service_connector,
                                                         interface_name);
}

}  // namespace mojo
<commit_msg>Fix Sky tests<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "mojo/public/cpp/application/service_provider_impl.h"

#include "mojo/public/cpp/application/service_connector.h"
#include "mojo/public/cpp/environment/logging.h"

namespace mojo {

ServiceProviderImpl::ServiceProviderImpl()
    : binding_(this), fallback_service_provider_(nullptr) {
}

ServiceProviderImpl::ServiceProviderImpl(
    InterfaceRequest<ServiceProvider> request)
    : binding_(this, request.Pass()), fallback_service_provider_(nullptr) {
}

ServiceProviderImpl::~ServiceProviderImpl() {
}

void ServiceProviderImpl::Bind(InterfaceRequest<ServiceProvider> request) {
  binding_.Bind(request.Pass());
}

void ServiceProviderImpl::Close() {
  if (binding_.is_bound())
    binding_.Close();
}

void ServiceProviderImpl::ConnectToService(
    const String& service_name,
    ScopedMessagePipeHandle client_handle) {
  // TODO(beng): perhaps take app connection thru ctor so that we can pass
  // ApplicationConnection through?
  bool service_found = service_connector_registry_.ConnectToService(
      nullptr, service_name, &client_handle);
  if (!service_found && fallback_service_provider_) {
    fallback_service_provider_->ConnectToService(service_name,
                                                 client_handle.Pass());
  }
}

void ServiceProviderImpl::SetServiceConnectorForName(
    ServiceConnector* service_connector,
    const std::string& interface_name) {
  service_connector_registry_.SetServiceConnectorForName(service_connector,
                                                         interface_name);
}

}  // namespace mojo
<|endoftext|>


<commit_before>/*
    Copyright 2010 Google Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

#include "GrTextureCache.h"
#include "GrTexture.h"

GrTextureEntry::GrTextureEntry(const GrTextureKey& key, GrTexture* texture)
        : fKey(key), fTexture(texture) {
    fLockCount = 0;
    fPrev = fNext = NULL;

    // we assume ownership of the texture, and will unref it when we die
    GrAssert(texture);
}

GrTextureEntry::~GrTextureEntry() {
    fTexture->unref();
}

#if GR_DEBUG
void GrTextureEntry::validate() const {
    GrAssert(fLockCount >= 0);
    GrAssert(fTexture);
    fTexture->validate();
}
#endif

///////////////////////////////////////////////////////////////////////////////

GrTextureCache::GrTextureCache(int maxCount, size_t maxBytes) :
        fMaxCount(maxCount),
        fMaxBytes(maxBytes) {
    fEntryCount          = 0;
    fEntryBytes          = 0;
    fClientDetachedCount = 0;
    fClientDetachedBytes = 0;

    fHead = fTail = NULL;
}

GrTextureCache::~GrTextureCache() {
    GrAutoTextureCacheValidate atcv(this);

    this->deleteAll(kFreeTexture_DeleteMode);
}

void GrTextureCache::getLimits(int* maxTextures, size_t* maxTextureBytes) const{
    if (maxTextures) {
        *maxTextures = fMaxCount;
    }
    if (maxTextureBytes) {
        *maxTextureBytes = fMaxBytes;
    }
}

void GrTextureCache::setLimits(int maxTextures, size_t maxTextureBytes) {
    bool smaller = (maxTextures < fMaxCount) || (maxTextureBytes < fMaxBytes);

    fMaxCount = maxTextures;
    fMaxBytes = maxTextureBytes;

    if (smaller) {
        this->purgeAsNeeded();
    }
}

void GrTextureCache::internalDetach(GrTextureEntry* entry,
                                    bool clientDetach) {
    GrTextureEntry* prev = entry->fPrev;
    GrTextureEntry* next = entry->fNext;

    if (prev) {
        prev->fNext = next;
    } else {
        fHead = next;
    }
    if (next) {
        next->fPrev = prev;
    } else {
        fTail = prev;
    }

    // update our stats
    if (clientDetach) {
        fClientDetachedCount += 1;
        fClientDetachedBytes += entry->texture()->sizeInBytes();
    } else {
        fEntryCount -= 1;
        fEntryBytes -= entry->texture()->sizeInBytes();
    }
}

void GrTextureCache::attachToHead(GrTextureEntry* entry,
                                  bool clientReattach) {
    entry->fPrev = NULL;
    entry->fNext = fHead;
    if (fHead) {
        fHead->fPrev = entry;
    }
    fHead = entry;
    if (NULL == fTail) {
        fTail = entry;
    }

    // update our stats
    if (clientReattach) {
        fClientDetachedCount -= 1;
        fClientDetachedBytes -= entry->texture()->sizeInBytes();
    } else {
        fEntryCount += 1;
        fEntryBytes += entry->texture()->sizeInBytes();
    }
}

class GrTextureCache::Key {
    typedef GrTextureEntry T;

    const GrTextureKey& fKey;
public:
    Key(const GrTextureKey& key) : fKey(key) {}

    uint32_t getHash() const { return fKey.hashIndex(); }

    static bool LT(const T& entry, const Key& key) {
        return entry.key() < key.fKey;
    }
    static bool EQ(const T& entry, const Key& key) {
        return entry.key() == key.fKey;
    }
#if GR_DEBUG
    static uint32_t GetHash(const T& entry) {
        return entry.key().hashIndex();
    }
    static bool LT(const T& a, const T& b) {
        return a.key() < b.key();
    }
    static bool EQ(const T& a, const T& b) {
        return a.key() == b.key();
    }
#endif
};

GrTextureEntry* GrTextureCache::findAndLock(const GrTextureKey& key) {
    GrAutoTextureCacheValidate atcv(this);

    GrTextureEntry* entry = fCache.find(key);
    if (entry) {
        this->internalDetach(entry, false);
        this->attachToHead(entry, false);
        // mark the entry as "busy" so it doesn't get purged
        entry->lock();
    }
    return entry;
}

GrTextureEntry* GrTextureCache::createAndLock(const GrTextureKey& key,
                                              GrTexture* texture) {
    GrAutoTextureCacheValidate atcv(this);

    GrTextureEntry* entry = new GrTextureEntry(key, texture);

    this->attachToHead(entry, false);
    fCache.insert(key, entry);

#if GR_DUMP_TEXTURE_UPLOAD
    GrPrintf("--- add texture to cache %p, count=%d bytes= %d %d\n",
             entry, fEntryCount, texture->sizeInBytes(), fEntryBytes);
#endif

    // mark the entry as "busy" so it doesn't get purged
    entry->lock();
    this->purgeAsNeeded();
    return entry;
}

void GrTextureCache::detach(GrTextureEntry* entry) {
    internalDetach(entry, true);
    fCache.remove(entry->fKey, entry);
}

void GrTextureCache::reattachAndUnlock(GrTextureEntry* entry) {
    attachToHead(entry, true);
    fCache.insert(entry->key(), entry);
    unlock(entry);
}

void GrTextureCache::unlock(GrTextureEntry* entry) {
    GrAutoTextureCacheValidate atcv(this);

    GrAssert(entry);
    GrAssert(entry->isLocked());
    GrAssert(fCache.find(entry->key()));

    entry->unlock();
    this->purgeAsNeeded();
}

void GrTextureCache::purgeAsNeeded() {
    GrAutoTextureCacheValidate atcv(this);

    GrTextureEntry* entry = fTail;
    while (entry) {
        if (fEntryCount <= fMaxCount && fEntryBytes <= fMaxBytes) {
            break;
        }

        GrTextureEntry* prev = entry->fPrev;
        if (!entry->isLocked()) {
            // remove from our cache
            fCache.remove(entry->fKey, entry);

            // remove from our llist
            this->internalDetach(entry, false);

#if GR_DUMP_TEXTURE_UPLOAD
            GrPrintf("--- ~texture from cache %p [%d %d]\n", entry->texture(),
                     entry->texture()->contentWidth(),
                     entry->texture()->contentHeight());
#endif
            delete entry;
        }
        entry = prev;
    }
}

void GrTextureCache::deleteAll(DeleteMode mode) {
    GrAssert(!fClientDetachedCount);
    GrAssert(!fClientDetachedBytes);

    GrTextureEntry* entry = fHead;
    while (entry) {
        GrAssert(!entry->isLocked());

        GrTextureEntry* next = entry->fNext;
        if (kAbandonTexture_DeleteMode == mode) {
            entry->texture()->abandon();
        }
        delete entry;
        entry = next;
    }

    fCache.removeAll();
    fHead = fTail = NULL;
    fEntryCount = 0;
    fEntryBytes = 0;
}

///////////////////////////////////////////////////////////////////////////////

#if GR_DEBUG
static int countMatches(const GrTextureEntry* head, const GrTextureEntry* target) {
    const GrTextureEntry* entry = head;
    int count = 0;
    while (entry) {
        if (target == entry) {
            count += 1;
        }
        entry = entry->next();
    }
    return count;
}

void GrTextureCache::validate() const {
    GrAssert(!fHead == !fTail);
    GrAssert(!fEntryCount == !fEntryBytes);
    GrAssert(!fClientDetachedBytes == !fClientDetachedBytes);
    GrAssert(fClientDetachedBytes <= fEntryBytes);
    GrAssert(fClientDetachedCount <= fEntryCount);
    GrAssert((fEntryCount - fClientDetachedCount) == fCache.count());
    GrAssert(fEntryBytes >= 0);
    GrAssert(fEntryCount >= 0);
    GrAssert(fClientDetachedCount >= 0);
    GrAssert(fClientDetachedBytes >= 0);

    fCache.validate();

    GrTextureEntry* entry = fHead;
    int count = 0;
    size_t bytes = 0;
    while (entry) {
        entry->validate();
        GrAssert(fCache.find(entry->key()));
        count += 1;
        bytes += entry->texture()->sizeInBytes();
        entry = entry->fNext;
    }
    GrAssert(count == fEntryCount - fClientDetachedCount);
    GrAssert(bytes == fEntryBytes  - fClientDetachedBytes);

    count = 0;
    for (entry = fTail; entry; entry = entry->fPrev) {
        count += 1;
    }
    GrAssert(count == fEntryCount - fClientDetachedCount);

    for (int i = 0; i < count; i++) {
        int matches = countMatches(fHead, fCache.getArray()[i]);
        GrAssert(1 == matches);
    }
}
#endif

<commit_msg>fix warning about size_t >= 0 (which must always be true)<commit_after>/*
    Copyright 2010 Google Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

#include "GrTextureCache.h"
#include "GrTexture.h"

GrTextureEntry::GrTextureEntry(const GrTextureKey& key, GrTexture* texture)
        : fKey(key), fTexture(texture) {
    fLockCount = 0;
    fPrev = fNext = NULL;

    // we assume ownership of the texture, and will unref it when we die
    GrAssert(texture);
}

GrTextureEntry::~GrTextureEntry() {
    fTexture->unref();
}

#if GR_DEBUG
void GrTextureEntry::validate() const {
    GrAssert(fLockCount >= 0);
    GrAssert(fTexture);
    fTexture->validate();
}
#endif

///////////////////////////////////////////////////////////////////////////////

GrTextureCache::GrTextureCache(int maxCount, size_t maxBytes) :
        fMaxCount(maxCount),
        fMaxBytes(maxBytes) {
    fEntryCount          = 0;
    fEntryBytes          = 0;
    fClientDetachedCount = 0;
    fClientDetachedBytes = 0;

    fHead = fTail = NULL;
}

GrTextureCache::~GrTextureCache() {
    GrAutoTextureCacheValidate atcv(this);

    this->deleteAll(kFreeTexture_DeleteMode);
}

void GrTextureCache::getLimits(int* maxTextures, size_t* maxTextureBytes) const{
    if (maxTextures) {
        *maxTextures = fMaxCount;
    }
    if (maxTextureBytes) {
        *maxTextureBytes = fMaxBytes;
    }
}

void GrTextureCache::setLimits(int maxTextures, size_t maxTextureBytes) {
    bool smaller = (maxTextures < fMaxCount) || (maxTextureBytes < fMaxBytes);

    fMaxCount = maxTextures;
    fMaxBytes = maxTextureBytes;

    if (smaller) {
        this->purgeAsNeeded();
    }
}

void GrTextureCache::internalDetach(GrTextureEntry* entry,
                                    bool clientDetach) {
    GrTextureEntry* prev = entry->fPrev;
    GrTextureEntry* next = entry->fNext;

    if (prev) {
        prev->fNext = next;
    } else {
        fHead = next;
    }
    if (next) {
        next->fPrev = prev;
    } else {
        fTail = prev;
    }

    // update our stats
    if (clientDetach) {
        fClientDetachedCount += 1;
        fClientDetachedBytes += entry->texture()->sizeInBytes();
    } else {
        fEntryCount -= 1;
        fEntryBytes -= entry->texture()->sizeInBytes();
    }
}

void GrTextureCache::attachToHead(GrTextureEntry* entry,
                                  bool clientReattach) {
    entry->fPrev = NULL;
    entry->fNext = fHead;
    if (fHead) {
        fHead->fPrev = entry;
    }
    fHead = entry;
    if (NULL == fTail) {
        fTail = entry;
    }

    // update our stats
    if (clientReattach) {
        fClientDetachedCount -= 1;
        fClientDetachedBytes -= entry->texture()->sizeInBytes();
    } else {
        fEntryCount += 1;
        fEntryBytes += entry->texture()->sizeInBytes();
    }
}

class GrTextureCache::Key {
    typedef GrTextureEntry T;

    const GrTextureKey& fKey;
public:
    Key(const GrTextureKey& key) : fKey(key) {}

    uint32_t getHash() const { return fKey.hashIndex(); }

    static bool LT(const T& entry, const Key& key) {
        return entry.key() < key.fKey;
    }
    static bool EQ(const T& entry, const Key& key) {
        return entry.key() == key.fKey;
    }
#if GR_DEBUG
    static uint32_t GetHash(const T& entry) {
        return entry.key().hashIndex();
    }
    static bool LT(const T& a, const T& b) {
        return a.key() < b.key();
    }
    static bool EQ(const T& a, const T& b) {
        return a.key() == b.key();
    }
#endif
};

GrTextureEntry* GrTextureCache::findAndLock(const GrTextureKey& key) {
    GrAutoTextureCacheValidate atcv(this);

    GrTextureEntry* entry = fCache.find(key);
    if (entry) {
        this->internalDetach(entry, false);
        this->attachToHead(entry, false);
        // mark the entry as "busy" so it doesn't get purged
        entry->lock();
    }
    return entry;
}

GrTextureEntry* GrTextureCache::createAndLock(const GrTextureKey& key,
                                              GrTexture* texture) {
    GrAutoTextureCacheValidate atcv(this);

    GrTextureEntry* entry = new GrTextureEntry(key, texture);

    this->attachToHead(entry, false);
    fCache.insert(key, entry);

#if GR_DUMP_TEXTURE_UPLOAD
    GrPrintf("--- add texture to cache %p, count=%d bytes= %d %d\n",
             entry, fEntryCount, texture->sizeInBytes(), fEntryBytes);
#endif

    // mark the entry as "busy" so it doesn't get purged
    entry->lock();
    this->purgeAsNeeded();
    return entry;
}

void GrTextureCache::detach(GrTextureEntry* entry) {
    internalDetach(entry, true);
    fCache.remove(entry->fKey, entry);
}

void GrTextureCache::reattachAndUnlock(GrTextureEntry* entry) {
    attachToHead(entry, true);
    fCache.insert(entry->key(), entry);
    unlock(entry);
}

void GrTextureCache::unlock(GrTextureEntry* entry) {
    GrAutoTextureCacheValidate atcv(this);

    GrAssert(entry);
    GrAssert(entry->isLocked());
    GrAssert(fCache.find(entry->key()));

    entry->unlock();
    this->purgeAsNeeded();
}

void GrTextureCache::purgeAsNeeded() {
    GrAutoTextureCacheValidate atcv(this);

    GrTextureEntry* entry = fTail;
    while (entry) {
        if (fEntryCount <= fMaxCount && fEntryBytes <= fMaxBytes) {
            break;
        }

        GrTextureEntry* prev = entry->fPrev;
        if (!entry->isLocked()) {
            // remove from our cache
            fCache.remove(entry->fKey, entry);

            // remove from our llist
            this->internalDetach(entry, false);

#if GR_DUMP_TEXTURE_UPLOAD
            GrPrintf("--- ~texture from cache %p [%d %d]\n", entry->texture(),
                     entry->texture()->contentWidth(),
                     entry->texture()->contentHeight());
#endif
            delete entry;
        }
        entry = prev;
    }
}

void GrTextureCache::deleteAll(DeleteMode mode) {
    GrAssert(!fClientDetachedCount);
    GrAssert(!fClientDetachedBytes);

    GrTextureEntry* entry = fHead;
    while (entry) {
        GrAssert(!entry->isLocked());

        GrTextureEntry* next = entry->fNext;
        if (kAbandonTexture_DeleteMode == mode) {
            entry->texture()->abandon();
        }
        delete entry;
        entry = next;
    }

    fCache.removeAll();
    fHead = fTail = NULL;
    fEntryCount = 0;
    fEntryBytes = 0;
}

///////////////////////////////////////////////////////////////////////////////

#if GR_DEBUG
static int countMatches(const GrTextureEntry* head, const GrTextureEntry* target) {
    const GrTextureEntry* entry = head;
    int count = 0;
    while (entry) {
        if (target == entry) {
            count += 1;
        }
        entry = entry->next();
    }
    return count;
}

#if GR_DEBUG
static bool both_zero_or_nonzero(int count, size_t bytes) {
    return (count == 0 && bytes == 0) || (count > 0 && bytes > 0);
}
#endif

void GrTextureCache::validate() const {
    GrAssert(!fHead == !fTail);
    GrAssert(both_zero_or_nonzero(fEntryCount, fEntryBytes));
    GrAssert(both_zero_or_nonzero(fClientDetachedCount, fClientDetachedBytes));
    GrAssert(fClientDetachedBytes <= fEntryBytes);
    GrAssert(fClientDetachedCount <= fEntryCount);
    GrAssert((fEntryCount - fClientDetachedCount) == fCache.count());

    fCache.validate();

    GrTextureEntry* entry = fHead;
    int count = 0;
    size_t bytes = 0;
    while (entry) {
        entry->validate();
        GrAssert(fCache.find(entry->key()));
        count += 1;
        bytes += entry->texture()->sizeInBytes();
        entry = entry->fNext;
    }
    GrAssert(count == fEntryCount - fClientDetachedCount);
    GrAssert(bytes == fEntryBytes  - fClientDetachedBytes);

    count = 0;
    for (entry = fTail; entry; entry = entry->fPrev) {
        count += 1;
    }
    GrAssert(count == fEntryCount - fClientDetachedCount);

    for (int i = 0; i < count; i++) {
        int matches = countMatches(fHead, fCache.getArray()[i]);
        GrAssert(1 == matches);
    }
}
#endif

<|endoftext|>