Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

256 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

English | 简体中文

Huawei Cloud C++ Software Development Kit (C++ SDK)

GitHub Release License

The Huawei Cloud C++ SDK allows you to easily work with Huawei Cloud services such as Elastic Compute Service (ECS) and Virtual Private Cloud (VPC) without the need to handle API related tasks.

This document introduces how to obtain and use Huawei Cloud C++ SDK.

Project Description

  • The current SDK code is automatically generated by an internal Huawei Cloud team using open source components (openapi-generator), and is directly submitted to the GitHub community by the Huawei Cloud team. For the sake of implementation consistency and version compatibility, we cannot currently accept PRs from developers.
  • We are currently considering the feasibility of operating the SDK in accordance with open source community standards, which will take some time. Meanwhile, we will respond to and handle issues raised by developers timely.

Requirements

  • To use Huawei Cloud C++ SDK, you must have Huawei Cloud account as well as the Access Key (AK) and Secret key (SK) of the Huawei Cloud account. You can create an Access Key in the Huawei Cloud console. For more information, see My Credentials.

  • To use Huawei Cloud C++ SDK to access the APIs of specific service, please make sure you do have activated the service in Huawei Cloud console if needed.

  • Huawei Cloud C++ SDK requires C++ 14 or later, and requires CMake 3.10 or later.

Install C++ SDK

You can get the SDK version information through SDK center or Github Releases.

Dependent Third-Party Libraries

curl, boost, cpprestsdk, spdlog, openssl, rttr

Install SDK on Linux platform

Step 1: Install third-party libraries

The required third-party packages are available in great part of package management tools of different OS.

Take Debian/Ubuntu system for example, you could run the following commands:

sudo apt-get install libcurl4-openssl-dev libboost-all-dev libssl-dev libcpprest-dev librttr-dev cmake g++

spdlog needs to be installed from source code to generate the corresponding dynamic library. Version v1.17.0 is recommended. If you have other versions of spdlog installed locally, it is advised to refer to the official documentation for source installation: https://github.com/gabime/spdlog.

git clone -b v1.17.0 https://github.com/gabime/spdlog.git
cd spdlog
mkdir build
cd build
cmake -DCMAKE_POSITION_INDEPENDENT_CODE=ON -DBUILD_SHARED_LIBS=ON ..  
make
sudo make install

For services that use BSON (kvs), install libbson and configure LIBBSON_INCLUDE_DIRS and LIBBSON_LIBRARY_DIRS to specify the header file path and library file path, respectively.

sudo apt-get install libbson-1.0

Step 2: Build and install SDK

By default, a service is constructed. The following example uses the v3 version of the CCE service.

git clone https://github.com/huaweicloud/huaweicloud-sdk-cpp-v3.git
cd huaweicloud-sdk-cpp-v3
mkdir build
cd build
cmake -DBUILD_SERVICE=cce -DSERVICE_VERSION=v3 ..
make
sudo make install

After the preceding commands completed, the installation directory of C++ SDK is /usr/local.

Special Notes

The libcore in the output may conflict with the names of other dynamic libraries. To avoid conflicts, you can manually rename it in the source code before building.
The following example demonstrates compiling the vpc package, where the output is renamed to core_change_name_demo.

1、Modified core to core_change_name_demo in /huaweicloud-sdk-cpp-v3/core/CMakeLists.txt. All changes are marked with comments.

cmake_minimum_required (VERSION 3.10)

project(core)

if(CMAKE_HOST_WIN32)
    add_compile_options(-bigobj)
else()
    set(cxx_base_flags "${cxx_base_flags} -bigobj")
    set(cpprestsdk_DIR /usr/lib/${CMAKE_LIBRARY_ARCHITECTURE}/cmake/)
endif()

set(CMAKE_BUILD_TYPE Debug)

find_package(OpenSSL REQUIRED)
find_package(spdlog REQUIRED)
find_package(cpprestsdk REQUIRED)
find_package(CURL REQUIRED)
# Update require components as necessary
if(CMAKE_HOST_WIN32)
    find_package(Boost REQUIRED COMPONENTS ${Boost_THREAD_LIBRARY} ${Boost_SYSTEM_LIBRARY} ${Boost_REGEX_LIBRARY} ${Boost_DATE_TIME_LIBRARY} ${Boost_PROGRAM_OPTIONS_LIBRARY} ${Boost_FILESYSTEM_LIBRARY})
