Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 1 | // Copyright 2020 The Monogon Project Authors. |
| 2 | // |
| 3 | // SPDX-License-Identifier: Apache-2.0 |
| 4 | // |
| 5 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | // you may not use this file except in compliance with the License. |
| 7 | // You may obtain a copy of the License at |
| 8 | // |
| 9 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | // |
| 11 | // Unless required by applicable law or agreed to in writing, software |
| 12 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | // See the License for the specific language governing permissions and |
| 15 | // limitations under the License. |
| 16 | |
| 17 | package supervisor |
| 18 | |
| 19 | // Supporting infrastructure to allow running some non-Go payloads under supervision. |
| 20 | |
| 21 | import ( |
| 22 | "context" |
| 23 | "net" |
| 24 | "os/exec" |
| 25 | |
| 26 | "google.golang.org/grpc" |
| 27 | ) |
| 28 | |
| 29 | // GRPCServer creates a Runnable that serves gRPC requests as longs as it's not canceled. |
| 30 | // If graceful is set to true, the server will be gracefully stopped instead of plain stopped. This means all pending |
| 31 | // RPCs will finish, but also requires streaming gRPC handlers to check their context liveliness and exit accordingly. |
| 32 | // If the server code does not support this, `graceful` should be false and the server will be killed violently instead. |
| 33 | func GRPCServer(srv *grpc.Server, lis net.Listener, graceful bool) Runnable { |
| 34 | return func(ctx context.Context) error { |
| 35 | Signal(ctx, SignalHealthy) |
| 36 | errC := make(chan error) |
| 37 | go func() { |
| 38 | errC <- srv.Serve(lis) |
| 39 | }() |
| 40 | select { |
| 41 | case <-ctx.Done(): |
| 42 | if graceful { |
| 43 | srv.GracefulStop() |
| 44 | } else { |
| 45 | srv.Stop() |
| 46 | } |
| 47 | return ctx.Err() |
| 48 | case err := <-errC: |
| 49 | return err |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
Serge Bazanski | 967be21 | 2020-11-02 11:26:59 +0100 | [diff] [blame] | 54 | // RunCommand will create a Runnable that starts a long-running command, whose exit is determined to be a failure. |
| 55 | func RunCommand(ctx context.Context, cmd *exec.Cmd) error { |
| 56 | Signal(ctx, SignalHealthy) |
| 57 | cmd.Stdout = RawLogger(ctx) |
| 58 | cmd.Stderr = RawLogger(ctx) |
| 59 | err := cmd.Run() |
| 60 | Logger(ctx).Infof("Command returned: %v", err) |
| 61 | return err |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 62 | } |