The API defined here is proposed, experimental, and (for now) subject to change at any time.
**Do not use it.**
If you think you want to use it, or for any other queries, contact <rkt-dev@googlegroups.com> or file an [issue](https://github.com/coreos/rkt/issues/new)
// ****************** END WARNING ******************** //
syntax="proto3";
packagev1alpha;
// ImageType defines the supported image type.
enumImageType{
IMAGE_TYPE_UNDEFINED=0;
IMAGE_TYPE_APPC=1;
IMAGE_TYPE_DOCKER=2;
IMAGE_TYPE_OCI=3;
}
// ImageFormat defines the format of the image.
messageImageFormat{
// Type of the image, required.
ImageTypetype=1;
// Version of the image format, required.
stringversion=2;
}
// Image describes the image's information.
messageImage{
// Base format of the image, required. This indicates the original format
// for the image as nowadays all the image formats will be transformed to
// ACI.
ImageFormatbase_format=1;
// ID of the image, a string that can be used to uniquely identify the image,
// e.g. sha512 hash of the ACIs, required.
stringid=2;
// Name of the image in the image manifest, e.g. 'coreos.com/etcd', optional.
stringname=3;
// Version of the image, e.g. 'latest', '2.0.10', optional.
stringversion=4;
// Timestamp of when the image is imported, it is the seconds since epoch, optional.
int64import_timestamp=5;
// JSON-encoded byte array that represents the image manifest, optional.
bytesmanifest=6;
}
// Network describes the network information of a pod.
messageNetwork{
// Name of the network that a pod belongs to, required.
stringname=1;
// Pod's IPv4 address within the network, optional if IPv6 address is given.
stringipv4=2;
// Pod's IPv6 address within the network, optional if IPv4 address is given.
stringipv6=3;
}
// AppState defines the possible states of the app.
enumAppState{
APP_STATE_UNDEFINED=0;
APP_STATE_RUNNING=1;
APP_STATE_EXITED=2;
}
// App describes the information of an app that's running in a pod.
messageApp{
// Name of the app, required.
stringname=1;
// Image used by the app, required. However, this may only contain the image id
// if it is returned by ListPods().
Imageimage=2;
// State of the app. optional, non-empty only if it's returned by InspectPod().
AppStatestate=3;
// Exit code of the app. optional, only valid if it's returned by InspectPod() and
// the app has already exited.
sint32exit_code=4;
}
// PodState defines the possible states of the pod.
// See https://github.com/coreos/rkt/blob/master/Documentation/devel/pod-lifecycle.md for a detailed
// explanation of each state.
enumPodState{
POD_STATE_UNDEFINED=0;
// States before the pod is running.
POD_STATE_EMBRYO=1;// Pod is created, ready to entering 'preparing' state.
POD_STATE_PREPARING=2;// Pod is being prepared. On success it will become 'prepared', otherwise it will become 'aborted prepared'.
POD_STATE_PREPARED=3;// Pod has been successfully prepared, ready to enter 'running' state. it can also enter 'deleting' if it's garbage collected before running.
// State that indicates the pod is running.
POD_STATE_RUNNING=4;// Pod is running, when it exits, it will become 'exited'.
// States that indicates the pod is exited, and will never run.
POD_STATE_ABORTED_PREPARE=5;// Pod failed to prepare, it will only be garbage collected and will never run again.
POD_STATE_EXITED=6;// Pod has exited, it now can be garbage collected.
POD_STATE_DELETING=7;// Pod is being garbage collected, after that it will enter 'garbage' state.
POD_STATE_GARBAGE=8;// Pod is marked as garbage collected, it no longer exists on the machine.
}
// Pod describes a pod's information.
messagePod{
// ID of the pod, in the form of a UUID, required.
stringid=1;
// PID of the pod, optional, only valid if it's returned by InspectPod(). A negative value means the pod has exited.
sint32pid=2;
// State of the pod, required.
PodStatestate=3;
// List of apps in the pod, required.
repeatedAppapps=4;
// Network information of the pod, optional, non-empty if the pod is running in private net.
// Note that a pod can be in multiple networks.
repeatedNetworknetworks=5;
// JSON-encoded byte array that represents the pod manifest of the pod, required.
bytesmanifest=6;
}
messageKeyValue{
// Key part of the key-value pair.
stringKey=1;
// Value part of the key-value pair.
stringvalue=2;
}
// PodFilter defines the condition that the returned pods need to satisfy in ListPods().
// The conditions are combined by 'AND'.
messagePodFilter{
// If not empty, the pods that have any of the ids will be returned.
repeatedstringids=1;
// If not empty, the pods that have any of the states will be returned.
repeatedPodStatestates=2;
// If not empty, the pods that have any of the apps will be returned.
repeatedstringapp_names=3;
// If not empty, the pods that have any of the images(in the apps) will be returned
repeatedstringimage_ids=4;
// If not empty, the pods that are in any of the networks will be returned.
repeatedstringnetwork_names=5;
// If not empty, the pods that have any of the annotations will be returned.
repeatedKeyValueannotations=6;
}
// ImageFilter defines the condition that the returned images need to satisfy in ListImages().
// The conditions are combined by 'AND'.
messageImageFilter{
// If not empty, the images that have any of the ids will be returned.
repeatedstringids=1;
// if not empty, the images that have any of the prefixes in the name will be returned.
repeatedstringprefixes=2;
// If not empty, the images that have any of the base names will be returned.
// For example, both 'coreos.com/etcd' and 'k8s.io/etcd' will be returned if 'etcd' is included,
// however 'k8s.io/etcd-backup' will not be returned.
repeatedstringbase_names=3;
// If not empty, the images that have any of the keywords in the name will be returned.
// For example, both 'kubernetes-etcd', 'etcd:latest' will be returned if 'etcd' is included,
repeatedstringkeywords=4;
// If not empty, the images that have any of the labels will be returned.
repeatedKeyValuelabels=5;
// If set, the images that are imported after this timestamp will be returned.
int64imported_after=6;
// If set, the images that are imported before this timestamp will be returned.
int64imported_before=7;
// If not empty, the images that have any of the annotations will be returned.
repeatedKeyValueannotations=8;
}
// Info describes the information of rkt on the machine.
messageInfo{
// Version of rkt, required, in the form of Semantic Versioning 2.0.0 (http://semver.org/).
stringrkt_version=1;
// Version of appc, required, in the form of Semantic Versioning 2.0.0 (http://semver.org/).
stringappc_version=2;
// Latest version of the api that's supported by the service, required, in the form of Semantic Versioning 2.0.0 (http://semver.org/).
stringapi_version=3;
}
// EventType defines the type of the events that will be received via ListenEvents().
enumEventType{
EVENT_TYPE_UNDEFINED=0;
// Pod events.
EVENT_TYPE_POD_PREPARED=1;
EVENT_TYPE_POD_PREPARE_ABORTED=2;
EVENT_TYPE_POD_STARTED=3;
EVENT_TYPE_POD_EXITED=4;
EVENT_TYPE_POD_GARBAGE_COLLECTED=5;
// App events.
EVENT_TYPE_APP_STARTED=6;
EVENT_TYPE_APP_EXITED=7;// (XXX)yifan: Maybe also return exit code in the event object?
// Image events.
EVENT_TYPE_IMAGE_IMPORTED=8;
EVENT_TYPE_IMAGE_REMOVED=9;
}
// Event describes the events that will be received via ListenEvents().
messageEvent{
// Type of the event, required.
EventTypetype=1;
// ID of the subject that causes the event, required.
// If the event is a pod or app event, the id is the pod's uuid.
// If the event is an image event, the id is the image's id.
stringid=2;
// Name of the subject that causes the event, required.
// If the event is a pod event, the name is the pod's name.
// If the event is an app event, the name is the app's name.
// If the event is an image event, the name is the image's name.
stringfrom=3;
// Timestamp of when the event happens, it is the seconds since epoch, required.
int64time=4;
// Data of the event, in the form of key-value pairs, optional.
repeatedKeyValuedata=5;
}
// EventFilter defines the condition that the returned events needs to satisfy in ListImages().
// The condition are combined by 'AND'.
messageEventFilter{
// If not empty, then only returns the events that have the listed types.
repeatedEventTypetypes=1;
// If not empty, then only returns the events whose 'id' is included in the listed ids.
repeatedstringids=2;
// If not empty, then only returns the events whose 'from' is included in the listed names.
repeatedstringnames=3;
// If set, then only returns the events after this timestamp.
// If the server starts after since_time, then only the events happened after the start of the server will be returned.
// If since_time is a future timestamp, then no events will be returned until that time.
int64since_time=4;
// If set, then only returns the events before this timestamp.
// If it is a future timestamp, then the event stream will be closed at that moment.
int64until_time=5;
}
// Request for GetInfo().
messageGetInfoRequest{}
// Response for GetInfo().
messageGetInfoResponse{
Infoinfo=1;// Required.
}
// Request for ListPods().
messageListPodsRequest{
PodFilterfilter=1;// Optional.
}
// Response for ListPods().
messageListPodsResponse{
repeatedPodpods=1;// Required.
}
// Request for InspectPod().
messageInspectPodRequest{
// ID of the pod which we are querying status for, required.
stringid=1;
}
// Response for InspectPod().
messageInspectPodResponse{
Podpod=1;// Required.
}
// Request for ListImages().
messageListImagesRequest{
ImageFilterfilter=1;// Optional.
}
// Response for ListImages().
messageListImagesResponse{
repeatedImageimages=1;// Required.
}
// Request for InspectImage().
messageInspectImageRequest{
stringid=1;// Required.
}
// Response for InspectImage().
messageInspectImageResponse{
Imageimage=1;// Required.
}
// Request for ListenEvents().
messageListenEventsRequest{
EventFilterfilter=1;// Optional.
}
// Response for ListenEvents().
messageListenEventsResponse{
// Aggregate multiple events to reduce round trips, optional as the response can contain no events.
repeatedEventevents=1;
}
// Request for GetLogs().
messageGetLogsRequest{
// ID of the pod which we will get logs from, required.
stringpod_id=1;
// Name of the app within the pod which we will get logs
// from, optional. If not set, then the logs of all the
// apps within the pod will be returned.
stringapp_name=2;
// Number of most recent lines to return, optional.
int32lines=3;
// If true, then a response stream will not be closed,
// and new log response will be sent via the stream, default is false.
boolfollow=4;
// If set, then only the logs after the timestamp will
// be returned, optional.
int64since_time=5;
// If set, then only the logs before the timestamp will
// be returned, optional.
int64until_time=6;
}
// Response for GetLogs().
messageGetLogsResponse{
// List of the log lines that returned, optional as the response can contain no logs.
repeatedstringlines=1;
}
// PublicAPI defines the read-only APIs that will be supported.
// These will be handled over TCP sockets.
servicePublicAPI{
// GetInfo gets the rkt's information on the machine.
This tutorial provides a basic Go programmer's introduction to working with gRPC. By walking through this example you'll learn how to:
- Define a service in a .proto file.
- Generate server and client code using the protocol buffer compiler.
- Use the Go gRPC API to write a simple client and server for your service.
It assumes that you have read the [Getting started](https://github.com/grpc/grpc/tree/master/examples) guide and are familiar with [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). Note that the example in this tutorial uses the proto3 version of the protocol buffers language, which is currently in alpha release:you can find out more in the [proto3 language guide](https://developers.google.com/protocol-buffers/docs/proto3) and see the [release notes](https://github.com/google/protobuf/releases) for the new version in the protocol buffers Github repository.
This isn't a comprehensive guide to using gRPC in Go: more reference documentation is coming soon.
## Why use gRPC?
Our example is a simple route mapping application that lets clients get information about features on their route, create a summary of their route, and exchange route information such as traffic updates with the server and other clients.
With gRPC we can define our service once in a .proto file and implement clients and servers in any of gRPC's supported languages, which in turn can be run in environments ranging from servers inside Google to your own tablet - all the complexity of communication between different languages and environments is handled for you by gRPC. We also get all the advantages of working with protocol buffers, including efficient serialization, a simple IDL, and easy interface updating.
## Example code and setup
The example code for our tutorial is in [grpc/grpc-go/examples/route_guide](https://github.com/grpc/grpc-go/tree/master/examples/route_guide). To download the example, clone the `grpc-go` repository by running the following command:
```shell
$ go get google.golang.org/grpc
```
Then change your current directory to `grpc-go/examples/route_guide`:
You also should have the relevant tools installed to generate the server and client interface code - if you don't already, follow the setup instructions in [the Go quick start guide](examples/).
## Defining the service
Our first step (as you'll know from [Getting started](https://github.com/grpc/grpc/tree/master/examples)) is to define the gRPC *service* and the method *request* and *response* types using [protocol buffers](https://developers.google.com/protocol-buffers/docs/overview). You can see the complete .proto file in [`examples/route_guide/proto/route_guide.proto`](examples/route_guide/proto/route_guide.proto).
To define a service, you specify a named `service` in your .proto file:
```proto
serviceRouteGuide{
...
}
```
Then you define `rpc` methods inside your service definition, specifying their request and response types. gRPC lets you define four kinds of service method, all of which are used in the `RouteGuide` service:
- A *simple RPC* where the client sends a request to the server using the stub and waits for a response to come back, just like a normal function call.
```proto
// Obtains the feature at a given position.
rpcGetFeature(Point)returns(Feature){}
```
- A *server-side streaming RPC* where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. As you can see in our example, you specify a server-side streaming method by placing the `stream` keyword before the *response* type.
```proto
// Obtains the Features available within the given Rectangle. Results are
// streamed rather than returned at once (e.g. in a response message with a
// repeated field), as the rectangle may cover a large area and contain a
- A *client-side streaming RPC* where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them all and return its response. You specify a client-side streaming method by placing the `stream` keyword before the *request* type.
```proto
// Accepts a stream of Points on a route being traversed, returning a
- A *bidirectional streaming RPC* where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved. You specify this type of method by placing the `stream` keyword before both the request and the response.
```proto
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
Our .proto file also contains protocol buffer message type definitions for all the request and response types used in our service methods - for example, here's the `Point` message type:
```proto
// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
messagePoint{
int32latitude=1;
int32longitude=2;
}
```
## Generating client and server code
Next we need to generate the gRPC client and server interfaces from our .proto service definition. We do this using the protocol buffer compiler `protoc` with a special gRPC Go plugin.
For simplicity, we've provided a [bash script](https://github.com/grpc/grpc-go/blob/master/codegen.sh) that runs `protoc` for you with the appropriate plugin, input, and output (if you want to run this by yourself, make sure you've installed protoc and followed the gRPC-Go [installation instructions](https://github.com/grpc/grpc-go/blob/master/README.md) first):
Running this command generates the following file in your current directory:
-`route_guide.pb.go`
This contains:
- All the protocol buffer code to populate, serialize, and retrieve our request and response message types
- An interface type (or *stub*) for clients to call with the methods defined in the `RouteGuide` service.
- An interface type for servers to implement, also with the methods defined in the `RouteGuide` service.
<aname="server"></a>
## Creating the server
First let's look at how we create a `RouteGuide` server. If you're only interested in creating gRPC clients, you can skip this section and go straight to [Creating the client](#client)(though you might find it interesting anyway!).
There are two parts to making our `RouteGuide` service do its job:
- Implementing the service interface generated from our service definition: doing the actual "work" of our service.
- Running a gRPC server to listen for requests from clients and dispatch them to the right service implementation.
You can find our example `RouteGuide` server in [grpc-go/examples/route_guide/server/server.go](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/server/server.go). Let's take a closer look at how it works.
### Implementing RouteGuide
As you can see, our server has a `routeGuideServer` struct type that implements the generated `RouteGuideServer` interface:
`routeGuideServer` implements all our service methods. Let's look at the simplest type first, `GetFeature`, which just gets a `Point` from the client and returns the corresponding feature information from its database in a `Feature`.
// No feature was found, return an unnamed feature
return&pb.Feature{"",point},nil
}
```
The method is passed a context object for the RPC and the client's `Point` protocol buffer request. It returns a `Feature` protocol buffer object with the response information and an `error`. In the method we populate the `Feature` with the appropriate information, and then `return` it along with an `nil` error to tell gRPC that we've finished dealing with the RPC and that the `Feature` can be returned to the client.
#### Server-side streaming RPC
Now let's look at one of our streaming RPCs. `ListFeatures` is a server-side streaming RPC, so we need to send back multiple `Feature`s to our client.
As you can see, instead of getting simple request and response objects in our method parameters, this time we get a request object (the `Rectangle` in which our client wants to find `Feature`s) and a special `RouteGuide_ListFeaturesServer` object to write our responses.
In the method, we populate as many `Feature` objects as we need to return, writing them to the `RouteGuide_ListFeaturesServer` using its `Send()` method. Finally, as in our simple RPC, we return a `nil` error to tell gRPC that we've finished writing responses. Should any error happen in this call, we return a non-`nil` error; the gRPC layer will translate it into an appropriate RPC status to be sent on the wire.
#### Client-side streaming RPC
Now let's look at something a little more complicated: the client-side streaming method `RecordRoute`, where we get a stream of `Point`s from the client and return a single `RouteSummary` with information about their trip. As you can see, this time the method doesn't have a request parameter at all. Instead, it gets a `RouteGuide_RecordRouteServer` stream, which the server can use to both read *and* write messages - it can receive client messages using its `Recv()` method and return its single response using its `SendAndClose()` method.
In the method body we use the `RouteGuide_RecordRouteServer`s `Recv()` method to repeatedly read in our client's requests to a request object (in this case a `Point`) until there are no more messages: the server needs to check the the error returned from `Read()` after each call. If this is `nil`, the stream is still good and it can continue reading; if it's `io.EOF` the message stream has ended and the server can return its `RouteSummary`. If it has any other value, we return the error "as is" so that it'll be translated to an RPC status by the gRPC layer.
#### Bidirectional streaming RPC
Finally, let's look at our bidirectional streaming RPC `RouteChat()`.
This time we get a `RouteGuide_RouteChatServer` stream that, as in our client-side streaming example, can be used to read and write messages. However, this time we return values via our method's stream while the client is still writing messages to *their* message stream.
The syntax for reading and writing here is very similar to our client-streaming method, except the server uses the stream's `Send()` method rather than `SendAndClose()` because it's writing multiple responses. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently.
### Starting the server
Once we've implemented all our methods, we also need to start up a gRPC server so that clients can actually use our service. The following snippet shows how we do this for our `RouteGuide` service:
1. Specify the port we want to use to listen for client requests using `lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))`.
2. Create an instance of the gRPC server using `grpc.NewServer()`.
3. Register our service implementation with the gRPC server.
4. Call `Serve()` on the server with our port details to do a blocking wait until the process is killed or `Stop()` is called.
<aname="client"></a>
## Creating the client
In this section, we'll look at creating a Go client for our `RouteGuide` service. You can see our complete example client code in [grpc-go/examples/route_guide/client/client.go](https://github.com/grpc/grpc-go/tree/master/examples/route_guide/client/client.go).
### Creating a stub
To call service methods, we first need to create a gRPC *channel* to communicate with the server. We create this by passing the server address and port number to `grpc.Dial()` as follows:
```go
conn,err:=grpc.Dial(*serverAddr)
iferr!=nil{
...
}
deferconn.Close()
```
You can use `DialOptions` to set the auth credentials (e.g., TLS, GCE credentials, JWT credentials) in `grpc.Dial` if the service you request requires that - however, we don't need to do this for our `RouteGuide` service.
Once the gRPC *channel* is setup, we need a client *stub* to perform RPCs. We get this using the `NewRouteGuideClient` method provided in the `pb` package we generated from our .proto.
```go
client:=pb.NewRouteGuideClient(conn)
```
### Calling service methods
Now let's look at how we call our service methods. Note that in gRPC-Go, RPCs operate in a blocking/synchronous mode, which means that the RPC call waits for the server to respond, and will either return a response or an error.
#### Simple RPC
Calling the simple RPC `GetFeature` is nearly as straightforward as calling a local method.
As you can see, we call the method on the stub we got earlier. In our method parameters we create and populate a request protocol buffer object (in our case `Point`). We also pass a `context.Context` object which lets us change our RPC's behaviour if necessary, such as time-out/cancel an RPC in flight. If the call doesn't return an error, then we can read the response information from the server from the first return value.
```go
log.Println(feature)
```
#### Server-side streaming RPC
Here's where we call the server-side streaming method `ListFeatures`, which returns a stream of geographical `Feature`s. If you've already read [Creating the server](#server) some of this may look very familiar - streaming RPCs are implemented in a similar way on both sides.
```go
rect:=&pb.Rectangle{...}// initialize a pb.Rectangle
As in the simple RPC, we pass the method a context and a request. However, instead of getting a response object back, we get back an instance of `RouteGuide_ListFeaturesClient`. The client can use the `RouteGuide_ListFeaturesClient` stream to read the server's responses.
We use the `RouteGuide_ListFeaturesClient`'s `Recv()` method to repeatedly read in the server's responses to a response protocol buffer object (in this case a `Feature`) until there are no more messages: the client needs to check the error `err` returned from `Recv()` after each call. If `nil`, the stream is still good and it can continue reading; if it's `io.EOF` then the message stream has ended; otherwise there must be an RPC error, which is passed over through `err`.
#### Client-side streaming RPC
The client-side streaming method `RecordRoute` is similar to the server-side method, except that we only pass the method a context and get a `RouteGuide_RecordRouteClient` stream back, which we can use to both write *and* read messages.
The `RouteGuide_RecordRouteClient` has a `Send()` method that we can use to send requests to the server. Once we've finished writing our client's requests to the stream using `Send()`, we need to call `CloseAndRecv()` on the stream to let gRPC know that we've finished writing and are expecting to receive a response. We get our RPC status from the `err` returned from `CloseAndRecv()`. If the status is `nil`, then the first return value from `CloseAndRecv()` will be a valid server response.
#### Bidirectional streaming RPC
Finally, let's look at our bidirectional streaming RPC `RouteChat()`. As in the case of `RecordRoute`, we only pass the method a context object and get back a stream that we can use to both write and read messages. However, this time we return values via our method's stream while the server is still writing messages to *their* message stream.
log.Printf("Got message %s at point(%d, %d)",in.Message,in.Location.Latitude,in.Location.Longitude)
}
}()
for_,note:=rangenotes{
iferr:=stream.Send(note);err!=nil{
log.Fatalf("Failed to send a note: %v",err)
}
}
stream.CloseSend()
<-waitc
```
The syntax for reading and writing here is very similar to our client-side streaming method, except we use the stream's `CloseSend()` method once we've finished our call. Although each side will always get the other's messages in the order they were written, both the client and server can read and write in any order — the streams operate completely independently.
## Try it out!
To compile and run the server, assuming you are in the folder
As outlined <ahref="https://github.com/grpc/grpc-common/blob/master/grpc-auth-support.md">here</a> gRPC supports a number of different mechanisms for asserting identity between an client and server. We'll present some code-samples here demonstrating how to provide TLS support encryption and identity assertions as well as passing OAuth2 tokens to services that support it.
As outlined <ahref="https://github.com/grpc/grpc/blob/master/doc/grpc-auth-support.md">here</a> gRPC supports a number of different mechanisms for asserting identity between an client and server. We'll present some code-samples here demonstrating how to provide TLS support encryption and identity assertions as well as passing OAuth2 tokens to services that support it.
// Resolver dose name resolution and watches for the resolution changes.
typeResolverinterface{
// Get gets a snapshot of the current name resolution results for target.
Get(targetstring)map[string]string
// Watch watches for the name resolution changes on target. It blocks until Stop() is invoked. The watch results are obtained via GetUpdate().
Watch(targetstring)
// GetUpdate returns a name resolution change when watch is triggered. It blocks until it observes a change. The caller needs to call it again to get the next change.