blob: d54b35c50f9628186f9cfbca8f62802b7cd7eef0 [file] [log] [blame]
Serge Bazanski9c09c4e2020-03-24 13:58:01 +01001// 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
17package supervisor
18
19// Supporting infrastructure to allow running some non-Go payloads under supervision.
20
21import (
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.
33func 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 Bazanski967be212020-11-02 11:26:59 +010054// RunCommand will create a Runnable that starts a long-running command, whose exit is determined to be a failure.
55func 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 Bazanski9c09c4e2020-03-24 13:58:01 +010062}