else()
    find_package(Boost REQUIRED COMPONENTS filesystem thread system regex date_time program_options)
endif()

if(ENABLE_BSON)
    file(GLOB source_file "src/*.cpp" "src/auth/*.cpp" "src/http/*.cpp" "src/utils/*.cpp" "src/exception/*.cpp" "src/bson/*.cpp" "src/bson/impl/*.cpp")
    file(GLOB core_bson_header ${CMAKE_CURRENT_SOURCE_DIR}/include/huaweicloud/core/bson/*.h)
    file(GLOB core_bson_impl_header ${CMAKE_CURRENT_SOURCE_DIR}/include/huaweicloud/core/bson/impl/*.h)
else()
    file(GLOB source_file "src/*.cpp" "src/auth/*.cpp" "src/http/*.cpp" "src/utils/*.cpp" "src/exception/*.cpp")
endif ()
file(GLOB core_header ${CMAKE_CURRENT_SOURCE_DIR}/include/huaweicloud/core/*.h)
file(GLOB core_auth_header ${CMAKE_CURRENT_SOURCE_DIR}/include/huaweicloud/core/auth/*.h)
file(GLOB core_exception_header ${CMAKE_CURRENT_SOURCE_DIR}/include/huaweicloud/core/exception/*.h)
file(GLOB core_http_header ${CMAKE_CURRENT_SOURCE_DIR}/include/huaweicloud/core/http/*.h)
file(GLOB core_utils_header ${CMAKE_CURRENT_SOURCE_DIR}/include/huaweicloud/core/utils/*.h)

if(ENABLE_BSON)
    # Modifications 1
    add_library(core_change_name_demo ${LIB_TYPE}
            ${source_file}
            ${core_header}
            ${core_auth_header}
            ${core_exception_header}
            ${core_http_header}
            ${core_utils_header}
            ${core_bson_header}
            ${core_bson_impl_header}
            )
else()
    # Modifications 2
    add_library(core_change_name_demo ${LIB_TYPE}
            ${source_file}
            ${core_header}
            ${core_auth_header}
            ${core_exception_header}
            ${core_http_header}
            ${core_utils_header}
            )
endif()
# Modifications 3
set_target_properties(core_change_name_demo
        PROPERTIES
        LINKER_LANGUAGE CXX
        ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib
        LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib
        RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
        # Modifications 4
        OUTPUT_NAME core_change_name_demo
        )

if(${LIB_TYPE} STREQUAL "SHARED")
    # Modifications 5
    set_target_properties(core_change_name_demo
            PROPERTIES
            DEFINE_SYMBOL HUAWEICLOUD_CORE_SHARED)
endif()


if(ENABLE_BSON)
    if(NOT LIBBSON_DIR)
        message(FATAL_ERROR "Please manual set variable LIBBSON_DIR for search libbson root dir")
    endif()
    set(LIBBSON_LIBRARY_DIR ${LIBBSON_DIR}/lib)
    set(LIBBSON_INCLUDE_DIR ${LIBBSON_DIR}/include/libbson-1.0)
    # Modifications 6
    target_include_directories(core_change_name_demo PUBLIC ${LIBBSON_INCLUDE_DIR})
    target_link_libraries(core_change_name_demo PUBLIC bson-1.0)
    target_link_directories(core_change_name_demo PUBLIC ${LIBBSON_LIBRARY_DIR})
endif()
# Modifications 7
target_include_directories(core_change_name_demo PUBLIC
        ${CMAKE_CURRENT_SOURCE_DIR}/include
        )
# Modifications 8
if(CMAKE_HOST_WIN32)
    target_link_libraries(core_change_name_demo PUBLIC
            spdlog::spdlog
            OpenSSL::SSL
            bcrypt
            ${Boost_LIBRARIES}
            ${CURL_LIBRARIES}
            cpprestsdk::cpprest
            )
else()
# Modifications 9
    target_link_libraries(core_change_name_demo PUBLIC
            spdlog::spdlog
            OpenSSL::SSL
            crypto
            ${Boost_LIBRARIES}
            ${CURL_LIBRARIES}
            cpprest
            )
endif()

install(FILES ${core_header}
        DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/huaweicloud/core)
install(FILES ${core_auth_header}
        DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/huaweicloud/core/auth)
install(FILES ${core_exception_header}
        DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/huaweicloud/core/exception)
install(FILES ${core_http_header}
        DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/huaweicloud/core/http)
install(FILES ${core_utils_header}
        DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/huaweicloud/core/utils)
# Modifications 10
install(TARGETS core_change_name_demo
        ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
        LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
        RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
        )
if(ENABLE_BSON)
install(FILES ${core_bson_header}
        DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/huaweicloud/core/bson)
install(FILES ${core_bson_impl_header}
        DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/huaweicloud/core/bson/impl)
endif()

2、Modified /huaweicloud-sdk-cpp-v3/vpc/src/v2/CMakeLists.txt to change the linked library name from core to core_change_name_demo. The modifications are marked with comments.

cmake_minimum_required (VERSION 3.10)

#PROJECT's NAME
project(vpc_v2)

if(CMAKE_HOST_WIN32)
    add_compile_options(-bigobj)
else()
    set(cxx_base_flags "${cxx_base_flags} -bigobj")
endif()

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DBOOST_UUID_FORCE_AUTO_LINK")

if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE Release)
endif()

#HEADER FILES
file(GLOB service_client_header
        ${CMAKE_SOURCE_DIR}/vpc/include/huaweicloud/vpc/v2/*.h)
file(GLOB service_model_header
        ${CMAKE_SOURCE_DIR}/vpc/include/huaweicloud/vpc/v2/model/*.h)
#SOURCE FILES
file(GLOB source_file
        ${CMAKE_SOURCE_DIR}/vpc/src/v2/*.cpp
        ${CMAKE_SOURCE_DIR}/vpc/src/v2/model/*.cpp)

add_library(vpc_v2 ${LIB_TYPE}
        ${source_file}
        ${service_client_header}
        ${service_model_header})

set_target_properties(vpc_v2
        PROPERTIES
        LINKER_LANGUAGE CXX
        ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib
        LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib
        RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
        OUTPUT_NAME vpc_v2
        )

if(CMAKE_HOST_WIN32)
    if(${LIB_TYPE} STREQUAL "SHARED")
        set_target_properties(vpc_v2
            PROPERTIES
            DEFINE_SYMBOL HUAWEICLOUD_VPC_V2_SHARED)
    endif()
else()
    if(${LIB_TYPE} STREQUAL "SHARED")
        set_target_properties(vpc_v2
            PROPERTIES
            DEFINE_SYMBOL HUAWEICLOUD_VPC_V2_EXPORT)
    endif()
endif()

target_include_directories(vpc_v2 PUBLIC
        ${CMAKE_SOURCE_DIR}/vpc/include
        )
# Modification
target_link_libraries(vpc_v2 PUBLIC
        core_change_name_demo)

if(ENABLE_RTTR)
    if(NOT CMAKE_HOST_WIN32)
        set(rttr_DIR /home/nfs/rttr/rttr-0.9.6/build/install/share/rttr/cmake)
    endif()
    find_package(rttr CONFIG REQUIRED)
    target_link_libraries(vpc_v2 PUBLIC
            RTTR::Core)
endif()

install(FILES ${service_client_header}
        DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/huaweicloud/vpc/v2)
install(FILES ${service_model_header}
        DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/huaweicloud/vpc/v2/model)
install(TARGETS vpc_v2
        ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
        LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
        RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)

Install SDK on Windows platform

Step 1: Install vcpkg and install third-part libraries by vcpkg:

vcpkg install curl cpprestsdk boost openssl spdlog

For services that use BSON (kvs), install libbson and configure LIBBSON_DIR to specify libbson root path.

vcpkg install libbson

Step 2: Build By CLion

  1. open directory huaweicloud-sdk-cpp-v3 by clion

  2. choose File -> Settings

  3. choose Build, Execution, Devloyment -> CMake

  4. add -DCMAKE_TOOLCHAIN_FILE={your vcpkg install dir}/scripts/buildsystems/vcpkg.cmake in CMake options

  5. click CMakeLists.txt and choose Load CMake Project

  6. Configure compilation toolchain of clion as MSVC: Select Toolchain as Visual Studio on the CMake configuration page in step 3, and you cannot select other compilers such as mingw (the windows platform relies on the msvc compiler, Compiling with other compilers such as mingw will report an error). In addition, the user can also choose whether the compiled binary file is in Debug mode or Release mode, and select Build Type to make a drop-down selection.

  7. Configure the architecture and platform of the target file: the windows platform supports compiling sdk link library files of different CPU architectures (x64, x86), users can configure according to actual needs, click Build, Execution, DeploymentToolchains, in the Architecture option, you can drop down to select the supported CPU architecture.

  8. choose Build and start compile

Step 3: Install C++ SDK

choose Build -> Install after compilation.

After the preceding commands completed, the installation directory of C++ SDK is C:\Program File (x86)\huaweicloud-sdk-cpp-v3.

Code example

  • The following example shows how to query a list of VPC in a specific region, you need to substitute your real {Service}Client for VpcClient in actual use.

    • Hard-coding ak and sk for authentication into the code or storing it in plain text has a great security risk. It is recommended to store the ciphertext in the profile or environment variables and decrypt it when used to ensure security.
  • In this example, ak and sk are stored in environment variables. Please configure the environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK before running this example.

#include <cstdio>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <string>
#include <huaweicloud/core/exception/Exceptions.h>
#include <huaweicloud/core/Client.h>
#include <huaweicloud/vpc/v2/VpcClient.h>
 
using namespace HuaweiCloud::Sdk;
using namespace HuaweiCloud::Sdk::Core;
using namespace HuaweiCloud::Sdk::Core::Exception;
 
int main(void)
{   
    std::string ak;
    std::string sk;
#if defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
    ak = getenv("HUAWEICLOUD_SDK_AK");
    sk = getenv("HUAWEICLOUD_SDK_SK");    
#elif defined(linux) || defined(__linux) || defined(__linux__)
    char* envVar; 
    #define INIT_ENV_VAR(ID, NAME)               \
    do {                                         \
        if ((envVar = secure_getenv(#NAME))) {   \
            ID = std::string(envVar);            \
        }                                        \
    } while (0)
    INIT_ENV_VAR(ak, HUAWEICLOUD_SDK_AK);
    INIT_ENV_VAR(sk, HUAWEICLOUD_SDK_SK);
    #undef INIT_ENV_VAR
#endif
    // Initialize AK/SK module
    auto basicCredentials = std::make_unique<BasicCredentials>();
    basicCredentials->withAk(ak)
            .withSk(sk)
            .withProjectId("{your project id}");
     
    // Initialize HTTP config
    HttpConfig httpConfig = HttpConfig();
    // Configure VpcClient instance
    std::unique_ptr<Vpc::V2::VpcClient> vpcApi_v2 = Vpc::V2::VpcClient::newBuilder()
            .withCredentials(std::unique_ptr<Credentials>(basicCredentials.release()))
            .withHttpConfig(httpConfig)
            .withEndPoint("{your endpoint}")
            .build();
 
    // Initialize request parameters
    Vpc::V2::Model::ListVpcsRequest listRequest;
    try {
        std::string responseBody;
        // Creat an API request and get response
        std::cout << "************ListVpc***********" << std::endl;
        std::shared_ptr<Vpc::V2::Model::ListVpcsResponse> listRes = 
            vpcApi_v2->listVpcs(listRequest);
        responseBody = listRes->getHttpBody();
        std::cout << responseBody << std::endl;
    } catch (HostUnreachableException& e) { // handle exception
        std::cout << e.what() << std::endl;
    } catch (SslHandShakeException& e) {
        std::cout << e.what() << std::endl;
    } catch (RetryOutageException& e) {
        std::cout << e.what() << std::endl;
    } catch (CallTimeoutException& e) {
        std::cout << e.what() << std::endl;
    } catch (ServiceResponseException& e) {
        std::cout << "StatusCode: " << e.getStatusCode() << std::endl;
        std::cout << "ErrorCode: " << e.getErrorCode() << std::endl;
        std::cout << "ErrorMsg: " << e.getErrorMsg() << std::endl;
        std::cout << "RequestId: " << e.getRequestId() << std::endl;
    } catch (std::exception &e) {
        std::cout << "Catch an unexpected exception: " << e.what() << std::endl;
    }
    return 0;
}

If you want to run the example on Linux platform, please copy commands above and save as vpc_test.cpp, then build with the following command:

$ g++ -o vpc_test vpc_test.cpp --std=c++14 -lvpc_v2 -lcore -lcrypto -lboost_system -lcpprest
$ ./vpc_test
# response
$

If you use cmake to manage projects under Windows, you need to introduce the relevant dependencies of the sdk core package and service package in CMakeLists.txt. You can refer to the following CMakeLists.txt file:

cmake_minimum_required(VERSION 3.16)
project(demo)
find_package(CURL REQUIRED)
set(CMAKE_CXX_STANDARD 14)

set(LINK_DIR "C:/Program Files (x86)/huaweicloud_cpp_sdk_v3/bin;")
set(BIN_DIR "C:/Program Files (x86)/huaweicloud_cpp_sdk_v3/lib;")
set(SERVICE_DIR "C:/Program Files (x86)/huaweicloud_cpp_sdk_v3/include;")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DBOOST_UUID_FORCE_AUTO_LINK")

link_directories(${BIN_DIR})
include_directories(${SERVICE_DIR})
add_compile_options("$<$<C_COMPILER_ID:MSVC>:/utf-8>")
add_compile_options("$<$<CXX_COMPILER_ID:MSVC>:/utf-8>")

add_executable(demo main.cpp)
target_link_libraries(demo PUBLIC core vpc_v2)

Online Debugging

API Explorer provides api retrieval, SDK samples and online debugging, supports full fast retrieval, visual debugging, help document viewing, and online consultation.

Changelog

Detailed changes for each released version are documented in the CHANGELOG.md.

User Manual 🔝

1. Client Configuration 🔝

1.1 Default Configuration 🔝

// Use default configuration
HttpConfig httpConfig = HttpConfig();

1.2 Network Proxy 🔝

// Use network proxy if needed
httpConfig.setProxyProtocol("http");
httpConfig.setProxyHost("proxy.com");
httpConfig.setProxyPort("8080");
// In this example, username and password are stored in environment variables. Please configure the environment variables PROXY_USERNAME and PROXY_PASSWORD before running this example.
httpConfig.setProxyUser(getenv("USENAME"));
httpConfig.setProxyPassword(getenv("PASSWORD"));

1.3 Timeout Configuration 🔝

// The default connection timeout is 60 seconds, the default read timeout is 120 seconds. You could change it if needed.
httpConfig.setConnectTimeout(60);
httpConfig.setReadTimeout(120);

1.4 SSL Certification 🔝

// Skip SSL certification checking while using https protocol if needed
httpConfig.setIgnoreSslVerification(true);

2. Credentials Configuration 🔝

There are two types of Huawei Cloud services, regional services and global services.

Global services only contain IAM.

For regional services' authentication, project_id is required.

For global services' authentication, domain_id is required.

Parameter description:

  • ak is the access key ID for your account.
  • sk is the secret access key for your account.
  • project_id is the ID of your project depending on your region which you want to operate.
  • domain_id is the account ID of Huawei Cloud.
  • security_token is the security token when using temporary AK/SK.

2.1 Use Permanent AK&SK 🔝

// Regional services
auto basicCredentials = std::make_unique<BasicCredentials>(); 
basicCredentials->withAk(ak)
    .withSk(sk)
    .withProjectId(projectId);

// Global services
auto globalCredentials = std::make_unique<GlobalCredentials>();
globalCredentials->withAk(ak)
    .withSk(sk)
    .withDomainId(domainId);

Notice:

  • projectId/domainId supports automatic acquisition in version 0.0.26-beta or later, if you want to use this feature, you need to provide the ak and sk of your account and the id of the region, and then build your client instance with method WithRegion(), detailed example could refer to 3.2 Initialize client with specified Region

2.2 Use Temporary AK&SK 🔝

It's required to obtain temporary AK&SK and security token first, which could be obtained through permanent AK&SK or through an agency.

// Regional services
auto basicCredentials = std::make_unique<BasicCredentials>(); 
basicCredentials->withAk(ak)
    .withSk(sk)
    .withProjectId(projectId)
    .withSecurityToken(securityToken);

// Global services
auto globalCredentials = std::make_unique<GlobalCredentials>();
globalCredentials->withAk(ak)
    .withSk(sk)
    .withDomainId(domainId)
    .withSecurityToken(securityToken);

3. Client Initialization 🔝

3.1 Initialize the {Service}Client with specified Endpoint 🔝

// Initialize specified service client instance, take VpcClient for example
std::unique_ptr<Vpc::V2::VpcClient> vpcApi_v2 = Vpc::V2::VpcClient::newBuilder()
    .withCredentials(basicCredentials)
    .withHttpConfig(httpConfig)
    .withEndPoint(endpoint)
    .build();

where:

  • endpoint varies by services and regions, see Regions and Endpoints to obtain correct endpoint.
  • When you meet some trouble in getting projectId using the specified region way, you could use this way instead.

3.2 Initialize the {Service}Client with specified Region (Recommended) 🔝

  • Region Services
// add dependency for the {{Service}}Region
#include <huaweicloud/ecs/v2/EcsRegion.h>
using namespace HuaweiCloud::Sdk::Ecs::V2;

//  Initialize the credentials, projectId or domainId could be unassigned in this situation, take initializing BasicCredentials for example
auto auth = std::make_unique<BasicCredentials>();
auth->withAk(ak)
        .withSk(sk);
// Initialize specified New{Service}Client, take initializing the region service ECS for example
auto client = EcsClient::newBuilder()
                .withCredentials(std::unique_ptr<Credentials>(auth.release()))
                .withHttpConfig(httpConfig)
                .withFileLog(R"(.\log.txt)", true)
                .withStreamLog(true)
                .withRegion(EcsRegion::valueOf("cn-east-2"))
                .build();
  • Global Services
// add dependency for the {{Service}}Region
#include <huaweicloud/devstar/v1/DevstarRegion.h>
#include <huaweicloud/devstar/v1/DevstarClient.h>
using namespace HuaweiCloud::Sdk::Devstar::V1;

auto auth = std::make_unique<GlobalCredentials>();
auth->withAk(ak).withSk(sk);

// Initialize the credentials, projectId or domainId could be unassigned in this situation, take initializing GlobalCredentials for example
auto client = DevStarClient::newBuilder()
            .withCredentials(std::unique_ptr<Credentials>(auth.release()))
            .withHttpConfig(httpConfig)
            .withFileLog(R"(.\log.txt)", true)
            .withStreamLog(true)
            .withRegion(DevstarRegion::valueOf("cn-east-2"))
            .build();

Notice:

  • If you use region to initialize {Service}Client, projectId/domainId supports automatic acquisition, you don't need to configure it when initializing Credentials.
  • Multiple ProjectId situation is not supported.
  • Supported region list: af-south-1, ap-southeast-1, ap-southeast-2, ap-southeast-3, cn-east-2, cn-east-3, cn-north-1, cn-north-4, cn-south-1, cn-southwest-2, ru-northwest-2. You may get exception such as Unsupported regionId if your region don't in the list above.

Comparison of the two ways:

Initialization Advantages Disadvantage
Specified Endpoint The API can be invoked successfully once it has been published in the environment. You need to prepare projectId and endpoint yourself.
Specified Region No need for projectId and endpoint, it supports automatic acquisition if you configure it in the right way. The supported services and regions are limited.

3.3 Initialize the client with specified User Agent 🔝

Additional information will be appended to the User-Agent in the request header by default since v3.1.187. It is used by service to identify what SDK language, C++ version, and platform info a client is using to call into their service, and a random identifier will be generated and appended to the User-Agent. The identifier will be stored in the user's home directory, as ~/.huaweicloud/application_id on Linux and C:\Users\USER_NAME\.huaweicloud\application_id on Windows.

The above information will be used to protect the security of your and your users' Huawei Cloud accounts.

You can disable this automatic User-Agent augmentation by explicitly setting a custom User-Agent header value. The value is recommended to be less than 50 characters and should use US-ASCII visible characters:

// Append custom User-Agent information to replace the default
HttpConfig httpConfig = HttpConfig();
httpConfig.setUserAgent("custom user agent...");
 
std::unique_ptr<Vpc::V2::VpcClient> vpcApi_v2 = Vpc::V2::VpcClient::newBuilder()
    .withCredentials(basicCredentials)
    .withHttpConfig(httpConfig)
    .withEndPoint(endpoint)
    .build();

4. Send Requests and Handle Responses 🔝

// Initialize request
Vpc::V2::Model::ListVpcsRequest listRequest;
std::shared_ptr<Vpc::V2::Model::ListVpcsResponse> listRes = vpcApi_v2->listVpcs(listRequest);
std::string responseBody = listRes->getHttpBody();
std::cout << responseBody << std::endl;

4.1 Exceptions 🔝

Level 1 Notice Level 2 Notice
ConnectionException Connection error HostUnreachableException Host is not reachable
SslHandShakeException SSL certification error
RequestTimeoutException Request timeout CallTimeoutException timeout for single request
RetryOutageException no response after retrying
ServiceResponseException service response error ServerResponseException server inner error, http status code: [500,]
ClientRequestException invalid request, http status code: [400? 500)
// handle exceptions
try {
    std::shared_ptr<Vpc::V2::Model::ListVpcsResponse> listRes = 
        vpcApi_v2->listVpcs(listRequest);
    std::string responseBody = listRes->getHttpBody();
    std::cout << responseBody << std::endl;
} catch (HostUnreachableException& e) {
    std::cout << e.what() << std::endl;
} catch (SslHandShakeException& e) {
    std::cout << e.what() << std::endl;
} catch (RetryOutageException& e) {
    std::cout << e.what() << std::endl;
} catch (CallTimeoutException& e) {
    std::cout << e.what() << std::endl;
} catch (ServiceResponseException& e) {
    std::cout << "StatusCode: " << e.getStatusCode() << std::endl;
    std::cout << "ErrorCode: " << e.getErrorCode() << std::endl;
    std::cout << "ErrorMsg: " << e.getErrorMsg() << std::endl;
    std::cout << "RequestId: " << e.getRequestId() << std::endl;
}

5. Use Asynchronous Client 🔝

// use c++ std::async
#include <future>
auto future = std::async(std::launch::async,
                        &Vpc::V2::VpcClient::listVpcs, vpcApi_v2.get(), listRequest);
auto listResponse = future.get();

6. Troubleshooting 🔝

SDK supports Access log which could be configured manually.

6.1 Access Log 🔝

SDK supports print access log which could be enabled by manual configuration, the log could be output to the console or specified files.

For example:

// Initialize specified service client instance, take VpcClient for example
std::unique_ptr<Vpc::V2::VpcClient> vpcApi_v2 = Vpc::V2::VpcClient::newBuilder()
    .withCredentials(basicCredentials)
    .withHttpConfig(httpConfig)
    .withFileLog(R"(.\log.txt)", true)
    .withStreamLog(true)
    .withEndPoint(endpoint)
    .build();

where:

  • withFileLogger:
    • logPath means log file path.
    • enable means file log is enabled.
  • withStreamLogger:
    • enable means console log is enabled.

After enabled log, the SDK will print the access log by default, every request will be recorded to the console like:

[2020-10-16 03:10:29][INFO] "GET https://iam.cn-north-1.myhuaweicloud.com/v3.0/OS-CREDENTIAL/credentials/W8VHHFEFPIJV6TFOUOQO"  200 244 7a68399eb8ed63fc91018426a7c4b8a0

The format of access log is:

"{httpMethod} {uri}" {httpStatusCode} {responseContentLength} {requestId}

7. Set CMakeLists.txt 🔝

  • If you want to use one service, you could configure like this:
# USE ONE SERVICE
SET(BUILD_SERVICE vpc)
SET(SERVICE_VERSION v2)

if(BUILD_SERVICE STREQUAL "")
    add_subdirectory(core)
else()
    add_subdirectory(core)
    add_subdirectory(${BUILD_SERVICE}/src/${SERVICE_VERSION})
    message(STATUS   "'BUILD_SERVICE'=${BUILD_SERVICE}")
endif()
  • If you want to use multiple services, you could configure like this:
# USE MULTIPLE SERVICES(EXAMPLE: vpc ecs eip)
add_subdirectory(core)
add_subdirectory(vpc/src/v2)
add_subdirectory(eip/src/v2)
add_subdirectory(ecs/src/v2)
  • For services that use BSON (kvs), set ENABLE_BSON to ON. ENABLE_BSON is set to OFF by default.
# For services that use BSON, set ENABLE_BSON to ON. ENABLE_BSON is set to OFF by default.
option(ENABLE_BSON "Enable bson library" ON)

8.Special Notes

  • If you need to use the three special APIs of the CCE service — listAutopilotJobs, getAutopilotOneJob, and deleteAutopilotJob — please refer to the following example code for invocation. Compared to other CCE APIs, the following two modifications are required: 1)When referencing the corresponding SDK client, you must include the CceSpecClient.h header file (other APIs use CceClient.h). 2)When calling the API, you must use the CceSpecClient::newBuilder() method to create the Client (other APIs use CceClient::newBuilder()).
#include <cstdlib>
#include <iostream>
#include <string>
#include <memory>
#include <huaweicloud/core/exception/Exceptions.h>
#include <huaweicloud/core/Client.h>
// use CceSpecClient.h to import CceSpecClient
#include <huaweicloud/cce/v3/CceSpecClient.h>

using namespace HuaweiCloud::Sdk::Cce::V3;
using namespace HuaweiCloud::Sdk::Cce::V3::Model;
using namespace HuaweiCloud::Sdk::Core;
using namespace HuaweiCloud::Sdk::Core::Exception;
using namespace std;

int main() {
    string ak = getenv("CLOUD_SDK_AK");
    string sk = getenv("CLOUD_SDK_SK");

    auto auth = std::make_unique<BasicCredentials>();
    auth->withAk(ak)
        .withSk(sk);
    HttpConfig httpConfig = HttpConfig();
    // use CceSpecClient to create client for api deleteAutopilotJob
    auto client = CceSpecClient::newBuilder()
            .withCredentials(std::unique_ptr<Credentials>(auth.release()))
            .withHttpConfig(httpConfig)
            .withEndPoint(endpoint)
            .build();

    DeleteAutopilotJobRequest request;
    request.setJobId("1234-11f1-852c-0255ac101783");

    std::cout << "-----begin execute request-------" << std::endl;
    try {
        auto reponse = client->deleteAutopilotJob(request);
        std::cout << reponse->getHttpBody() << std::endl;
    } catch (HostUnreachableException& e) {
        std::cout << "host unreachable:" << e.what() << std::endl;
    } catch (SslHandShakeException& e) {
        std::cout << "ssl handshake error:" << e.what() << std::endl;
    } catch (RetryOutageException& e) {
        std::cout << "retryoutage error:" << e.what() << std::endl;
    } catch (CallTimeoutException& e) {
        std::cout << "call timeout:" <<  e.what() << std::endl;
    } catch (ServiceResponseException& e) {
        std::cout << "http status code:" << e.getStatusCode() << std::endl;
        std::cout << "error code:" << e.getErrorCode() << std::endl;
        std::cout << "error msg:" << e.getErrorMsg() << std::endl;
        std::cout << "RequestId:" << e.getRequestId() << std::endl;
    } catch (exception& e) {
        std:cout << "unknown exception:" << e.what() << std::endl;
    }
    std::cout << "------request finished--------" << std::endl;
    return 0;
}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Used by

Contributors

Languages