From 9f50b42fa9f2787b78df5f33e4bc8c7712654dac Mon Sep 17 00:00:00 2001 From: Eugene Ostroukhov Date: Mon, 27 Nov 2023 09:48:16 -0800 Subject: [PATCH] wip - orca example --- examples/cpp/cmake/common.cmake | 1 + examples/cpp/orca/BUILD | 41 ++++++++++ examples/cpp/orca/CMakeLists.txt | 75 +++++++++++++++++ examples/cpp/orca/README.md | 6 ++ examples/cpp/orca/orca_client.cc | 133 +++++++++++++++++++++++++++++++ examples/cpp/orca/orca_server.cc | 101 +++++++++++++++++++++++ 6 files changed, 357 insertions(+) create mode 100644 examples/cpp/orca/BUILD create mode 100644 examples/cpp/orca/CMakeLists.txt create mode 100644 examples/cpp/orca/README.md create mode 100644 examples/cpp/orca/orca_client.cc create mode 100644 examples/cpp/orca/orca_server.cc diff --git a/examples/cpp/cmake/common.cmake b/examples/cpp/cmake/common.cmake index 5c3d1053182d17..df9bc4db0f87ff 100644 --- a/examples/cpp/cmake/common.cmake +++ b/examples/cpp/cmake/common.cmake @@ -51,6 +51,7 @@ if(GRPC_AS_SUBMODULE) # this build. set(_PROTOBUF_LIBPROTOBUF libprotobuf) set(_REFLECTION grpc++_reflection) + set(_ORCA_SERVICE grpcpp_orca_service) if(CMAKE_CROSSCOMPILING) find_program(_PROTOBUF_PROTOC protoc) else() diff --git a/examples/cpp/orca/BUILD b/examples/cpp/orca/BUILD new file mode 100644 index 00000000000000..bc09afe8712a65 --- /dev/null +++ b/examples/cpp/orca/BUILD @@ -0,0 +1,41 @@ +# Copyright 2023 the gRPC authors. +# +# 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. + +licenses(["notice"]) + +cc_binary( + name = "orca_client", + srcs = ["orca_client.cc"], + defines = ["BAZEL_BUILD"], + deps = [ + "//:grpc++", + "//examples/protos:helloworld_cc_grpc", + "@com_google_absl//absl/flags:flag", + "@com_google_absl//absl/flags:parse", + ], +) + +cc_binary( + name = "orca_server", + srcs = ["orca_server.cc"], + defines = ["BAZEL_BUILD"], + deps = [ + "//:grpc++", + "//:grpcpp_orca_service", + "//examples/protos:helloworld_cc_grpc", + "@com_google_absl//absl/flags:flag", + "@com_google_absl//absl/flags:parse", + "@com_google_absl//absl/strings:str_format", + ], +) diff --git a/examples/cpp/orca/CMakeLists.txt b/examples/cpp/orca/CMakeLists.txt new file mode 100644 index 00000000000000..9b4ea1c2e5ec37 --- /dev/null +++ b/examples/cpp/orca/CMakeLists.txt @@ -0,0 +1,75 @@ +# Copyright 2018 gRPC authors. +# +# 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. +# +# cmake build file for C++ helloworld example. +# Assumes protobuf and gRPC have been installed using cmake. +# See cmake_externalproject/CMakeLists.txt for all-in-one cmake build +# that automatically builds all the dependencies before building helloworld. + +cmake_minimum_required(VERSION 3.8) + +project(HelloWorld C CXX) + +include(../cmake/common.cmake) + +# Proto file +get_filename_component(hw_proto "../../protos/helloworld.proto" ABSOLUTE) +get_filename_component(hw_proto_path "${hw_proto}" PATH) + +# Generated sources +set(hw_proto_srcs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.pb.cc") +set(hw_proto_hdrs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.pb.h") +set(hw_grpc_srcs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.grpc.pb.cc") +set(hw_grpc_hdrs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.grpc.pb.h") +add_custom_command( + OUTPUT "${hw_proto_srcs}" "${hw_proto_hdrs}" "${hw_grpc_srcs}" "${hw_grpc_hdrs}" + COMMAND ${_PROTOBUF_PROTOC} + ARGS --grpc_out "${CMAKE_CURRENT_BINARY_DIR}" + --cpp_out "${CMAKE_CURRENT_BINARY_DIR}" + -I "${hw_proto_path}" + --plugin=protoc-gen-grpc="${_GRPC_CPP_PLUGIN_EXECUTABLE}" + "${hw_proto}" + DEPENDS "${hw_proto}") + +# Include generated *.pb.h files +include_directories("${CMAKE_CURRENT_BINARY_DIR}") + +# hw_grpc_proto +add_library(hw_grpc_proto + ${hw_grpc_srcs} + ${hw_grpc_hdrs} + ${hw_proto_srcs} + ${hw_proto_hdrs}) +target_link_libraries(hw_grpc_proto + ${_REFLECTION} + ${_GRPC_GRPCPP} + ${_PROTOBUF_LIBPROTOBUF}) + +add_executable(orca_client "orca_client.cc") +target_link_libraries(orca_client + hw_grpc_proto + absl::flags + absl::flags_parse + ${_REFLECTION} + ${_GRPC_GRPCPP} + ${_PROTOBUF_LIBPROTOBUF}) + +add_executable(orca_server "orca_server.cc") +target_link_libraries(orca_server + hw_grpc_proto + absl::flags + absl::flags_parse + ${_GRPC_GRPCPP} + ${_ORCA_SERVICE} + ${_PROTOBUF_LIBPROTOBUF}) diff --git a/examples/cpp/orca/README.md b/examples/cpp/orca/README.md new file mode 100644 index 00000000000000..a06cc8e3cb2c67 --- /dev/null +++ b/examples/cpp/orca/README.md @@ -0,0 +1,6 @@ +# gRPC C++ Hello World Example + +You can find a complete set of instructions for building gRPC and running the +Hello World app in the [C++ Quick Start][]. + +[C++ Quick Start]: https://grpc.io/docs/languages/cpp/quickstart diff --git a/examples/cpp/orca/orca_client.cc b/examples/cpp/orca/orca_client.cc new file mode 100644 index 00000000000000..00172bbf709468 --- /dev/null +++ b/examples/cpp/orca/orca_client.cc @@ -0,0 +1,133 @@ +/* + * + * Copyright 2015 gRPC authors. + * + * 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 +#include +#include +#include + +#include "absl/flags/flag.h" +#include "absl/flags/parse.h" +#include "absl/strings/string_view.h" + +#include + +#ifdef BAZEL_BUILD +#include "examples/protos/helloworld.grpc.pb.h" + +#include "src/core/lib/config/core_configuration.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/load_balancing/lb_policy.h" +#include "src/core/lib/load_balancing/lb_policy_factory.h" +#else +#include "helloworld.grpc.pb.h" +#endif + +ABSL_FLAG(std::string, target, "localhost:50051", "Server address"); + +namespace { + +using grpc::Channel; +using grpc::ClientContext; +using grpc::Status; + +using grpc_core::LoadBalancingPolicy; + +using helloworld::Greeter; +using helloworld::HelloReply; +using helloworld::HelloRequest; + +constexpr absl::string_view kName = "orca-example"; +class OrcaLBPolicy : public LoadBalancingPolicy { + public: + absl::string_view name() const override { return kName; } +}; + +class OrcaLBPolicyFactory : public grpc_core::LoadBalancingPolicyFactory { + public: + absl::string_view name() const override { return kName; } + + grpc_core::OrphanablePtr CreateLoadBalancingPolicy( + LoadBalancingPolicy::Args /* args */) const override { + return grpc_core::MakeOrphanable(); + } + + absl::StatusOr> + ParseLoadBalancingConfig(const grpc_core::Json& /* json */) const override { + return nullptr; + } +}; + +class GreeterClient { + public: + GreeterClient(std::shared_ptr channel) + : stub_(Greeter::NewStub(channel)) {} + + // Assembles the client's payload, sends it and presents the response back + // from the server. + std::string SayHello(const std::string& user) { + // Data we are sending to the server. + HelloRequest request; + request.set_name(user); + + // Container for the data we expect from the server. + HelloReply reply; + + // Context for the client. It could be used to convey extra information to + // the server and/or tweak certain RPC behaviors. + ClientContext context; + + // The actual RPC. + Status status = stub_->SayHello(&context, request, &reply); + + // Act upon its status. + if (status.ok()) { + return reply.message(); + } else { + std::cout << status.error_code() << ": " << status.error_message() + << std::endl; + return "RPC failed"; + } + } + + private: + std::unique_ptr stub_; +}; + +} // namespace + +int main(int argc, char** argv) { + absl::ParseCommandLine(argc, argv); + grpc_core::CoreConfiguration::RegisterBuilder([](auto builder) { + builder->lb_policy_registry()->RegisterLoadBalancingPolicyFactory( + std::make_unique()); + }); + // Instantiate the client. It requires a channel, out of which the actual RPCs + // are created. This channel models a connection to an endpoint specified by + // the argument "--target=" which is the only expected argument. + std::string target_str = absl::GetFlag(FLAGS_target); + // We indicate that the channel isn't authenticated (use of + // InsecureChannelCredentials()). + GreeterClient greeter( + grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials())); + std::string user("world"); + std::string reply = greeter.SayHello(user); + std::cout << "Greeter received: " << reply << std::endl; + + return 0; +} diff --git a/examples/cpp/orca/orca_server.cc b/examples/cpp/orca/orca_server.cc new file mode 100644 index 00000000000000..2342ec278a6ac5 --- /dev/null +++ b/examples/cpp/orca/orca_server.cc @@ -0,0 +1,101 @@ +/* + * + * Copyright 2015 gRPC authors. + * + * 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 +#include +#include +#include + +#include "absl/flags/flag.h" +#include "absl/flags/parse.h" +#include "absl/strings/str_format.h" + +#include +#include +#include +#include +#include + +#ifdef BAZEL_BUILD +#include "examples/protos/helloworld.grpc.pb.h" +#else +#include "helloworld.grpc.pb.h" +#endif + +using grpc::Server; +using grpc::ServerBuilder; +using grpc::ServerContext; +using grpc::Status; +using helloworld::Greeter; +using helloworld::HelloReply; +using helloworld::HelloRequest; + +ABSL_FLAG(uint16_t, port, 50051, "Server port for the service"); + +// Logic and data behind the server's behavior. +class GreeterServiceImpl final : public Greeter::Service { + Status SayHello(ServerContext* context, const HelloRequest* request, + HelloReply* reply) override { + auto recorder = context->ExperimentalGetCallMetricRecorder(); + if (recorder == nullptr) { + return Status(grpc::StatusCode::INTERNAL, + "Unable to access metrics recorder. Make sure " + "EnableCallMetricRecording had been called."); + } + recorder->RecordRequestCostMetric("db_queries", 10); + std::string prefix("Hello "); + reply->set_message(prefix + request->name()); + return Status::OK; + } +}; + +void RunServer(uint16_t port) { + std::string server_address = absl::StrFormat("0.0.0.0:%d", port); + GreeterServiceImpl service; + + auto server_metric_recorder = + grpc::experimental::ServerMetricRecorder::Create(); + + grpc::experimental::OrcaService orca_service( + server_metric_recorder.get(), + grpc::experimental::OrcaService::Options().set_min_report_duration( + absl::Seconds(0.1))); + + grpc::EnableDefaultHealthCheckService(true); + ServerBuilder builder; + // Listen on the given address without any authentication mechanism. + builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); + // Register "service" as the instance through which we'll communicate with + // clients. In this case it corresponds to an *synchronous* service. + builder.RegisterService(&service); + grpc::ServerBuilder::experimental_type(&builder).EnableCallMetricRecording( + nullptr); + // Finally assemble the server. + std::unique_ptr server(builder.BuildAndStart()); + std::cout << "Server listening on " << server_address << std::endl; + + // Wait for the server to shutdown. Note that some other thread must be + // responsible for shutting down the server for this call to ever return. + server->Wait(); +} + +int main(int argc, char** argv) { + absl::ParseCommandLine(argc, argv); + RunServer(absl::GetFlag(FLAGS_port)); + return 0; +}