diff options
Diffstat (limited to 'include')
45 files changed, 4331 insertions, 0 deletions
diff --git a/include/grpc++/async_server.h b/include/grpc++/async_server.h new file mode 100644 index 0000000000..fe2c5d9367 --- /dev/null +++ b/include/grpc++/async_server.h @@ -0,0 +1,70 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_ASYNC_SERVER_H__ +#define __GRPCPP_ASYNC_SERVER_H__ + +#include <mutex> + +#include <grpc++/config.h> + +struct grpc_server; + +namespace grpc { +class CompletionQueue; + +class AsyncServer { + public: + explicit AsyncServer(CompletionQueue* cc); + ~AsyncServer(); + + void AddPort(const grpc::string& addr); + + void Start(); + + // The user has to call this to get one new rpc on the completion + // queue. + void RequestOneRpc(); + + void Shutdown(); + + private: + bool started_; + std::mutex shutdown_mu_; + bool shutdown_; + grpc_server* server_; +}; + +} // namespace grpc + +#endif // __GRPCPP_ASYNC_SERVER_H__ diff --git a/include/grpc++/async_server_context.h b/include/grpc++/async_server_context.h new file mode 100644 index 0000000000..dd4097b25c --- /dev/null +++ b/include/grpc++/async_server_context.h @@ -0,0 +1,93 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_ASYNC_SERVER_CONTEXT_H__ +#define __GRPCPP_ASYNC_SERVER_CONTEXT_H__ + +#include <chrono> + +#include <grpc++/config.h> + +struct grpc_byte_buffer; +struct grpc_call; +struct grpc_completion_queue; + +namespace google { +namespace protobuf { +class Message; +} +} + +using std::chrono::system_clock; + +namespace grpc { +class Status; + +// TODO(rocking): wrap grpc c structures. +class AsyncServerContext { + public: + AsyncServerContext(grpc_call* call, const grpc::string& method, + const grpc::string& host, + system_clock::time_point absolute_deadline); + ~AsyncServerContext(); + + // Accept this rpc, bind it to a completion queue. + void Accept(grpc_completion_queue* cq); + + // Read and write calls, all async. Return true for success. + bool StartRead(google::protobuf::Message* request); + bool StartWrite(const google::protobuf::Message& response, int flags); + bool StartWriteStatus(const Status& status); + + bool ParseRead(grpc_byte_buffer* read_buffer); + + grpc::string method() const { return method_; } + grpc::string host() const { return host_; } + system_clock::time_point absolute_deadline() { return absolute_deadline_; } + + private: + AsyncServerContext(const AsyncServerContext&); + AsyncServerContext& operator=(const AsyncServerContext&); + + // These properties may be moved to a ServerContext class. + const grpc::string method_; + const grpc::string host_; + system_clock::time_point absolute_deadline_; + + google::protobuf::Message* request_; // not owned + grpc_call* call_; // owned +}; + +} // namespace grpc + +#endif // __GRPCPP_ASYNC_SERVER_CONTEXT_H__ diff --git a/include/grpc++/channel_interface.h b/include/grpc++/channel_interface.h new file mode 100644 index 0000000000..4b9d76e0d1 --- /dev/null +++ b/include/grpc++/channel_interface.h @@ -0,0 +1,68 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_CHANNEL_INTERFACE_H__ +#define __GRPCPP_CHANNEL_INTERFACE_H__ + +#include <grpc++/status.h> + +namespace google { +namespace protobuf { +class Message; +} +} + +namespace grpc { + +class ClientContext; +class RpcMethod; +class StreamContextInterface; + +class ChannelInterface { + public: + virtual ~ChannelInterface() {} + + virtual Status StartBlockingRpc(const RpcMethod& method, + ClientContext* context, + const google::protobuf::Message& request, + google::protobuf::Message* result) = 0; + + virtual StreamContextInterface* CreateStream(const RpcMethod& method, + ClientContext* context, + const google::protobuf::Message* request, + google::protobuf::Message* result) = 0; +}; + +} // namespace grpc + +#endif // __GRPCPP_CHANNEL_INTERFACE_H__ diff --git a/include/grpc++/client_context.h b/include/grpc++/client_context.h new file mode 100644 index 0000000000..8301b3c630 --- /dev/null +++ b/include/grpc++/client_context.h @@ -0,0 +1,85 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_CLIENT_CONTEXT_H__ +#define __GRPCPP_CLIENT_CONTEXT_H__ + +#include <chrono> +#include <string> +#include <vector> + +#include <grpc++/config.h> + +using std::chrono::system_clock; + +struct grpc_call; +struct grpc_completion_queue; + +namespace grpc { + +class ClientContext { + public: + ClientContext(); + ~ClientContext(); + + void AddMetadata(const grpc::string &meta_key, + const grpc::string &meta_value); + + void set_absolute_deadline(const system_clock::time_point &deadline); + system_clock::time_point absolute_deadline(); + + void StartCancel(); + + private: + // Disallow copy and assign. + ClientContext(const ClientContext &); + ClientContext &operator=(const ClientContext &); + + friend class Channel; + friend class StreamContext; + + grpc_call *call() { return call_; } + void set_call(grpc_call *call) { call_ = call; } + + grpc_completion_queue *cq() { return cq_; } + void set_cq(grpc_completion_queue *cq) { cq_ = cq; } + + grpc_call *call_; + grpc_completion_queue *cq_; + system_clock::time_point absolute_deadline_; + std::vector<std::pair<grpc::string, grpc::string> > metadata_; +}; + +} // namespace grpc + +#endif // __GRPCPP_CLIENT_CONTEXT_H__ diff --git a/include/grpc++/completion_queue.h b/include/grpc++/completion_queue.h new file mode 100644 index 0000000000..72f6253f8e --- /dev/null +++ b/include/grpc++/completion_queue.h @@ -0,0 +1,87 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_COMPLETION_QUEUE_H__ +#define __GRPCPP_COMPLETION_QUEUE_H__ + +struct grpc_completion_queue; + +namespace grpc { + +// grpc_completion_queue wrapper class +class CompletionQueue { + public: + CompletionQueue(); + ~CompletionQueue(); + + enum CompletionType { + QUEUE_CLOSED = 0, // Shutting down. + RPC_END = 1, // An RPC finished. Either at client or server. + CLIENT_READ_OK = 2, // A client-side read has finished successfully. + CLIENT_READ_ERROR = 3, // A client-side read has finished with error. + CLIENT_WRITE_OK = 4, + CLIENT_WRITE_ERROR = 5, + SERVER_RPC_NEW = 6, // A new RPC just arrived at the server. + SERVER_READ_OK = 7, // A server-side read has finished successfully. + SERVER_READ_ERROR = 8, // A server-side read has finished with error. + SERVER_WRITE_OK = 9, + SERVER_WRITE_ERROR = 10, + // Client or server has sent half close successfully. + HALFCLOSE_OK = 11, + // New CompletionTypes may be added in the future, so user code should + // always + // handle the default case of a CompletionType that appears after such code + // was + // written. + DO_NOT_USE = 20, + }; + + // Blocking read from queue. + // For QUEUE_CLOSED, *tag is not changed. + // For SERVER_RPC_NEW, *tag will be a newly allocated AsyncServerContext. + // For others, *tag will be the AsyncServerContext of this rpc. + CompletionType Next(void** tag); + + // Shutdown has to be called, and the CompletionQueue can only be + // destructed when the QUEUE_CLOSED message has been read with Next(). + void Shutdown(); + + grpc_completion_queue* cq() { return cq_; } + + private: + grpc_completion_queue* cq_; // owned +}; + +} // namespace grpc + +#endif // __GRPCPP_COMPLETION_QUEUE_H__ diff --git a/include/grpc++/config.h b/include/grpc++/config.h new file mode 100644 index 0000000000..153b288f0c --- /dev/null +++ b/include/grpc++/config.h @@ -0,0 +1,45 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_CONFIG_H__ +#define __GRPCPP_CONFIG_H__ + +#include <string> + +namespace grpc { + +typedef std::string string; + +} + +#endif // __GRPCPP_CONFIG_H__ diff --git a/include/grpc++/create_channel.h b/include/grpc++/create_channel.h new file mode 100644 index 0000000000..3bb16b2618 --- /dev/null +++ b/include/grpc++/create_channel.h @@ -0,0 +1,53 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_CREATE_CHANNEL_H__ +#define __GRPCPP_CREATE_CHANNEL_H__ + +#include <memory> + +#include <grpc++/config.h> +#include <grpc++/credentials.h> + +namespace grpc { +class ChannelInterface; + +std::shared_ptr<ChannelInterface> CreateChannel(const grpc::string& target); + +std::shared_ptr<ChannelInterface> CreateChannel( + const grpc::string& target, + const std::unique_ptr<grpc::Credentials>& creds); + +} // namespace grpc + +#endif // __GRPCPP_CREATE_CHANNEL_H__ diff --git a/include/grpc++/credentials.h b/include/grpc++/credentials.h new file mode 100644 index 0000000000..f0db6c252b --- /dev/null +++ b/include/grpc++/credentials.h @@ -0,0 +1,95 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_CREDENTIALS_H_ +#define __GRPCPP_CREDENTIALS_H_ + +#include <memory> + +#include <grpc++/config.h> + +struct grpc_credentials; + +namespace grpc { + +// grpc_credentials wrapper class. Typical use in C++ applications is limited +// to creating an instance using CredentialsFactory, and passing it down +// during channel construction. + +class Credentials final { + public: + ~Credentials(); + // TODO(abhikumar): Specify a plugin API here to be implemented by + // credentials that do not have a corresponding implementation in C. + + protected: + explicit Credentials(grpc_credentials*); + + private: + grpc_credentials* GetRawCreds(); + + friend class CredentialsFactory; + + grpc_credentials* creds_; +}; + +// Options used to build SslCredentials +struct SslCredentialsOptions { + grpc::string pem_root_certs; + grpc::string pem_private_key; + grpc::string pem_cert_chain; +}; + +// Factory for building different types of Credentials +class CredentialsFactory { + public: + // Builds credentials with reasonable defaults. + static std::unique_ptr<Credentials> DefaultCredentials(); + + // Builds SSL Credentials given SSL specific options + static std::unique_ptr<Credentials> SslCredentials( + const SslCredentialsOptions& options); + + // Builds credentials for use when running in GCE + static std::unique_ptr<Credentials> ComputeEngineCredentials(); + + + // Combines two credentials objects into a composite credentials + static std::unique_ptr<Credentials> ComposeCredentials( + const std::unique_ptr<Credentials>& creds1, + const std::unique_ptr<Credentials>& creds2); +}; + +} // namespace grpc + +#endif // __GRPCPP_CREDENTIALS_H_ diff --git a/include/grpc++/server.h b/include/grpc++/server.h new file mode 100644 index 0000000000..443b4d42f2 --- /dev/null +++ b/include/grpc++/server.h @@ -0,0 +1,111 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_SERVER_H__ +#define __GRPCPP_SERVER_H__ + +#include <condition_variable> +#include <map> +#include <memory> +#include <mutex> + +#include <grpc++/completion_queue.h> +#include <grpc++/config.h> +#include <grpc++/status.h> + +struct grpc_server; + +namespace google { +namespace protobuf { +class Message; +} +} + +namespace grpc { +class AsyncServerContext; +class RpcService; +class RpcServiceMethod; +class ThreadPoolInterface; + +// Currently it only supports handling rpcs in a single thread. +class Server { + public: + ~Server(); + + // Shutdown the server, block until all rpc processing finishes. + void Shutdown(); + + private: + friend class ServerBuilder; + + // ServerBuilder use only + explicit Server(ThreadPoolInterface* thread_pool); + Server(); + // Register a service. This call does not take ownership of the service. + // The service must exist for the lifetime of the Server instance. + void RegisterService(RpcService* service); + // Add a listening port. Can be called multiple times. + void AddPort(const grpc::string& addr); + // Start the server. + void Start(); + + void AllowOneRpc(); + void HandleQueueClosed(); + void RunRpc(); + void ScheduleCallback(); + + // Completion queue. + CompletionQueue cq_; + + // Sever status + std::mutex mu_; + bool started_; + bool shutdown_; + // The number of threads which are running callbacks. + int num_running_cb_; + std::condition_variable callback_cv_; + + // Pointer to the c grpc server. + grpc_server* server_; + + // A map for all method information. + std::map<grpc::string, RpcServiceMethod*> method_map_; + + ThreadPoolInterface* thread_pool_; + // Whether the thread pool is created and owned by the server. + bool thread_pool_owned_; +}; + +} // namespace grpc + +#endif // __GRPCPP_SERVER_H__ diff --git a/include/grpc++/server_builder.h b/include/grpc++/server_builder.h new file mode 100644 index 0000000000..89e9a25107 --- /dev/null +++ b/include/grpc++/server_builder.h @@ -0,0 +1,75 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_SERVER_BUILDER_H__ +#define __GRPCPP_SERVER_BUILDER_H__ + +#include <memory> +#include <vector> + +#include <grpc++/config.h> + +namespace grpc { + +class RpcService; +class Server; +class ThreadPoolInterface; + +class ServerBuilder { + public: + ServerBuilder(); + + // Register a service. This call does not take ownership of the service. + // The service must exist for the lifetime of the Server instance returned by + // BuildAndStart(). + void RegisterService(RpcService* service); + + // Add a listening port. Can be called multiple times. + void AddPort(const grpc::string& addr); + + // Set the thread pool used for running appliation rpc handlers. + // Does not take ownership. + void SetThreadPool(ThreadPoolInterface* thread_pool); + + // Return a running server which is ready for processing rpcs. + std::unique_ptr<Server> BuildAndStart(); + + private: + std::vector<RpcService*> services_; + std::vector<grpc::string> ports_; + ThreadPoolInterface* thread_pool_; +}; + +} // namespace grpc + +#endif // __GRPCPP_SERVER_BUILDER_H__ diff --git a/include/grpc++/status.h b/include/grpc++/status.h new file mode 100644 index 0000000000..432158a989 --- /dev/null +++ b/include/grpc++/status.h @@ -0,0 +1,65 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_STATUS_H__ +#define __GRPCPP_STATUS_H__ + +#include <grpc++/status_code_enum.h> +#include <grpc++/config.h> + +namespace grpc { + +class Status { + public: + Status() : code_(StatusCode::OK) {} + explicit Status(StatusCode code) : code_(code) {} + Status(StatusCode code, const grpc::string& details) + : code_(code), details_(details) {} + + // Pre-defined special status objects. + static const Status& OK; + static const Status& Cancelled; + + StatusCode code() const { return code_; } + grpc::string details() const { return details_; } + + bool IsOk() const { return code_ == StatusCode::OK; } + + private: + StatusCode code_; + grpc::string details_; +}; + +} // namespace grpc + +#endif // __GRPCPP_STATUS_H__ diff --git a/include/grpc++/status_code_enum.h b/include/grpc++/status_code_enum.h new file mode 100644 index 0000000000..964420dcc4 --- /dev/null +++ b/include/grpc++/status_code_enum.h @@ -0,0 +1,199 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_STATUS_CODE_ENUM_H__ +#define __GRPCPP_STATUS_CODE_ENUM_H__ + + +namespace grpc { + +enum StatusCode { + /* Not an error; returned on success + + HTTP Mapping: 200 OK */ + OK = 0, + + /* The operation was cancelled (typically by the caller). + + HTTP Mapping: 499 Client Closed Request */ + CANCELLED = 1, + + /* Unknown error. An example of where this error may be returned is + if a Status value received from another address space belongs to + an error-space that is not known in this address space. Also + errors raised by APIs that do not return enough error information + may be converted to this error. + + HTTP Mapping: 500 Internal Server Error */ + UNKNOWN = 2, + + /* Client specified an invalid argument. Note that this differs + from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments + that are problematic regardless of the state of the system + (e.g., a malformed file name). + + HTTP Mapping: 400 Bad Request */ + INVALID_ARGUMENT = 3, + + /* Deadline expired before operation could complete. For operations + that change the state of the system, this error may be returned + even if the operation has completed successfully. For example, a + successful response from a server could have been delayed long + enough for the deadline to expire. + + HTTP Mapping: 504 Gateway Timeout */ + DEADLINE_EXCEEDED = 4, + + /* Some requested entity (e.g., file or directory) was not found. + + HTTP Mapping: 404 Not Found */ + NOT_FOUND = 5, + + /* Some entity that we attempted to create (e.g., file or directory) + already exists. + + HTTP Mapping: 409 Conflict */ + ALREADY_EXISTS = 6, + + /* The caller does not have permission to execute the specified + operation. PERMISSION_DENIED must not be used for rejections + caused by exhausting some resource (use RESOURCE_EXHAUSTED + instead for those errors). PERMISSION_DENIED must not be + used if the caller can not be identified (use UNAUTHENTICATED + instead for those errors). + + HTTP Mapping: 403 Forbidden */ + PERMISSION_DENIED = 7, + + /* The request does not have valid authentication credentials for the + operation. + + HTTP Mapping: 401 Unauthorized */ + UNAUTHENTICATED = 16, + + /* Some resource has been exhausted, perhaps a per-user quota, or + perhaps the entire file system is out of space. + + HTTP Mapping: 429 Too Many Requests */ + RESOURCE_EXHAUSTED = 8, + + /* Operation was rejected because the system is not in a state + required for the operation's execution. For example, directory + to be deleted may be non-empty, an rmdir operation is applied to + a non-directory, etc. + + A litmus test that may help a service implementor in deciding + between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + (a) Use UNAVAILABLE if the client can retry just the failing call. + (b) Use ABORTED if the client should retry at a higher-level + (e.g., restarting a read-modify-write sequence). + (c) Use FAILED_PRECONDITION if the client should not retry until + the system state has been explicitly fixed. E.g., if an "rmdir" + fails because the directory is non-empty, FAILED_PRECONDITION + should be returned since the client should not retry unless + they have first fixed up the directory by deleting files from it. + (d) Use FAILED_PRECONDITION if the client performs conditional + REST Get/Update/Delete on a resource and the resource on the + server does not match the condition. E.g., conflicting + read-modify-write on the same resource. + + HTTP Mapping: 400 Bad Request + + NOTE: HTTP spec says 412 Precondition Failed should only be used if + the request contains Etag related headers. So if the server does see + Etag related headers in the request, it may choose to return 412 + instead of 400 for this error code. */ + FAILED_PRECONDITION = 9, + + /* The operation was aborted, typically due to a concurrency issue + like sequencer check failures, transaction aborts, etc. + + See litmus test above for deciding between FAILED_PRECONDITION, + ABORTED, and UNAVAILABLE. + + HTTP Mapping: 409 Conflict */ + ABORTED = 10, + + /* Operation was attempted past the valid range. E.g., seeking or + reading past end of file. + + Unlike INVALID_ARGUMENT, this error indicates a problem that may + be fixed if the system state changes. For example, a 32-bit file + system will generate INVALID_ARGUMENT if asked to read at an + offset that is not in the range [0,2^32-1], but it will generate + OUT_OF_RANGE if asked to read from an offset past the current + file size. + + There is a fair bit of overlap between FAILED_PRECONDITION and + OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific + error) when it applies so that callers who are iterating through + a space can easily look for an OUT_OF_RANGE error to detect when + they are done. + + HTTP Mapping: 400 Bad Request */ + OUT_OF_RANGE = 11, + + /* Operation is not implemented or not supported/enabled in this service. + + HTTP Mapping: 501 Not Implemented */ + UNIMPLEMENTED = 12, + + /* Internal errors. Means some invariants expected by underlying + system has been broken. If you see one of these errors, + something is very broken. + + HTTP Mapping: 500 Internal Server Error */ + INTERNAL = 13, + + /* The service is currently unavailable. This is a most likely a + transient condition and may be corrected by retrying with + a backoff. + + See litmus test above for deciding between FAILED_PRECONDITION, + ABORTED, and UNAVAILABLE. + + HTTP Mapping: 503 Service Unavailable */ + UNAVAILABLE = 14, + + /* Unrecoverable data loss or corruption. + + HTTP Mapping: 500 Internal Server Error */ + DATA_LOSS = 15, + + /* Force users to include a default branch: */ + DO_NOT_USE = -1 +}; + +} // namespace grpc + +#endif // __GRPCPP_STATUS_CODE_ENUM_H_ diff --git a/include/grpc++/stream.h b/include/grpc++/stream.h new file mode 100644 index 0000000000..50c21565b5 --- /dev/null +++ b/include/grpc++/stream.h @@ -0,0 +1,178 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_STREAM_H__ +#define __GRPCPP_STREAM_H__ + +#include <grpc++/stream_context_interface.h> +#include <grpc++/status.h> +#include <grpc/support/log.h> + +namespace grpc { + +// Common interface for all client side streaming. +class ClientStreamingInterface { + public: + virtual ~ClientStreamingInterface() {} + + // Try to cancel the stream. Wait() still needs to be called to get the final + // status. Cancelling after the stream has finished has no effects. + virtual void Cancel() = 0; + + // Wait until the stream finishes, and return the final status. When the + // client side declares it has no more message to send, either implicitly or + // by calling WritesDone, it needs to make sure there is no more message to + // be received from the server, either implicitly or by getting a false from + // a Read(). Otherwise, this implicitly cancels the stream. + virtual const Status& Wait() = 0; +}; + +// An interface that yields a sequence of R messages. +template <class R> +class ReaderInterface { + public: + virtual ~ReaderInterface() {} + + // Blocking read a message and parse to msg. Returns true on success. + // The method returns false when there will be no more incoming messages, + // either because the other side has called WritesDone or the stream has + // failed (or been cancelled). + virtual bool Read(R* msg) = 0; +}; + +// An interface that can be fed a sequence of W messages. +template <class W> +class WriterInterface { + public: + virtual ~WriterInterface() {} + + // Blocking write msg to the stream. Returns true on success. + // Returns false when the stream has been closed. + virtual bool Write(const W& msg) = 0; +}; + +template <class R> +class ClientReader : public ClientStreamingInterface, + public ReaderInterface<R> { + public: + // Blocking create a stream and write the first request out. + explicit ClientReader(StreamContextInterface* context) : context_(context) { + GPR_ASSERT(context_); + context_->Start(true); + context_->Write(context_->request(), true); + } + + ~ClientReader() { delete context_; } + + virtual bool Read(R* msg) { return context_->Read(msg); } + + virtual void Cancel() { context_->FinishStream(Status::Cancelled, true); } + + virtual const Status& Wait() { return context_->Wait(); } + + private: + StreamContextInterface* const context_; +}; + +template <class W> +class ClientWriter : public ClientStreamingInterface, + public WriterInterface<W> { + public: + // Blocking create a stream. + explicit ClientWriter(StreamContextInterface* context) : context_(context) { + GPR_ASSERT(context_); + context_->Start(false); + } + + ~ClientWriter() { delete context_; } + + virtual bool Write(const W& msg) { + return context_->Write(const_cast<W*>(&msg), false); + } + + virtual void WritesDone() { context_->Write(nullptr, true); } + + virtual void Cancel() { context_->FinishStream(Status::Cancelled, true); } + + // Read the final response and wait for the final status. + virtual const Status& Wait() { + bool success = context_->Read(context_->response()); + if (!success) { + Cancel(); + } else { + success = context_->Read(nullptr); + if (success) { + Cancel(); + } + } + return context_->Wait(); + } + + private: + StreamContextInterface* const context_; +}; + +// Client-side interface for bi-directional streaming. +template <class W, class R> +class ClientReaderWriter : public ClientStreamingInterface, + public WriterInterface<W>, + public ReaderInterface<R> { + public: + // Blocking create a stream. + explicit ClientReaderWriter(StreamContextInterface* context) + : context_(context) { + GPR_ASSERT(context_); + context_->Start(false); + } + + ~ClientReaderWriter() { delete context_; } + + virtual bool Read(R* msg) { return context_->Read(msg); } + + virtual bool Write(const W& msg) { + return context_->Write(const_cast<W*>(&msg), false); + } + + virtual void WritesDone() { context_->Write(nullptr, true); } + + virtual void Cancel() { context_->FinishStream(Status::Cancelled, true); } + + virtual const Status& Wait() { return context_->Wait(); } + + private: + StreamContextInterface* const context_; +}; + +} // namespace grpc + +#endif // __GRPCPP_STREAM_H__ diff --git a/include/grpc++/stream_context_interface.h b/include/grpc++/stream_context_interface.h new file mode 100644 index 0000000000..eb5c092059 --- /dev/null +++ b/include/grpc++/stream_context_interface.h @@ -0,0 +1,64 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_STREAM_CONTEXT_INTERFACE_H__ +#define __GRPCPP_STREAM_CONTEXT_INTERFACE_H__ + +namespace google { +namespace protobuf { +class Message; +} +} + +namespace grpc { +class Status; + +// An interface to avoid dependency on internal implementation. +class StreamContextInterface { + public: + virtual ~StreamContextInterface() {} + + virtual void Start(bool buffered) = 0; + + virtual bool Read(google::protobuf::Message* msg) = 0; + virtual bool Write(const google::protobuf::Message* msg, bool is_last) = 0; + virtual const Status& Wait() = 0; + virtual void FinishStream(const Status& status, bool send) = 0; + + virtual const google::protobuf::Message* request() = 0; + virtual google::protobuf::Message* response() = 0; +}; + +} // namespace grpc + +#endif // __GRPCPP_STREAM_CONTEXT_INTERFACE_H__ diff --git a/include/grpc++/thread_pool_interface.h b/include/grpc++/thread_pool_interface.h new file mode 100644 index 0000000000..a8eacb037f --- /dev/null +++ b/include/grpc++/thread_pool_interface.h @@ -0,0 +1,52 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPCPP_THREAD_POOL_INTERFACE_H__ +#define __GRPCPP_THREAD_POOL_INTERFACE_H__ + +#include <functional> + +namespace grpc { + +// A thread pool interface for running callbacks. +class ThreadPoolInterface { + public: + virtual ~ThreadPoolInterface() {} + + // Schedule the given callback for execution. + virtual void ScheduleCallback(const std::function<void()>& callback) = 0; +}; + +} // namespace grpc + +#endif // __GRPCPP_THREAD_POOL_INTERFACE_H__ diff --git a/include/grpc/byte_buffer.h b/include/grpc/byte_buffer.h new file mode 100644 index 0000000000..0db59d7aee --- /dev/null +++ b/include/grpc/byte_buffer.h @@ -0,0 +1,50 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_BYTE_BUFFER_H__ +#define __GRPC_BYTE_BUFFER_H__ + +#include <grpc/grpc.h> +#include <grpc/support/slice_buffer.h> + +typedef enum { GRPC_BB_SLICE_BUFFER } grpc_byte_buffer_type; + +/* byte buffers are what meesages are passed in as from the public api's */ +struct grpc_byte_buffer { + grpc_byte_buffer_type type; + union { + gpr_slice_buffer slice_buffer; + } data; +}; + +#endif /* __GRPC_BYTE_BUFFER_H__ */ diff --git a/include/grpc/byte_buffer_reader.h b/include/grpc/byte_buffer_reader.h new file mode 100644 index 0000000000..5f1c160e15 --- /dev/null +++ b/include/grpc/byte_buffer_reader.h @@ -0,0 +1,49 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_BYTE_BUFFER_READER_H__ +#define __GRPC_BYTE_BUFFER_READER_H__ + +#include <grpc/grpc.h> +#include <grpc/byte_buffer.h> + +struct grpc_byte_buffer_reader { + grpc_byte_buffer *buffer; + /* Different current objects correspond to different types of byte buffers */ + union { + /* Index into a slice buffer's array of slices */ + int index; + } current; +}; + +#endif /* __GRPC_BYTE_BUFFER_READER_H__ */ diff --git a/include/grpc/grpc.h b/include/grpc/grpc.h new file mode 100644 index 0000000000..17e155a929 --- /dev/null +++ b/include/grpc/grpc.h @@ -0,0 +1,421 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_GRPC_H__ +#define __GRPC_GRPC_H__ + +#include <grpc/status.h> + +#include <stddef.h> +#include <grpc/support/slice.h> +#include <grpc/support/time.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/* Completion Channels enable notification of the completion of asynchronous + actions. */ +typedef struct grpc_completion_queue grpc_completion_queue; + +/* The Channel interface allows creation of Call objects. */ +typedef struct grpc_channel grpc_channel; + +/* A server listens to some port and responds to request calls */ +typedef struct grpc_server grpc_server; + +/* A Call represents an RPC. When created, it is in a configuration state + allowing properties to be set until it is invoked. After invoke, the Call + can have messages written to it and read from it. */ +typedef struct grpc_call grpc_call; + +/* Type specifier for grpc_arg */ +typedef enum { + GRPC_ARG_STRING, + GRPC_ARG_INTEGER, + GRPC_ARG_POINTER +} grpc_arg_type; + +/* A single argument... each argument has a key and a value + + A note on naming keys: + Keys are namespaced into groups, usually grouped by library, and are + keys for module XYZ are named XYZ.key1, XYZ.key2, etc. Module names must + be restricted to the regex [A-Za-z][_A-Za-z0-9]{,15}. + Key names must be restricted to the regex [A-Za-z][_A-Za-z0-9]{,47}. + + GRPC core library keys are prefixed by grpc. + + Library authors are strongly encouraged to #define symbolic constants for + their keys so that it's possible to change them in the future. */ +typedef struct { + grpc_arg_type type; + char *key; + union { + char *string; + int integer; + struct { + void *p; + void *(*copy)(void *p); + void (*destroy)(void *p); + } pointer; + } value; +} grpc_arg; + +/* An array of arguments that can be passed around */ +typedef struct { + size_t num_args; + grpc_arg *args; +} grpc_channel_args; + +/* Channel argument keys: */ +/* Enable census for tracing and stats collection */ +#define GRPC_ARG_ENABLE_CENSUS "grpc.census" +/* Maximum number of concurrent incoming streams to allow on a http2 + connection */ +#define GRPC_ARG_MAX_CONCURRENT_STREAMS "grpc.max_concurrent_streams" +/* Maximum message length that the channel can receive */ +#define GRPC_ARG_MAX_MESSAGE_LENGTH "grpc.max_message_length" + +/* Status of a completed call */ +typedef struct grpc_status { + grpc_status_code code; + char *details; +} grpc_status; + +/* Result of a grpc call. If the caller satisfies the prerequisites of a + particular operation, the grpc_call_error returned will be GRPC_CALL_OK. + Receiving any other value listed here is an indication of a bug in the + caller. */ +typedef enum grpc_call_error { + /* everything went ok */ + GRPC_CALL_OK = 0, + /* something failed, we don't know what */ + GRPC_CALL_ERROR, + /* this method is not available on the server */ + GRPC_CALL_ERROR_NOT_ON_SERVER, + /* this method is not available on the client */ + GRPC_CALL_ERROR_NOT_ON_CLIENT, + /* this method must be called before invoke */ + GRPC_CALL_ERROR_ALREADY_INVOKED, + /* this method must be called after invoke */ + GRPC_CALL_ERROR_NOT_INVOKED, + /* this call is already finished + (writes_done or write_status has already been called) */ + GRPC_CALL_ERROR_ALREADY_FINISHED, + /* there is already an outstanding read/write operation on the call */ + GRPC_CALL_ERROR_TOO_MANY_OPERATIONS, + /* the flags value was illegal for this call */ + GRPC_CALL_ERROR_INVALID_FLAGS +} grpc_call_error; + +/* Result of a grpc operation */ +typedef enum grpc_op_error { + /* everything went ok */ + GRPC_OP_OK = 0, + /* something failed, we don't know what */ + GRPC_OP_ERROR +} grpc_op_error; + +/* Write Flags: */ +/* Hint that the write may be buffered and need not go out on the wire + immediately. GRPC is free to buffer the message until the next non-buffered + write, or until writes_done, but it need not buffer completely or at all. */ +#define GRPC_WRITE_BUFFER_HINT (0x00000001u) +/* Force compression to be disabled for a particular write + (start_write/add_metadata). Illegal on invoke/accept. */ +#define GRPC_WRITE_NO_COMPRESS (0x00000002u) + +/* A buffer of bytes */ +struct grpc_byte_buffer; +typedef struct grpc_byte_buffer grpc_byte_buffer; + +/* Sample helpers to obtain byte buffers (these will certainly move place */ +grpc_byte_buffer *grpc_byte_buffer_create(gpr_slice *slices, size_t nslices); +size_t grpc_byte_buffer_length(grpc_byte_buffer *bb); +void grpc_byte_buffer_destroy(grpc_byte_buffer *byte_buffer); + +/* Reader for byte buffers. Iterates over slices in the byte buffer */ +struct grpc_byte_buffer_reader; +typedef struct grpc_byte_buffer_reader grpc_byte_buffer_reader; + +grpc_byte_buffer_reader *grpc_byte_buffer_reader_create( + grpc_byte_buffer *buffer); +/* At the end of the stream, returns 0. Otherwise, returns 1 and sets slice to + be the returned slice. Caller is responsible for calling gpr_slice_unref on + the result. */ +int grpc_byte_buffer_reader_next(grpc_byte_buffer_reader *reader, + gpr_slice *slice); +void grpc_byte_buffer_reader_destroy(grpc_byte_buffer_reader *reader); + +/* A single metadata element */ +typedef struct grpc_metadata { + char *key; + char *value; + size_t value_length; +} grpc_metadata; + +typedef enum grpc_completion_type { + GRPC_QUEUE_SHUTDOWN, /* Shutting down */ + GRPC_READ, /* A read has completed */ + GRPC_INVOKE_ACCEPTED, /* An invoke call has been accepted by flow + control */ + GRPC_WRITE_ACCEPTED, /* A write has been accepted by + flow control */ + GRPC_FINISH_ACCEPTED, /* writes_done or write_status has been accepted */ + GRPC_CLIENT_METADATA_READ, /* The metadata array sent by server received at + client */ + GRPC_FINISHED, /* An RPC has finished. The event contains status. + On the server this will be OK or Cancelled. */ + GRPC_SERVER_RPC_NEW, /* A new RPC has arrived at the server */ + GRPC_COMPLETION_DO_NOT_USE /* must be last, forces users to include + a default: case */ +} grpc_completion_type; + +typedef struct grpc_event { + grpc_completion_type type; + void *tag; + grpc_call *call; + /* Data associated with the completion type. Field names match the type of + completion as listed in grpc_completion_type. */ + union { + /* Contains a pointer to the buffer that was read, or NULL at the end of a + stream. */ + grpc_byte_buffer *read; + grpc_op_error write_accepted; + grpc_op_error finish_accepted; + grpc_op_error invoke_accepted; + struct { + size_t count; + grpc_metadata *elements; + } client_metadata_read; + grpc_status finished; + struct { + const char *method; + const char *host; + gpr_timespec deadline; + size_t metadata_count; + grpc_metadata *metadata_elements; + } server_rpc_new; + } data; +} grpc_event; + +/* Initialize the grpc library */ +void grpc_init(); + +/* Shutdown the grpc library */ +void grpc_shutdown(); + +grpc_completion_queue *grpc_completion_queue_create(); + +/* Blocks until an event is available, the completion queue is being shutdown, + or deadline is reached. Returns NULL on timeout, otherwise the event that + occurred. Callers should call grpc_event_finish once they have processed + the event. + + Callers must not call grpc_completion_queue_next and + grpc_completion_queue_pluck simultaneously on the same completion queue. */ +grpc_event *grpc_completion_queue_next(grpc_completion_queue *cq, + gpr_timespec deadline); + +/* Blocks until an event with tag 'tag' is available, the completion queue is + being shutdown or deadline is reached. Returns NULL on timeout, or a pointer + to the event that occurred. Callers should call grpc_event_finish once they + have processed the event. + + Callers must not call grpc_completion_queue_next and + grpc_completion_queue_pluck simultaneously on the same completion queue. */ +grpc_event *grpc_completion_queue_pluck(grpc_completion_queue *cq, void *tag, + gpr_timespec deadline); + +/* Cleanup any data owned by the event */ +void grpc_event_finish(grpc_event *event); + +/* Begin destruction of a completion queue. Once all possible events are + drained it's safe to call grpc_completion_queue_destroy. */ +void grpc_completion_queue_shutdown(grpc_completion_queue *cq); + +/* Destroy a completion queue. The caller must ensure that the queue is + drained and no threads are executing grpc_completion_queue_next */ +void grpc_completion_queue_destroy(grpc_completion_queue *cq); + +/* Create a call given a grpc_channel, in order to call 'method'. The request + is not sent until grpc_call_invoke is called. All completions are sent to + 'completion_queue'. */ +grpc_call *grpc_channel_create_call(grpc_channel *channel, const char *method, + const char *host, gpr_timespec deadline); + +/* Create a client channel */ +grpc_channel *grpc_channel_create(const char *target, + const grpc_channel_args *args); + +/* Close and destroy a grpc channel */ +void grpc_channel_destroy(grpc_channel *channel); + +/* THREAD-SAFETY for grpc_call + The following functions are thread-compatible for any given call: + grpc_call_add_metadata + grpc_call_invoke + grpc_call_start_write + grpc_call_writes_done + grpc_call_start_read + grpc_call_destroy + The function grpc_call_cancel is thread-safe, and can be called at any + point before grpc_call_destroy is called. */ + +/* Error handling for grpc_call + Most grpc_call functions return a grpc_error. If the error is not GRPC_OK + then the operation failed due to some unsatisfied precondition. + If a grpc_call fails, it's guaranteed that no change to the call state + has been made. */ + +/* Add a single metadata element to the call, to be sent upon invocation. + flags is a bit-field combination of the write flags defined above. + REQUIRES: grpc_call_start_invoke/grpc_call_accept have not been called on + this call. + Produces no events. */ +grpc_call_error grpc_call_add_metadata(grpc_call *call, grpc_metadata *metadata, + gpr_uint32 flags); + +/* Invoke the RPC. Starts sending metadata and request headers on the wire. + flags is a bit-field combination of the write flags defined above. + REQUIRES: Can be called at most once per call. + Can only be called on the client. + Produces a GRPC_INVOKE_ACCEPTED event with invoke_accepted_tag when the + call has been invoked (meaning bytes can start flowing to the wire). + Produces a GRPC_CLIENT_METADATA_READ event with metadata_read_tag when + the servers initial metadata has been read. + Produces a GRPC_FINISHED event with finished_tag when the call has been + completed (there may be other events for the call pending at this + time) */ +grpc_call_error grpc_call_start_invoke(grpc_call *call, + grpc_completion_queue *cq, + void *invoke_accepted_tag, + void *metadata_read_tag, + void *finished_tag, gpr_uint32 flags); + +/* Accept an incoming RPC, binding a completion queue to it. + To be called after adding metadata to the call, but before sending + messages. + flags is a bit-field combination of the write flags defined above. + REQUIRES: Can be called at most once per call. + Can only be called on the server. + Produces a GRPC_FINISHED event with finished_tag when the call has been + completed (there may be other events for the call pending at this + time) */ +grpc_call_error grpc_call_accept(grpc_call *call, grpc_completion_queue *cq, + void *finished_tag, gpr_uint32 flags); + +/* Called by clients to cancel an RPC on the server. + Can be called multiple times, from any thread. */ +grpc_call_error grpc_call_cancel(grpc_call *call); + +/* Queue a byte buffer for writing. + flags is a bit-field combination of the write flags defined above. + A write with byte_buffer null is allowed, and will not send any bytes on the + wire. If this is performed without GRPC_WRITE_BUFFER_HINT flag it provides + a mechanism to flush any previously buffered writes to outgoing flow control. + REQUIRES: No other writes are pending on the call. It is only safe to + start the next write after the corresponding write_accepted event + is received. + GRPC_INVOKE_ACCEPTED must have been received by the application + prior to calling this on the client. On the server, + grpc_call_accept must have been called successfully. + Produces a GRPC_WRITE_ACCEPTED event. */ +grpc_call_error grpc_call_start_write(grpc_call *call, + grpc_byte_buffer *byte_buffer, void *tag, + gpr_uint32 flags); + +/* Queue a status for writing. + REQUIRES: No other writes are pending on the call. + grpc_call_accept must have been called on the call prior to calling + this. + Only callable on the server. + Produces a GRPC_FINISH_ACCEPTED event when the status is sent. */ +grpc_call_error grpc_call_start_write_status(grpc_call *call, + grpc_status status, void *tag); + +/* No more messages to send. + REQUIRES: No other writes are pending on the call. + Only callable on the client. + Produces a GRPC_FINISH_ACCEPTED event when all bytes for the call have passed + outgoing flow control. */ +grpc_call_error grpc_call_writes_done(grpc_call *call, void *tag); + +/* Initiate a read on a call. Output event contains a byte buffer with the + result of the read. + REQUIRES: No other reads are pending on the call. It is only safe to start + the next read after the corresponding read event is received. + GRPC_INVOKE_ACCEPTED must have been received by the application + prior to calling this. + Produces a single GRPC_READ event. */ +grpc_call_error grpc_call_start_read(grpc_call *call, void *tag); + +/* Destroy a call. */ +void grpc_call_destroy(grpc_call *call); + +/* Request a call on a server. + Allows the server to create a single GRPC_SERVER_RPC_NEW event, with tag + tag_new. + If the call is subsequently cancelled, the cancellation will occur with tag + tag_cancel. + REQUIRES: Server must not have been shutdown. + NOTE: calling this is the only way to obtain GRPC_SERVER_RPC_NEW events. */ +grpc_call_error grpc_server_request_call(grpc_server *server, void *tag_new); + +/* Create a server */ +grpc_server *grpc_server_create(grpc_completion_queue *cq, + const grpc_channel_args *args); + +/* Add a http2 over tcp listener; returns 1 on success, 0 on failure + REQUIRES: server not started */ +int grpc_server_add_http2_port(grpc_server *server, const char *addr); + +/* Add a secure port to server; returns 1 on success, 0 on failure + REQUIRES: server not started */ +int grpc_server_add_secure_http2_port(grpc_server *server, const char *addr); + +/* Start a server - tells all listeners to start listening */ +void grpc_server_start(grpc_server *server); + +/* Begin shutting down a server. */ +void grpc_server_shutdown(grpc_server *server); + +/* Destroy a server */ +void grpc_server_destroy(grpc_server *server); + +#ifdef __cplusplus +} +#endif + +#endif /* __GRPC_GRPC_H__ */ diff --git a/include/grpc/grpc_security.h b/include/grpc/grpc_security.h new file mode 100644 index 0000000000..cc1d74c81e --- /dev/null +++ b/include/grpc/grpc_security.h @@ -0,0 +1,143 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 GRPC_SECURITY_H_ +#define GRPC_SECURITY_H_ + +#include "grpc.h" +#include "status.h" + +/* --- grpc_credentials object. --- + + A credentials object represents a way to authenticate a client. */ + +typedef struct grpc_credentials grpc_credentials; + +/* Releases a credentials object. + The creator of the credentials object is responsible for its release. */ +void grpc_credentials_release(grpc_credentials *creds); + +/* Creates default credentials. */ +grpc_credentials *grpc_default_credentials_create(void); + +/* Creates an SSL credentials object. + - pem_roots_cert is the buffer containing the PEM encoding of the server + root certificates. This parameter cannot be NULL. + - pem_roots_cert_size is the size of the associated buffer. + - pem_private_key is the buffer containing the PEM encoding of the client's + private key. This parameter can be NULL if the client does not have a + private key. + - pem_private_key_size is the size of the associated buffer. + - pem_cert_chain is the buffer containing the PEM encoding of the client's + certificate chain. This parameter can be NULL if the client does not have + a certificate chain. + - pem_cert_chain_size is the size of the associated buffer. */ +grpc_credentials *grpc_ssl_credentials_create( + const unsigned char *pem_root_certs, size_t pem_root_certs_size, + const unsigned char *pem_private_key, size_t pem_private_key_size, + const unsigned char *pem_cert_chain, size_t pem_cert_chain_size); + +/* Creates a composite credentials object. */ +grpc_credentials *grpc_composite_credentials_create(grpc_credentials *creds1, + grpc_credentials *creds2); + +/* Creates a compute engine credentials object. */ +grpc_credentials *grpc_compute_engine_credentials_create(void); + +/* Creates a fake transport security credentials object for testing. */ +grpc_credentials *grpc_fake_transport_security_credentials_create(void); + + +/* --- Secure channel creation. --- */ + +/* The caller of the secure_channel_create functions may override the target + name used for SSL host name checking using this channel argument which is of + type GRPC_ARG_STRING. This *should* be used for testing only. + If this argument is not specified, the name used for SSL host name checking + will be the target parameter (assuming that the secure channel is an SSL + channel). If this parameter is specified and the underlying is not an SSL + channel, it will just be ignored. */ +#define GRPC_SSL_TARGET_NAME_OVERRIDE_ARG "grpc.ssl_target_name_override" + +/* Creates a default secure channel using the default credentials object using + the environment. */ +grpc_channel *grpc_default_secure_channel_create(const char *target, + const grpc_channel_args *args); + +/* Creates a secure channel using the passed-in credentials. */ +grpc_channel *grpc_secure_channel_create(grpc_credentials *creds, + const char *target, + const grpc_channel_args *args); + +/* --- grpc_server_credentials object. --- + + A server credentials object represents a way to authenticate a server. */ + +typedef struct grpc_server_credentials grpc_server_credentials; + +/* Releases a server_credentials object. + The creator of the server_credentials object is responsible for its release. + */ +void grpc_server_credentials_release(grpc_server_credentials *creds); + +/* Creates an SSL server_credentials object. + TODO(jboeuf): Change the constructor so that it can support multiple + key/cert pairs. + - pem_roots_cert is the buffer containing the PEM encoding of the server + root certificates. This parameter may be NULL if the server does not want + the client to be authenticated with SSL. + - pem_roots_cert_size is the size of the associated buffer. + - pem_private_key is the buffer containing the PEM encoding of the client's + private key. This parameter cannot be NULL. + - pem_private_key_size is the size of the associated buffer. + - pem_cert_chain is the buffer containing the PEM encoding of the client's + certificate chain. This parameter cannot be NULL. + - pem_cert_chain_size is the size of the associated buffer. */ +grpc_server_credentials *grpc_ssl_server_credentials_create( + const unsigned char *pem_root_certs, size_t pem_root_certs_size, + const unsigned char *pem_private_key, size_t pem_private_key_size, + const unsigned char *pem_cert_chain, size_t pem_cert_chain_size); + +/* Creates a fake server transport security credentials object for testing. */ +grpc_server_credentials *grpc_fake_transport_security_server_credentials_create( + void); + + +/* --- Secure server creation. --- */ + +/* Creates a secure server using the passed-in server credentials. */ +grpc_server *grpc_secure_server_create(grpc_server_credentials *creds, + grpc_completion_queue *cq, + const grpc_channel_args *args); + +#endif /* GRPC_SECURITY_H_ */ diff --git a/include/grpc/status.h b/include/grpc/status.h new file mode 100644 index 0000000000..a4ce312bf2 --- /dev/null +++ b/include/grpc/status.h @@ -0,0 +1,203 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_STATUS_H__ +#define __GRPC_STATUS_H__ + + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + /* Not an error; returned on success + + HTTP Mapping: 200 OK */ + GRPC_STATUS_OK = 0, + + /* The operation was cancelled (typically by the caller). + + HTTP Mapping: 499 Client Closed Request */ + GRPC_STATUS_CANCELLED = 1, + + /* Unknown error. An example of where this error may be returned is + if a Status value received from another address space belongs to + an error-space that is not known in this address space. Also + errors raised by APIs that do not return enough error information + may be converted to this error. + + HTTP Mapping: 500 Internal Server Error */ + GRPC_STATUS_UNKNOWN = 2, + + /* Client specified an invalid argument. Note that this differs + from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments + that are problematic regardless of the state of the system + (e.g., a malformed file name). + + HTTP Mapping: 400 Bad Request */ + GRPC_STATUS_INVALID_ARGUMENT = 3, + + /* Deadline expired before operation could complete. For operations + that change the state of the system, this error may be returned + even if the operation has completed successfully. For example, a + successful response from a server could have been delayed long + enough for the deadline to expire. + + HTTP Mapping: 504 Gateway Timeout */ + GRPC_STATUS_DEADLINE_EXCEEDED = 4, + + /* Some requested entity (e.g., file or directory) was not found. + + HTTP Mapping: 404 Not Found */ + GRPC_STATUS_NOT_FOUND = 5, + + /* Some entity that we attempted to create (e.g., file or directory) + already exists. + + HTTP Mapping: 409 Conflict */ + GRPC_STATUS_ALREADY_EXISTS = 6, + + /* The caller does not have permission to execute the specified + operation. PERMISSION_DENIED must not be used for rejections + caused by exhausting some resource (use RESOURCE_EXHAUSTED + instead for those errors). PERMISSION_DENIED must not be + used if the caller can not be identified (use UNAUTHENTICATED + instead for those errors). + + HTTP Mapping: 403 Forbidden */ + GRPC_STATUS_PERMISSION_DENIED = 7, + + /* The request does not have valid authentication credentials for the + operation. + + HTTP Mapping: 401 Unauthorized */ + GRPC_STATUS_UNAUTHENTICATED = 16, + + /* Some resource has been exhausted, perhaps a per-user quota, or + perhaps the entire file system is out of space. + + HTTP Mapping: 429 Too Many Requests */ + GRPC_STATUS_RESOURCE_EXHAUSTED = 8, + + /* Operation was rejected because the system is not in a state + required for the operation's execution. For example, directory + to be deleted may be non-empty, an rmdir operation is applied to + a non-directory, etc. + + A litmus test that may help a service implementor in deciding + between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + (a) Use UNAVAILABLE if the client can retry just the failing call. + (b) Use ABORTED if the client should retry at a higher-level + (e.g., restarting a read-modify-write sequence). + (c) Use FAILED_PRECONDITION if the client should not retry until + the system state has been explicitly fixed. E.g., if an "rmdir" + fails because the directory is non-empty, FAILED_PRECONDITION + should be returned since the client should not retry unless + they have first fixed up the directory by deleting files from it. + (d) Use FAILED_PRECONDITION if the client performs conditional + REST Get/Update/Delete on a resource and the resource on the + server does not match the condition. E.g., conflicting + read-modify-write on the same resource. + + HTTP Mapping: 400 Bad Request + + NOTE: HTTP spec says 412 Precondition Failed should only be used if + the request contains Etag related headers. So if the server does see + Etag related headers in the request, it may choose to return 412 + instead of 400 for this error code. */ + GRPC_STATUS_FAILED_PRECONDITION = 9, + + /* The operation was aborted, typically due to a concurrency issue + like sequencer check failures, transaction aborts, etc. + + See litmus test above for deciding between FAILED_PRECONDITION, + ABORTED, and UNAVAILABLE. + + HTTP Mapping: 409 Conflict */ + GRPC_STATUS_ABORTED = 10, + + /* Operation was attempted past the valid range. E.g., seeking or + reading past end of file. + + Unlike INVALID_ARGUMENT, this error indicates a problem that may + be fixed if the system state changes. For example, a 32-bit file + system will generate INVALID_ARGUMENT if asked to read at an + offset that is not in the range [0,2^32-1], but it will generate + OUT_OF_RANGE if asked to read from an offset past the current + file size. + + There is a fair bit of overlap between FAILED_PRECONDITION and + OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific + error) when it applies so that callers who are iterating through + a space can easily look for an OUT_OF_RANGE error to detect when + they are done. + + HTTP Mapping: 400 Bad Request */ + GRPC_STATUS_OUT_OF_RANGE = 11, + + /* Operation is not implemented or not supported/enabled in this service. + + HTTP Mapping: 501 Not Implemented */ + GRPC_STATUS_UNIMPLEMENTED = 12, + + /* Internal errors. Means some invariants expected by underlying + system has been broken. If you see one of these errors, + something is very broken. + + HTTP Mapping: 500 Internal Server Error */ + GRPC_STATUS_INTERNAL = 13, + + /* The service is currently unavailable. This is a most likely a + transient condition and may be corrected by retrying with + a backoff. + + See litmus test above for deciding between FAILED_PRECONDITION, + ABORTED, and UNAVAILABLE. + + HTTP Mapping: 503 Service Unavailable */ + GRPC_STATUS_UNAVAILABLE = 14, + + /* Unrecoverable data loss or corruption. + + HTTP Mapping: 500 Internal Server Error */ + GRPC_STATUS_DATA_LOSS = 15, + + /* Force users to include a default branch: */ + GRPC_STATUS__DO_NOT_USE = -1 +} grpc_status_code; + +#ifdef __cplusplus +} +#endif + +#endif /* __GRPC_STATUS_H__ */ diff --git a/include/grpc/support/alloc.h b/include/grpc/support/alloc.h new file mode 100644 index 0000000000..d613d85683 --- /dev/null +++ b/include/grpc/support/alloc.h @@ -0,0 +1,58 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_ALLOC_H__ +#define __GRPC_SUPPORT_ALLOC_H__ + +#include <stddef.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/* malloc, never returns NULL */ +void *gpr_malloc(size_t size); +/* free */ +void gpr_free(void *ptr); +/* realloc, never returns NULL */ +void *gpr_realloc(void *p, size_t size); +/* aligned malloc, never returns NULL, alignment must be power of 2 */ +void *gpr_malloc_aligned(size_t size, size_t alignment); +/* free memory allocated by gpr_malloc_aligned */ +void gpr_free_aligned(void *ptr); + +#ifdef __cplusplus +} +#endif + +#endif /* __GRPC_SUPPORT_ALLOC_H__ */ diff --git a/include/grpc/support/atm.h b/include/grpc/support/atm.h new file mode 100644 index 0000000000..d9fd383209 --- /dev/null +++ b/include/grpc/support/atm.h @@ -0,0 +1,92 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_ATM_H__ +#define __GRPC_SUPPORT_ATM_H__ + +/* This interface provides atomic operations and barriers. + It is internal to gpr support code and should not be used outside it. + + If an operation with acquire semantics precedes another memory access by the + same thread, the operation will precede that other access as seen by other + threads. + + If an operation with release semantics follows another memory access by the + same thread, the operation will follow that other access as seen by other + threads. + + Routines with "acq" or "full" in the name have acquire semantics. Routines + with "rel" or "full" in the name have release semantics. Routines with + "no_barrier" in the name have neither acquire not release semantics. + + The routines may be implemented as macros. + + // Atomic operations acton an intergral_type gpr_atm that is guaranteed to + // be the same size as a pointer. + typedef gpr_intptr gpr_atm; + + // A memory barrier, providing both acquire and release semantics, but not + // otherwise acting no memory. + void gpr_atm_full_barrier(void); + + // Atomically return *p, with acquire semantics. + gpr_atm gpr_atm_acq_load(gpr_atm *p); + + // Atomically set *p = value, with release semantics. + void gpr_atm_rel_store(gpr_atm *p, gpr_atm value); + + // Atomically add delta to *p, and return the old value of *p, with + // the barriers specified. + gpr_atm gpr_atm_no_barrier_fetch_add(gpr_atm *p, gpr_atm delta); + gpr_atm gpr_atm_full_fetch_add(gpr_atm *p, gpr_atm delta); + + // Atomically, if *p==o, set *p=n and return non-zero otherwise return 0, + // with the barriers specified if the operation succeeds. + int gpr_atm_no_barrier_cas(gpr_atm *p, gpr_atm o, gpr_atm n); + int gpr_atm_acq_cas(gpr_atm *p, gpr_atm o, gpr_atm n); + int gpr_atm_rel_cas(gpr_atm *p, gpr_atm o, gpr_atm n); +*/ + +#include <grpc/support/port_platform.h> + +#if defined(GPR_GCC_ATOMIC) +#include <grpc/support/atm_gcc_atomic.h> +#elif defined(GPR_GCC_SYNC) +#include <grpc/support/atm_gcc_sync.h> +#elif defined(GPR_WIN32) +#include <grpc/support/atm_win32.h> +#else +#error could not determine platform for atm +#endif + +#endif /* __GRPC_SUPPORT_ATM_H__ */ diff --git a/include/grpc/support/atm_gcc_atomic.h b/include/grpc/support/atm_gcc_atomic.h new file mode 100644 index 0000000000..4e0a7ab1c6 --- /dev/null +++ b/include/grpc/support/atm_gcc_atomic.h @@ -0,0 +1,69 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_ATM_GCC_ATOMIC_H__ +#define __GRPC_SUPPORT_ATM_GCC_ATOMIC_H__ + +/* atm_platform.h for gcc and gcc-like compilers with the + __atomic_* interface. */ +#include <grpc/support/port_platform.h> + +typedef gpr_intptr gpr_atm; + +#define gpr_atm_full_barrier() (__atomic_thread_fence(__ATOMIC_SEQ_CST)) + +#define gpr_atm_acq_load(p) (__atomic_load_n((p), __ATOMIC_ACQUIRE)) +#define gpr_atm_rel_store(p, value) \ + (__atomic_store_n((p), (gpr_intptr)(value), __ATOMIC_RELEASE)) + +#define gpr_atm_no_barrier_fetch_add(p, delta) \ + (__atomic_fetch_add((p), (gpr_intptr)(delta), __ATOMIC_RELAXED)) +#define gpr_atm_full_fetch_add(p, delta) \ + (__atomic_fetch_add((p), (gpr_intptr)(delta), __ATOMIC_ACQ_REL)) + +static __inline int gpr_atm_no_barrier_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { + return __atomic_compare_exchange_n(p, &o, n, 0, __ATOMIC_RELAXED, + __ATOMIC_RELAXED); +} + +static __inline int gpr_atm_acq_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { + return __atomic_compare_exchange_n(p, &o, n, 0, __ATOMIC_ACQUIRE, + __ATOMIC_RELAXED); +} + +static __inline int gpr_atm_rel_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { + return __atomic_compare_exchange_n(p, &o, n, 0, __ATOMIC_RELEASE, + __ATOMIC_RELAXED); +} + +#endif /* __GRPC_SUPPORT_ATM_GCC_ATOMIC_H__ */ diff --git a/include/grpc/support/atm_gcc_sync.h b/include/grpc/support/atm_gcc_sync.h new file mode 100644 index 0000000000..30570da540 --- /dev/null +++ b/include/grpc/support/atm_gcc_sync.h @@ -0,0 +1,69 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_ATM_GCC_SYNC_H__ +#define __GRPC_SUPPORT_ATM_GCC_SYNC_H__ + +/* atm_platform.h for gcc and gcc-like compilers with the + __atomic_* interface. */ +#include <grpc/support/port_platform.h> + +typedef gpr_intptr gpr_atm; + +#define gpr_atm_full_barrier() (__atomic_thread_fence(__ATOMIC_SEQ_CST)) + +#define gpr_atm_acq_load(p) (__atomic_load_n((p), __ATOMIC_ACQUIRE)) +#define gpr_atm_rel_store(p, value) \ + (__atomic_store_n((p), (gpr_intptr)(value), __ATOMIC_RELEASE)) + +#define gpr_atm_no_barrier_fetch_add(p, delta) \ + (__atomic_fetch_add((p), (gpr_intptr)(delta), __ATOMIC_RELAXED)) +#define gpr_atm_full_fetch_add(p, delta) \ + (__atomic_fetch_add((p), (gpr_intptr)(delta), __ATOMIC_ACQ_REL)) + +static __inline int gpr_atm_no_barrier_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { + return __atomic_compare_exchange_n(p, &o, n, 0, __ATOMIC_RELAXED, + __ATOMIC_RELAXED); +} + +static __inline int gpr_atm_acq_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { + return __atomic_compare_exchange_n(p, &o, n, 0, __ATOMIC_ACQUIRE, + __ATOMIC_RELAXED); +} + +static __inline int gpr_atm_rel_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { + return __atomic_compare_exchange_n(p, &o, n, 0, __ATOMIC_RELEASE, + __ATOMIC_RELAXED); +} + +#endif /* __GRPC_SUPPORT_ATM_GCC_SYNC_H__ */ diff --git a/include/grpc/support/atm_win32.h b/include/grpc/support/atm_win32.h new file mode 100644 index 0000000000..9b2f0e84ba --- /dev/null +++ b/include/grpc/support/atm_win32.h @@ -0,0 +1,94 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_ATM_WIN32_H__ +#define __GRPC_SUPPORT_ATM_WIN32_H__ + +/* Win32 variant of atm_platform.h */ +#include <grpc/support/port_platform.h> + +#include <windows.h> + +typedef gpr_intptr gpr_atm; + +#define gpr_atm_full_barrier MemoryBarrier + +static __inline gpr_atm gpr_atm_acq_load(const gpr_atm *p) { + gpr_atm result = *p; + gpr_atm_full_barrier(); + return result; +} + +static __inline void gpr_atm_rel_store(gpr_atm *p, gpr_atm value) { + gpr_atm_full_barrier(); + *p = value; +} + +static __inline int gpr_atm_no_barrier_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { + /* InterlockedCompareExchangePointerNoFence() not available on vista or + windows7 */ + return o == (gpr_atm)InterlockedCompareExchangePointerAcquire(p, (void *)n, + (void *)o); +} + +static __inline int gpr_atm_acq_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { + return o == (gpr_atm)InterlockedCompareExchangePointerAcquire(p, (void *)n, + (void *)o); +} + +static __inline int gpr_atm_rel_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { + return o == (gpr_atm)InterlockedCompareExchangePointerRelease(p, (void *)n, + (void *)o); +} + +static __inline gpr_atm gpr_atm_no_barrier_fetch_add(gpr_atm *p, + gpr_atm delta) { + /* Use the CAS operation to get pointer-sized fetch and add */ + gpr_atm old; + do { + old = *p; + } while (!gpr_atm_no_barrier_cas(p, old, old + delta)); + return old; +} + +static __inline gpr_atm gpr_atm_full_fetch_add(gpr_atm *p, gpr_atm delta) { + /* Use a CAS operation to get pointer-sized fetch and add */ + gpr_atm old; + do { + old = *p; + } while (old != (gpr_atm)InterlockedCompareExchangePointer( + p, (void *)(old + delta), (void *)old)); + return old; +} + +#endif /* __GRPC_SUPPORT_ATM_WIN32_H__ */ diff --git a/include/grpc/support/cancellable_platform.h b/include/grpc/support/cancellable_platform.h new file mode 100644 index 0000000000..d67302dd90 --- /dev/null +++ b/include/grpc/support/cancellable_platform.h @@ -0,0 +1,56 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_CANCELLABLE_PLATFORM_H__ +#define __GRPC_SUPPORT_CANCELLABLE_PLATFORM_H__ + +#include <grpc/support/atm.h> +#include <grpc/support/sync.h> + +struct gpr_cancellable_list_ { + /* a doubly-linked list on cancellable's waiters queue */ + struct gpr_cancellable_list_ *next; + struct gpr_cancellable_list_ *prev; + /* The following two fields are arguments to gpr_cv_cancellable_wait() */ + gpr_mu *mu; + gpr_cv *cv; +}; + +/* Internal definition of gpr_cancellable. */ +typedef struct { + gpr_mu mu; /* protects waiters and modifications to cancelled */ + gpr_atm cancelled; + struct gpr_cancellable_list_ waiters; +} gpr_cancellable; + +#endif /* __GRPC_SUPPORT_CANCELLABLE_PLATFORM_H__ */ diff --git a/include/grpc/support/cmdline.h b/include/grpc/support/cmdline.h new file mode 100644 index 0000000000..60e8035c75 --- /dev/null +++ b/include/grpc/support/cmdline.h @@ -0,0 +1,95 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_CMDLINE_H__ +#define __GRPC_SUPPORT_CMDLINE_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Simple command line parser. + + Supports flags that can be specified as -foo, --foo, --no-foo, -no-foo, etc + And integers, strings that can be specified as -foo=4, -foo blah, etc + + No support for short command line options (but we may get that in the + future.) + + Usage (for a program with a single flag argument 'foo'): + + int main(int argc, char **argv) { + gpr_cmdline *cl; + int verbose = 0; + + cl = gpr_cmdline_create("My cool tool"); + gpr_cmdline_add_int(cl, "verbose", "Produce verbose output?", &verbose); + gpr_cmdline_parse(cl, argc, argv); + gpr_cmdline_destroy(cl); + + if (verbose) { + gpr_log(GPR_INFO, "Goodbye cruel world!"); + } + + return 0; + } */ + +typedef struct gpr_cmdline gpr_cmdline; + +/* Construct a command line parser: takes a short description of the tool + doing the parsing */ +gpr_cmdline *gpr_cmdline_create(const char *description); +/* Add an integer parameter, with a name (used on the command line) and some + helpful text (used in the command usage) */ +void gpr_cmdline_add_int(gpr_cmdline *cl, const char *name, const char *help, + int *value); +/* The same, for a boolean flag */ +void gpr_cmdline_add_flag(gpr_cmdline *cl, const char *name, const char *help, + int *value); +/* And for a string */ +void gpr_cmdline_add_string(gpr_cmdline *cl, const char *name, const char *help, + char **value); +/* Set a callback for non-named arguments */ +void gpr_cmdline_on_extra_arg( + gpr_cmdline *cl, const char *name, const char *help, + void (*on_extra_arg)(void *user_data, const char *arg), void *user_data); +/* Parse the command line */ +void gpr_cmdline_parse(gpr_cmdline *cl, int argc, char **argv); +/* Destroy the parser */ +void gpr_cmdline_destroy(gpr_cmdline *cl); + +#ifdef __cplusplus +} +#endif + +#endif /* __GRPC_SUPPORT_CMDLINE_H__ */ diff --git a/include/grpc/support/histogram.h b/include/grpc/support/histogram.h new file mode 100644 index 0000000000..13dce3bdcd --- /dev/null +++ b/include/grpc/support/histogram.h @@ -0,0 +1,66 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_HISTOGRAM_H__ +#define __GRPC_SUPPORT_HISTOGRAM_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct gpr_histogram gpr_histogram; + +gpr_histogram *gpr_histogram_create(double resolution, double max_bucket_start); +void gpr_histogram_destroy(gpr_histogram *h); +void gpr_histogram_add(gpr_histogram *h, double x); + +/* The following merges the second histogram into the first. It only works + if they have the same buckets and resolution. Returns 0 on failure, 1 + on success */ +int gpr_histogram_merge(gpr_histogram *dst, gpr_histogram *src); + +double gpr_histogram_percentile(gpr_histogram *histogram, double percentile); +double gpr_histogram_mean(gpr_histogram *histogram); +double gpr_histogram_stddev(gpr_histogram *histogram); +double gpr_histogram_variance(gpr_histogram *histogram); +double gpr_histogram_maximum(gpr_histogram *histogram); +double gpr_histogram_minimum(gpr_histogram *histogram); +double gpr_histogram_count(gpr_histogram *histogram); +double gpr_histogram_sum(gpr_histogram *histogram); +double gpr_histogram_sum_of_squares(gpr_histogram *histogram); + +#ifdef __cplusplus +} +#endif + +#endif /* __GRPC_SUPPORT_HISTOGRAM_H__ */ diff --git a/include/grpc/support/host_port.h b/include/grpc/support/host_port.h new file mode 100644 index 0000000000..9495bfea40 --- /dev/null +++ b/include/grpc/support/host_port.h @@ -0,0 +1,57 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_HOST_PORT_H__ +#define __GRPC_SUPPORT_HOST_PORT_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Given a host and port, creates a newly-allocated string of the form + "host:port" or "[ho:st]:port", depending on whether the host contains colons + like an IPv6 literal. If the host is already bracketed, then additional + brackets will not be added. + + Usage is similar to gpr_asprintf: returns the number of bytes written + (excluding the final '\0'), and *out points to a string which must later be + destroyed using gpr_free(). + + In the unlikely event of an error, returns -1 and sets *out to NULL. */ +int gpr_join_host_port(char **out, const char *host, int port); + +#ifdef __cplusplus +} +#endif + +#endif /* __GRPC_SUPPORT_HOST_PORT_H__ */ diff --git a/include/grpc/support/log.h b/include/grpc/support/log.h new file mode 100644 index 0000000000..b79d661f65 --- /dev/null +++ b/include/grpc/support/log.h @@ -0,0 +1,91 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_LOG_H__ +#define __GRPC_SUPPORT_LOG_H__ + +#include <stdlib.h> /* for abort() */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* GPR log API. + + Usage (within grpc): + + int argument1 = 3; + char* argument2 = "hello"; + gpr_log(GPR_DEBUG, "format string %d", argument1); + gpr_log(GPR_INFO, "hello world"); + gpr_log(GPR_ERROR, "%d %s!!", argument1, argument2); */ + +/* The severity of a log message - use the #defines below when calling into + gpr_log to additionally supply file and line data */ +typedef enum gpr_log_severity { + GPR_LOG_SEVERITY_DEBUG, + GPR_LOG_SEVERITY_INFO, + GPR_LOG_SEVERITY_ERROR +} gpr_log_severity; + +/* Returns a string representation of the log severity */ +const char *gpr_log_severity_string(gpr_log_severity severity); + +/* Macros to build log contexts at various severity levels */ +#define GPR_DEBUG __FILE__, __LINE__, GPR_LOG_SEVERITY_DEBUG +#define GPR_INFO __FILE__, __LINE__, GPR_LOG_SEVERITY_INFO +#define GPR_ERROR __FILE__, __LINE__, GPR_LOG_SEVERITY_ERROR + +/* Log a message. It's advised to use GPR_xxx above to generate the context + * for each message */ +void gpr_log(const char *file, int line, gpr_log_severity severity, + const char *format, ...); + +/* abort() the process if x is zero, having written a line to the log. + + Intended for internal invariants. If the error can be recovered from, + without the possibility of corruption, or might best be reflected via + an exception in a higher-level language, consider returning error code. */ +#define GPR_ASSERT(x) \ + do { \ + if (!(x)) { \ + gpr_log(GPR_ERROR, "assertion failed: %s", #x); \ + abort(); \ + } \ + } while (0) + +#ifdef __cplusplus +} +#endif + +#endif /* __GRPC_SUPPORT_LOG_H__ */ diff --git a/include/grpc/support/port_platform.h b/include/grpc/support/port_platform.h new file mode 100644 index 0000000000..592fce60da --- /dev/null +++ b/include/grpc/support/port_platform.h @@ -0,0 +1,132 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_PORT_PLATFORM_H__ +#define __GRPC_SUPPORT_PORT_PLATFORM_H__ + +/* Override this file with one for your platform if you need to redefine + things. */ + +/* For a common case, assume that the platform has a C99-like stdint.h */ + +#include <stdint.h> + +#if !defined(GPR_NO_AUTODETECT_PLATFORM) +#if defined(_WIN64) || defined(WIN64) +#define GPR_WIN32 1 +#define GPR_ARCH_64 1 +#define GPR_POSIX_SOCKETUTILS 1 +#elif defined(_WIN32) || defined(WIN32) +#define GPR_WIN32 1 +#define GPR_ARCH_32 1 +#define GPR_POSIX_SOCKETUTILS 1 +#elif defined(ANDROID) || defined(__ANDROID__) +#define GPR_POSIX_TIME 1 +#define GPR_POSIX_SYNC 1 +#define GPR_POSIX_SOCKETUTILS 1 +#define GPR_ANDROID 1 +#define GPR_GCC_SYNC 1 +#define GPR_ARCH_32 1 +#elif defined(__linux__) +#define GPR_POSIX_TIME 1 +#define GPR_POSIX_SYNC 1 +#define GPR_LINUX 1 +#define GPR_GCC_ATOMIC 1 +#ifdef _LP64 +#define GPR_ARCH_64 1 +#else /* _LP64 */ +#define GPR_ARCH_32 1 +#endif /* _LP64 */ +#elif defined(__APPLE__) +#define GPR_POSIX_TIME 1 +#define GPR_POSIX_SYNC 1 +#define GPR_POSIX_LOG 1 +#define GPR_POSIX_SOCKETUTILS 1 +#define GPR_GCC_ATOMIC 1 +#ifdef _LP64 +#define GPR_ARCH_64 1 +#else /* _LP64 */ +#define GPR_ARCH_32 1 +#endif /* _LP64 */ +#else +#error Could not auto-detect platform +#endif +#endif /* GPR_NO_AUTODETECT_PLATFORM */ + +/* Cache line alignment */ +#ifndef GPR_CACHELINE_SIZE +#if defined(__i386__) || defined(__x86_64__) +#define GPR_CACHELINE_SIZE 64 +#endif +#ifndef GPR_CACHELINE_SIZE +/* A reasonable default guess. Note that overestimates tend to waste more + space, while underestimates tend to waste more time. */ +#define GPR_CACHELINE_SIZE 64 +#endif /* GPR_CACHELINE_SIZE */ +#endif /* GPR_CACHELINE_SIZE */ + +/* scrub GCC_ATOMIC if it's not available on this compiler */ +#if defined(GPR_GCC_ATOMIC) && !defined(__ATOMIC_RELAXED) +#undef GPR_GCC_ATOMIC +#define GPR_GCC_SYNC 1 +#endif + +/* Validate platform combinations */ +#if defined(GPR_GCC_ATOMIC) + defined(GPR_GCC_SYNC) + defined(GPR_WIN32) != 1 +#error Must define exactly one of GPR_GCC_ATOMIC, GPR_GCC_SYNC, GPR_WIN32 +#endif + +#if defined(GPR_ARCH_32) + defined(GPR_ARCH_64) != 1 +#error Must define exactly one of GPR_ARCH_32, GPR_ARCH_64 +#endif + +typedef int16_t gpr_int16; +typedef int32_t gpr_int32; +typedef int64_t gpr_int64; +typedef uint8_t gpr_uint8; +typedef uint16_t gpr_uint16; +typedef uint32_t gpr_uint32; +typedef uint64_t gpr_uint64; +typedef intmax_t gpr_intmax; +typedef intptr_t gpr_intptr; +typedef uintmax_t gpr_uintmax; +typedef uintptr_t gpr_uintptr; + +/* INT64_MAX is unavailable on some platforms. */ +#define GPR_INT64_MAX (~(gpr_uint64)0 >> 1) + +/* maximum alignment needed for any type on this platform, rounded up to a + power of two */ +#define GPR_MAX_ALIGNMENT 16 + +#endif /* __GRPC_SUPPORT_PORT_PLATFORM_H__ */ diff --git a/include/grpc/support/slice.h b/include/grpc/support/slice.h new file mode 100644 index 0000000000..6678f39256 --- /dev/null +++ b/include/grpc/support/slice.h @@ -0,0 +1,175 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_SLICE_H__ +#define __GRPC_SUPPORT_SLICE_H__ + +#include <grpc/support/sync.h> + +#include <stddef.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/* Slice API + + A slice represents a contiguous reference counted array of bytes. + It is cheap to take references to a slice, and it is cheap to create a + slice pointing to a subset of another slice. + + The data-structure for slices is exposed here to allow non-gpr code to + build slices from whatever data they have available. + + When defining interfaces that handle slices, care should be taken to define + reference ownership semantics (who should call unref?) and mutability + constraints (is the callee allowed to modify the slice?) */ + +/* Reference count container for gpr_slice. Contains function pointers to + increment and decrement reference counts. Implementations should cleanup + when the reference count drops to zero. + Typically client code should not touch this, and use gpr_slice_malloc, + gpr_slice_new, or gpr_slice_new_with_len instead. */ +typedef struct gpr_slice_refcount { + void (*ref)(void *); + void (*unref)(void *); +} gpr_slice_refcount; + +#define GPR_SLICE_INLINED_SIZE (sizeof(size_t) + sizeof(gpr_uint8 *) - 1) + +/* A gpr_slice s, if initialized, represents the byte range + s.bytes[0..s.length-1]. + + It can have an associated ref count which has a destruction routine to be run + when the ref count reaches zero (see gpr_slice_new() and grp_slice_unref()). + Multiple gpr_slice values may share a ref count. + + If the slice does not have a refcount, it represents an inlined small piece + of data that is copied by value. */ +typedef struct gpr_slice { + struct gpr_slice_refcount *refcount; + union { + struct { + gpr_uint8 *bytes; + size_t length; + } refcounted; + struct { + gpr_uint8 length; + gpr_uint8 bytes[GPR_SLICE_INLINED_SIZE]; + } inlined; + } data; +} gpr_slice; + +#define GPR_SLICE_START_PTR(slice) \ + ((slice).refcount ? (slice).data.refcounted.bytes \ + : (slice).data.inlined.bytes) +#define GPR_SLICE_LENGTH(slice) \ + ((slice).refcount ? (slice).data.refcounted.length \ + : (slice).data.inlined.length) +#define GPR_SLICE_SET_LENGTH(slice, newlen) \ + ((slice).refcount ? ((slice).data.refcounted.length = (newlen)) \ + : ((slice).data.inlined.length = (newlen))) +#define GPR_SLICE_END_PTR(slice) \ + GPR_SLICE_START_PTR(slice) + GPR_SLICE_LENGTH(slice) + +/* Increment the refcount of s. Requires slice is initialized. + Returns s. */ +gpr_slice gpr_slice_ref(gpr_slice s); + +/* Decrement the ref count of s. If the ref count of s reaches zero, all + slices sharing the ref count are destroyed, and considered no longer + initialized. If s is ultimately derived from a call to gpr_slice_new(start, + len, dest) where dest!=NULL , then (*dest)(start, len) is called. Requires + s initialized. */ +void gpr_slice_unref(gpr_slice s); + +/* Create a slice pointing at some data. Calls malloc to allocate a refcount + for the object, and arranges that destroy will be called with the pointer + passed in at destruction. */ +gpr_slice gpr_slice_new(void *p, size_t len, void (*destroy)(void *)); + +/* Equivalent to gpr_slice_new, but with a two argument destroy function that + also takes the slice length. */ +gpr_slice gpr_slice_new_with_len(void *p, size_t len, + void (*destroy)(void *, size_t)); + +/* Equivalent to gpr_slice_new(malloc(len), len, free), but saves one malloc() + call. + Aborts if malloc() fails. */ +gpr_slice gpr_slice_malloc(size_t length); + +/* Create a slice by copying a string. + Does not preserve null terminators. + Equivalent to: + size_t len = strlen(source); + gpr_slice slice = gpr_slice_malloc(len); + memcpy(slice->data, source, len); */ +gpr_slice gpr_slice_from_copied_string(const char *source); + +/* Create a slice by copying a buffer. + Equivalent to: + gpr_slice slice = gpr_slice_malloc(len); + memcpy(slice->data, source, len); */ +gpr_slice gpr_slice_from_copied_buffer(const char *source, size_t len); + +/* Return a result slice derived from s, which shares a ref count with s, where + result.data==s.data+begin, and result.length==end-begin. + The ref count of s is increased by one. + Requires s initialized, begin <= end, begin <= s.length, and + end <= source->length. */ +gpr_slice gpr_slice_sub(gpr_slice s, size_t begin, size_t end); + +/* The same as gpr_slice_sub, but without altering the ref count */ +gpr_slice gpr_slice_sub_no_ref(gpr_slice s, size_t begin, size_t end); + +/* Splits s into two: modifies s to be s[0:split], and returns a new slice, + sharing a refcount with s, that contains s[split:s.length]. + Requires s intialized, split <= s.length */ +gpr_slice gpr_slice_split_tail(gpr_slice *s, size_t split); + +/* Splits s into two: modifies s to be s[split:s.length], and returns a new + slice, sharing a refcount with s, that contains s[0:split]. + Requires s intialized, split <= s.length */ +gpr_slice gpr_slice_split_head(gpr_slice *s, size_t split); + +gpr_slice gpr_empty_slice(); + +/* Returns <0 if a < b, ==0 if a == b, >0 if a > b */ +int gpr_slice_cmp(gpr_slice a, gpr_slice b); +int gpr_slice_str_cmp(gpr_slice a, const char *b); + +#ifdef __cplusplus +} +#endif + +#endif /* __GRPC_SUPPORT_SLICE_H__ */ diff --git a/include/grpc/support/slice_buffer.h b/include/grpc/support/slice_buffer.h new file mode 100644 index 0000000000..e4d204b827 --- /dev/null +++ b/include/grpc/support/slice_buffer.h @@ -0,0 +1,84 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_SLICE_BUFFER_H__ +#define __GRPC_SUPPORT_SLICE_BUFFER_H__ + +#include <grpc/support/slice.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/* Represents an expandable array of slices, to be interpreted as a single item + TODO(ctiller): inline some small number of elements into the struct, to + avoid per-call allocations */ +typedef struct { + /* slices in the array */ + gpr_slice *slices; + /* the number of slices in the array */ + size_t count; + /* the number of slices allocated in the array */ + size_t capacity; + /* the combined length of all slices in the array */ + size_t length; +} gpr_slice_buffer; + +/* initialize a slice buffer */ +void gpr_slice_buffer_init(gpr_slice_buffer *sb); +/* destroy a slice buffer - unrefs any held elements */ +void gpr_slice_buffer_destroy(gpr_slice_buffer *sb); +/* Add an element to a slice buffer - takes ownership of the slice. + This function is allowed to concatenate the passed in slice to the end of + some other slice if desired by the slice buffer. */ +void gpr_slice_buffer_add(gpr_slice_buffer *sb, gpr_slice slice); +/* add an element to a slice buffer - takes ownership of the slice and returns + the index of the slice. + Guarantees that the slice will not be concatenated at the end of another + slice (i.e. the data for this slice will begin at the first byte of the + slice at the returned index in sb->slices) + The implementation MAY decide to concatenate data at the end of a small + slice added in this fashion. */ +size_t gpr_slice_buffer_add_indexed(gpr_slice_buffer *sb, gpr_slice slice); +void gpr_slice_buffer_addn(gpr_slice_buffer *sb, gpr_slice *slices, size_t n); +/* add a very small (less than 8 bytes) amount of data to the end of a slice + buffer: returns a pointer into which to add the data */ +gpr_uint8 *gpr_slice_buffer_tiny_add(gpr_slice_buffer *sb, int len); +/* clear a slice buffer, unref all elements */ +void gpr_slice_buffer_reset_and_unref(gpr_slice_buffer *sb); + +#ifdef __cplusplus +} +#endif + +#endif /* __GRPC_SUPPORT_SLICE_BUFFER_H__ */ diff --git a/include/grpc/support/string.h b/include/grpc/support/string.h new file mode 100644 index 0000000000..08c8809e64 --- /dev/null +++ b/include/grpc/support/string.h @@ -0,0 +1,76 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_STRING_H__ +#define __GRPC_SUPPORT_STRING_H__ + +#include <stddef.h> + +#include <grpc/support/port_platform.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/* String utility functions */ + +/* Returns a copy of src that can be passed to gpr_free(). + If allocation fails or if src is NULL, returns NULL. */ +char *gpr_strdup(const char *src); + +/* flag to include plaintext after a hexdump */ +#define GPR_HEXDUMP_PLAINTEXT 0x00000001 + +/* Converts array buf, of length len, into a hexadecimal dump. Result should + be freed with gpr_free() */ +char *gpr_hexdump(const char *buf, size_t len, gpr_uint32 flags); + +/* Parses an array of bytes into an integer (base 10). Returns 1 on success, + 0 on failure. */ +int gpr_parse_bytes_to_uint32(const char *data, size_t length, + gpr_uint32 *result); + +/* printf to a newly-allocated string. The set of supported formats may vary + between platforms. + + On success, returns the number of bytes printed (excluding the final '\0'), + and *strp points to a string which must later be destroyed with gpr_free(). + + On error, returns -1 and sets *strp to NULL. */ +int gpr_asprintf(char **strp, const char *format, ...); + +#ifdef __cplusplus +} +#endif + +#endif /* __GRPC_SUPPORT_STRING_H__ */ diff --git a/include/grpc/support/sync.h b/include/grpc/support/sync.h new file mode 100644 index 0000000000..3e435a6e4c --- /dev/null +++ b/include/grpc/support/sync.h @@ -0,0 +1,348 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_SYNC_H__ +#define __GRPC_SUPPORT_SYNC_H__ +/* Synchronization primitives for GPR. + + The type gpr_mu provides a non-reentrant mutex (lock). + + The type gpr_cv provides a condition variable. + + The type gpr_once provides for one-time initialization. + + The type gpr_event provides one-time-setting, reading, and + waiting of a void*, with memory barriers. + + The type gpr_refcount provides an object reference counter, + with memory barriers suitable to control + object lifetimes. + + The type gpr_stats_counter provides an atomic statistics counter. It + provides no memory barriers. + */ + +/* Platform-specific type declarations of gpr_mu and gpr_cv. */ +#include <grpc/support/port_platform.h> +#include <grpc/support/sync_generic.h> + +#if defined(GPR_POSIX_SYNC) +#include <grpc/support/sync_posix.h> +#elif defined(GPR_WIN32) +#include <grpc/support/sync_win32.h> +#else +#error Unable to determine platform for sync +#endif + +#include <grpc/support/time.h> /* for gpr_timespec */ +#include <grpc/support/cancellable_platform.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/* --- Mutex interface --- + + At most one thread may hold an exclusive lock on a mutex at any given time. + Actions taken by a thread that holds a mutex exclusively happen after + actions taken by all previous holders of the mutex. Variables of type + gpr_mu are uninitialized when first declared. */ + +/* Initialize *mu. Requires: *mu uninitialized. */ +void gpr_mu_init(gpr_mu *mu); + +/* Cause *mu no longer to be initialized, freeing any memory in use. Requires: + *mu initialized; no other concurrent operation on *mu. */ +void gpr_mu_destroy(gpr_mu *mu); + +/* Wait until no thread has a lock on *mu, cause the calling thread to own an + exclusive lock on *mu, then return. May block indefinitely or crash if the + calling thread has a lock on *mu. Requires: *mu initialized. */ +void gpr_mu_lock(gpr_mu *mu); + +/* Release an exclusive lock on *mu held by the calling thread. Requires: *mu + initialized; the calling thread holds an exclusive lock on *mu. */ +void gpr_mu_unlock(gpr_mu *mu); + +/* Without blocking, attempt to acquire an exclusive lock on *mu for the + calling thread, then return non-zero iff success. Fail, if any thread holds + the lock; succeeds with high probability if no thread holds the lock. + Requires: *mu initialized. */ +int gpr_mu_trylock(gpr_mu *mu); + +/* --- Condition variable interface --- + + A while-loop should be used with gpr_cv_wait() when waiting for conditions + to become true. See the example below. Variables of type gpr_cv are + uninitialized when first declared. */ + +/* Initialize *cv. Requires: *cv uninitialized. */ +void gpr_cv_init(gpr_cv *cv); + +/* Cause *cv no longer to be initialized, freeing any memory in use. Requires: + *cv initialized; no other concurrent operation on *cv.*/ +void gpr_cv_destroy(gpr_cv *cv); + +/* Atomically release *mu and wait on *cv. When the calling thread is woken + from *cv or the deadline abs_deadline is exceeded, execute gpr_mu_lock(mu) + and return whether the deadline was exceeded. Use + abs_deadline==gpr_inf_future for no deadline. May return even when not + woken explicitly. Requires: *mu and *cv initialized; the calling thread + holds an exclusive lock on *mu. */ +int gpr_cv_wait(gpr_cv *cv, gpr_mu *mu, gpr_timespec abs_deadline); + +/* Behave like gpr_cv_wait(cv, mu, abs_deadline), except behave as though + the deadline has expired if *c is cancelled. */ +int gpr_cv_cancellable_wait(gpr_cv *cv, gpr_mu *mu, gpr_timespec abs_deadline, + gpr_cancellable *c); + +/* If any threads are waiting on *cv, wake at least one. + Clients may treat this as an optimization of gpr_cv_broadcast() + for use in the case where waking more than one waiter is not useful. + Requires: *cv initialized. */ +void gpr_cv_signal(gpr_cv *cv); + +/* Wake all threads waiting on *cv. Requires: *cv initialized. */ +void gpr_cv_broadcast(gpr_cv *cv); + +/* --- Cancellation --- + A gpr_cancellable can be used with gpr_cv_cancellable_wait() + or gpr_event_cancellable_wait() cancel pending waits. */ + +/* Initialize *c. */ +void gpr_cancellable_init(gpr_cancellable *c); + +/* Cause *c no longer to be initialized, freeing any memory in use. Requires: + *c initialized; no other concurrent operation on *c. */ +void gpr_cancellable_destroy(gpr_cancellable *c); + +/* Return non-zero iff *c has been cancelled. Requires *c initialized. + This call is faster than acquiring a mutex on most platforms. */ +int gpr_cancellable_is_cancelled(gpr_cancellable *c); + +/* Cancel *c. If *c was not previously cancelled, cause + gpr_cancellable_init() to return non-zero, and outstanding and future + calls to gpr_cv_cancellable_wait() and gpr_event_cancellable_wait() to + return immediately indicating a timeout has occurred; otherwise do nothing. + Requires *c initialized.*/ +void gpr_cancellable_cancel(gpr_cancellable *c); + +/* --- One-time initialization --- + + gpr_once must be declared with static storage class, and initialized with + GPR_ONCE_INIT. e.g., + static gpr_once once_var = GPR_ONCE_INIT; */ + +/* Ensure that (*init_routine)() has been called exactly once (for the + specified gpr_once instance) and then return. + If multiple threads call gpr_once() on the same gpr_once instance, one of + them will call (*init_routine)(), and the others will block until that call + finishes.*/ +void gpr_once_init(gpr_once *once, void (*init_routine)(void)); + +/* --- One-time event notification --- + + These operations act on a gpr_event, which should be initialized with + gpr_ev_init(), or with GPR_EVENT_INIT if static, e.g., + static gpr_event event_var = GPR_EVENT_INIT; + It requires no destruction. */ + +/* Initialize *ev. */ +void gpr_event_init(gpr_event *ev); + +/* Set *ev so that gpr_event_get() and gpr_event_wait() will return value. + Requires: *ev initialized; value != NULL; no prior or concurrent calls to + gpr_event_set(ev, ...) since initialization. */ +void gpr_event_set(gpr_event *ev, void *value); + +/* Return the value set by gpr_event_set(ev, ...), or NULL if no such call has + completed. If the result is non-NULL, all operations that occurred prior to + the gpr_event_set(ev, ...) set will be visible after this call returns. + Requires: *ev initialized. This operation is faster than acquiring a mutex + on most platforms. */ +void *gpr_event_get(gpr_event *ev); + +/* Wait until *ev is set by gpr_event_set(ev, ...), or abs_deadline is + exceeded, then return gpr_event_get(ev). Requires: *ev initialized. Use + abs_deadline==gpr_inf_future for no deadline. When the event has been + signalled before the call, this operation is faster than acquiring a mutex + on most platforms. */ +void *gpr_event_wait(gpr_event *ev, gpr_timespec abs_deadline); + +/* Behave like gpr_event_wait(ev, abs_deadline), except behave as though + the deadline has expired if *c is cancelled. */ +void *gpr_event_cancellable_wait(gpr_event *ev, gpr_timespec abs_deadline, + gpr_cancellable *c); + +/* --- Reference counting --- + + These calls act on the type gpr_refcount. It requires no desctruction. */ + +/* Initialize *r to value n. */ +void gpr_ref_init(gpr_refcount *r, int n); + +/* Increment the reference count *r. Requires *r initialized. */ +void gpr_ref(gpr_refcount *r); + +/* Increment the reference count *r by n. Requires *r initialized, n > 0. */ +void gpr_refn(gpr_refcount *r, int n); + +/* Decrement the reference count *r and return non-zero iff it has reached + zero. . Requires *r initialized. */ +int gpr_unref(gpr_refcount *r); + +/* --- Stats counters --- + + These calls act on the integral type gpr_stats_counter. It requires no + destruction. Static instances may be initialized with + gpr_stats_counter c = GPR_STATS_INIT; + Beware: These operations do not imply memory barriers. Do not use them to + synchronize other events. */ + +/* Initialize *c to the value n. */ +void gpr_stats_init(gpr_stats_counter *c, gpr_intptr n); + +/* *c += inc. Requires: *c initialized. */ +void gpr_stats_inc(gpr_stats_counter *c, gpr_intptr inc); + +/* Return *c. Requires: *c initialized. */ +gpr_intptr gpr_stats_read(const gpr_stats_counter *c); + +/* ==================Example use of interface=================== + A producer-consumer queue of up to N integers, + illustrating the use of the calls in this interface. */ +#if 0 + +#define N 4 + + typedef struct queue { + gpr_cv non_empty; /* Signalled when length becomes non-zero. */ + gpr_cv non_full; /* Signalled when length becomes non-N. */ + gpr_mu mu; /* Protects all fields below. + (That is, except during initialization or + destruction, the fields below should be accessed + only by a thread that holds mu.) */ + int head; /* Index of head of queue 0..N-1. */ + int length; /* Number of valid elements in queue 0..N. */ + int elem[N]; /* elem[head .. head+length-1] are queue elements. */ + } queue; + + /* Initialize *q. */ + void queue_init(queue *q) { + gpr_mu_init(&q->mu); + gpr_cv_init(&q->non_empty); + gpr_cv_init(&q->non_full); + q->head = 0; + q->length = 0; + } + + /* Free storage associated with *q. */ + void queue_destroy(queue *q) { + gpr_mu_destroy(&q->mu); + gpr_cv_destroy(&q->non_empty); + gpr_cv_destroy(&q->non_full); + } + + /* Wait until there is room in *q, then append x to *q. */ + void queue_append(queue *q, int x) { + gpr_mu_lock(&q->mu); + /* To wait for a predicate without a deadline, loop on the negation of the + predicate, and use gpr_cv_wait(..., gpr_inf_future) inside the loop + to release the lock, wait, and reacquire on each iteration. Code that + makes the condition true should use gpr_cv_broadcast() on the + corresponding condition variable. The predicate must be on state + protected by the lock. */ + while (q->length == N) { + gpr_cv_wait(&q->non_full, &q->mu, gpr_inf_future); + } + if (q->length == 0) { /* Wake threads blocked in queue_remove(). */ + /* It's normal to use gpr_cv_broadcast() or gpr_signal() while + holding the lock. */ + gpr_cv_broadcast(&q->non_empty); + } + q->elem[(q->head + q->length) % N] = x; + q->length++; + gpr_mu_unlock(&q->mu); + } + + /* If it can be done without blocking, append x to *q and return non-zero. + Otherwise return 0. */ + int queue_try_append(queue *q, int x) { + int result = 0; + if (gpr_mu_trylock(&q->mu)) { + if (q->length != N) { + if (q->length == 0) { /* Wake threads blocked in queue_remove(). */ + gpr_cv_broadcast(&q->non_empty); + } + q->elem[(q->head + q->length) % N] = x; + q->length++; + result = 1; + } + gpr_mu_unlock(&q->mu); + } + return result; + } + + /* Wait until the *q is non-empty or deadline abs_deadline passes. If the + queue is non-empty, remove its head entry, place it in *head, and return + non-zero. Otherwise return 0. */ + int queue_remove(queue *q, int *head, gpr_timespec abs_deadline) { + int result = 0; + gpr_mu_lock(&q->mu); + /* To wait for a predicate with a deadline, loop on the negation of the + predicate or until gpr_cv_wait() returns true. Code that makes + the condition true should use gpr_cv_broadcast() on the corresponding + condition variable. The predicate must be on state protected by the + lock. */ + while (q->length == 0 && + !gpr_cv_wait(&q->non_empty, &q->mu, abs_deadline)) { + } + if (q->length != 0) { /* Queue is non-empty. */ + result = 1; + if (q->length == N) { /* Wake threads blocked in queue_append(). */ + gpr_cv_broadcast(&q->non_full); + } + *head = q->elem[q->head]; + q->head = (q->head + 1) % N; + q->length--; + } /* else deadline exceeded */ + gpr_mu_unlock(&q->mu); + return result; + } +#endif /* 0 */ + +#ifdef __cplusplus +} +#endif + +#endif /* __GRPC_SUPPORT_SYNC_H__ */ diff --git a/include/grpc/support/sync_generic.h b/include/grpc/support/sync_generic.h new file mode 100644 index 0000000000..0c8a992439 --- /dev/null +++ b/include/grpc/support/sync_generic.h @@ -0,0 +1,55 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_SYNC_GENERIC_H__ +#define __GRPC_SUPPORT_SYNC_GENERIC_H__ +/* Generic type defintions for gpr_sync. */ + +#include <grpc/support/atm.h> + +/* gpr_event */ +typedef struct { gpr_atm state; } gpr_event; + +#define GPR_EVENT_INIT \ + { 0 } + +/* gpr_refcount */ +typedef struct { gpr_atm count; } gpr_refcount; + +/* gpr_stats_counter */ +typedef struct { gpr_atm value; } gpr_stats_counter; + +#define GPR_STATS_INIT \ + { 0 } + +#endif /* __GRPC_SUPPORT_SYNC_GENERIC_H__ */ diff --git a/include/grpc/support/sync_posix.h b/include/grpc/support/sync_posix.h new file mode 100644 index 0000000000..6787695cfb --- /dev/null +++ b/include/grpc/support/sync_posix.h @@ -0,0 +1,48 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_SYNC_POSIX_H__ +#define __GRPC_SUPPORT_SYNC_POSIX_H__ + +#include <grpc/support/sync_generic.h> + +/* Posix variant of gpr_sync_platform.h */ +#include <pthread.h> + +typedef pthread_mutex_t gpr_mu; +typedef pthread_cond_t gpr_cv; +typedef pthread_once_t gpr_once; + +#define GPR_ONCE_INIT PTHREAD_ONCE_INIT + +#endif /* __GRPC_SUPPORT_SYNC_POSIX_H__ */ diff --git a/include/grpc/support/sync_win32.h b/include/grpc/support/sync_win32.h new file mode 100644 index 0000000000..b3230dcc0d --- /dev/null +++ b/include/grpc/support/sync_win32.h @@ -0,0 +1,52 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_SYNC_WIN32_H__ +#define __GRPC_SUPPORT_SYNC_WIN32_H__ + +#include <grpc/support/sync_generic.h> + +/* Win32 variant of gpr_sync_platform.h */ +#include <windows.h> + +typedef struct { + CRITICAL_SECTION cs; /* Not an SRWLock until Vista is unsupported */ + int locked; +} gpr_mu; + +typedef CONDITION_VARIABLE gpr_cv; + +typedef INIT_ONCE gpr_once; +#define GPR_ONCE_INIT INIT_ONCE_STATIC_INIT + +#endif /* __GRPC_SUPPORT_SYNC_WIN32_H__ */ diff --git a/include/grpc/support/thd.h b/include/grpc/support/thd.h new file mode 100644 index 0000000000..18a1e80d06 --- /dev/null +++ b/include/grpc/support/thd.h @@ -0,0 +1,79 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_THD_H__ +#define __GRPC_SUPPORT_THD_H__ +/* Thread interface for GPR. + + Types + gpr_thd_id a thread identifier. + (Currently no calls take a thread identifier. + It exists for future extensibility.) + gpr_thd_options options used when creating a thread + */ + +#include <grpc/support/port_platform.h> + +#if defined(GPR_POSIX_SYNC) +#include <grpc/support/thd_posix.h> +#elif defined(GPR_WIN32) +#include <grpc/support/thd_win32.h> +#else +#error could not determine platform for thd +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* Thread creation options. */ +typedef struct { + int flags; /* Flags below can be set here. Default value 0. */ +} gpr_thd_options; +/* No flags are currently defined. */ + +/* Create a new thread running (*thd_body)(arg) and place its thread identifier + in *t, and return true. If there are insufficient resources, return false. + If options==NULL, default options are used. + The thread is immediately runnable, and exits when (*thd_body)() returns. */ +int gpr_thd_new(gpr_thd_id *t, void (*thd_body)(void *arg), void *arg, + const gpr_thd_options *options); + +/* Return a gpr_thd_options struct with all fields set to defaults. */ +gpr_thd_options gpr_thd_options_default(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __GRPC_SUPPORT_THD_H__ */ diff --git a/include/grpc/support/thd_posix.h b/include/grpc/support/thd_posix.h new file mode 100644 index 0000000000..3cfa512402 --- /dev/null +++ b/include/grpc/support/thd_posix.h @@ -0,0 +1,42 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_THD_POSIX_H__ +#define __GRPC_SUPPORT_THD_POSIX_H__ +/* Posix variant of gpr_thd_platform.h. */ + +#include <pthread.h> + +typedef pthread_t gpr_thd_id; + +#endif /* __GRPC_SUPPORT_THD_POSIX_H__ */ diff --git a/include/grpc/support/thd_win32.h b/include/grpc/support/thd_win32.h new file mode 100644 index 0000000000..6fa576e4a4 --- /dev/null +++ b/include/grpc/support/thd_win32.h @@ -0,0 +1,44 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_THD_WIN32_H__ +#define __GRPC_SUPPORT_THD_WIN32_H__ + +/* Win32 variant of gpr_thd_platform.h */ + +#include <windows.h> +#include <grpc/support/atm.h> + +typedef int gpr_thd_id; + +#endif /* __GRPC_SUPPORT_THD_WIN32_H__ */ diff --git a/include/grpc/support/time.h b/include/grpc/support/time.h new file mode 100644 index 0000000000..6f07de0054 --- /dev/null +++ b/include/grpc/support/time.h @@ -0,0 +1,109 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_TIME_H__ +#define __GRPC_SUPPORT_TIME_H__ +/* Time support. + We use gpr_timespec, which is typedefed to struct timespec on platforms which + have it. On some machines, absolute times may be in local time. */ + +/* Platform specific header declares gpr_timespec. + gpr_timespec contains: + time_t tv_sec; // seconds since start of 1970 + int tv_nsec; // nanoseconds; always in 0..999999999; never negative. + */ + +#include <grpc/support/port_platform.h> + +#if defined(GPR_POSIX_TIME) +#include <grpc/support/time_posix.h> +#elif defined(GPR_WIN32) +#include <grpc/support/time_win32.h> +#else +#error could not determine platform for time +#endif + +#include <stddef.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/* Time constants. */ +extern const gpr_timespec gpr_time_0; /* The zero time interval. */ +extern const gpr_timespec gpr_inf_future; /* The far future */ +extern const gpr_timespec gpr_inf_past; /* The far past. */ + +#define GPR_MS_PER_SEC 1000 +#define GPR_US_PER_SEC 1000000 +#define GPR_NS_PER_SEC 1000000000 +#define GPR_NS_PER_MS 1000000 +#define GPR_NS_PER_US 1000 +#define GPR_US_PER_MS 1000 + +/* Return the current time measured from the system's default epoch. */ +gpr_timespec gpr_now(void); + +/* Return -ve, 0, or +ve according to whether a < b, a == b, or a > b + respectively. */ +int gpr_time_cmp(gpr_timespec a, gpr_timespec b); + +/* Add and subtract times. Calculations saturate at infinities. */ +gpr_timespec gpr_time_add(gpr_timespec a, gpr_timespec b); +gpr_timespec gpr_time_sub(gpr_timespec a, gpr_timespec b); + +/* Return a timespec representing a given number of microseconds. LONG_MIN is + interpreted as gpr_inf_past, and LONG_MAX as gpr_inf_future. */ +gpr_timespec gpr_time_from_micros(long x); +gpr_timespec gpr_time_from_nanos(long x); +gpr_timespec gpr_time_from_millis(long x); +gpr_timespec gpr_time_from_seconds(long x); +gpr_timespec gpr_time_from_minutes(long x); +gpr_timespec gpr_time_from_hours(long x); + +/* Return 1 if two times are equal or within threshold of each other, + 0 otherwise */ +int gpr_time_similar(gpr_timespec a, gpr_timespec b, gpr_timespec threshold); + +/* Sleep until at least 'until' - an absolute timeout */ +void gpr_sleep_until(gpr_timespec until); + +struct timeval gpr_timeval_from_timespec(gpr_timespec t); + +gpr_timespec gpr_timespec_from_timeval(struct timeval t); + +#ifdef __cplusplus +} +#endif + +#endif /* __GRPC_SUPPORT_TIME_H__ */ diff --git a/include/grpc/support/time_posix.h b/include/grpc/support/time_posix.h new file mode 100644 index 0000000000..72ebf5f3fd --- /dev/null +++ b/include/grpc/support/time_posix.h @@ -0,0 +1,43 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_TIME_POSIX_H__ +#define __GRPC_SUPPORT_TIME_POSIX_H__ +/* Posix variant of gpr_time_platform.h */ + +#include <sys/time.h> +#include <time.h> + +typedef struct timespec gpr_timespec; + +#endif /* __GRPC_SUPPORT_TIME_POSIX_H__ */ diff --git a/include/grpc/support/time_win32.h b/include/grpc/support/time_win32.h new file mode 100644 index 0000000000..2450550bd6 --- /dev/null +++ b/include/grpc/support/time_win32.h @@ -0,0 +1,46 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_TIME_WIN32_H__ +#define __GRPC_SUPPORT_TIME_WIN32_H__ +/* Win32 variant of gpr_time_platform.h */ + +#include <Winsock.h> +#include <time.h> + +typedef struct gpr_timespec { + time_t tv_sec; + long tv_nsec; +} gpr_timespec; + +#endif /* __GRPC_SUPPORT_TIME_WIN32_H__ */ diff --git a/include/grpc/support/useful.h b/include/grpc/support/useful.h new file mode 100644 index 0000000000..2f92b633fc --- /dev/null +++ b/include/grpc/support/useful.h @@ -0,0 +1,45 @@ +/* + * + * Copyright 2014, Google Inc. + * All rights reserved. + * + * 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * 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 COPYRIGHT + * OWNER 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 __GRPC_SUPPORT_USEFUL_H__ +#define __GRPC_SUPPORT_USEFUL_H__ + +/* useful macros that don't belong anywhere else */ + +#define GPR_MIN(a, b) ((a) < (b) ? (a) : (b)) +#define GPR_MAX(a, b) ((a) > (b) ? (a) : (b)) +#define GPR_CLAMP(a, min, max) ((a) < (min) ? (min) : (a) > (max) ? (max) : (a)) + +#define GPR_ARRAY_SIZE(array) (sizeof(array) / sizeof(*(array))) + +#endif /* __GRPC_SUPPORT_USEFUL_H__ */ |