forked from replicate/keepsake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserve.go
305 lines (269 loc) · 9.08 KB
/
serve.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package shared
// TODO(andreas): document this for R API etc
import (
"context"
"fmt"
"net"
"os"
"os/signal"
"syscall"
"time"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/replicate/replicate/go/pkg/console"
"github.com/replicate/replicate/go/pkg/errors"
"github.com/replicate/replicate/go/pkg/project"
"github.com/replicate/replicate/go/pkg/servicepb"
)
type projectGetter func() (proj *project.Project, err error)
type server struct {
servicepb.UnimplementedDaemonServer
workChan chan func() error
projectGetter projectGetter
project *project.Project
heartbeatsByExperimentID map[string]*HeartbeatProcess
}
func (s *server) CreateExperiment(ctx context.Context, req *servicepb.CreateExperimentRequest) (*servicepb.CreateExperimentReply, error) {
pbReqExp := req.GetExperiment()
args := project.CreateExperimentArgs{
Path: pbReqExp.GetPath(),
Command: pbReqExp.GetCommand(),
Params: valueMapFromPb(pbReqExp.GetParams()),
PythonPackages: pbReqExp.GetPythonPackages(),
PythonVersion: pbReqExp.GetPythonVersion(),
}
proj, err := s.getProject()
if err != nil {
return nil, handleError(err)
}
exp, err := proj.CreateExperiment(args, true, s.workChan, req.Quiet)
if err != nil {
return nil, handleError(err)
}
if !req.DisableHeartbeat {
s.heartbeatsByExperimentID[exp.ID] = StartHeartbeat(s.project, exp.ID)
}
pbRetExp := experimentToPb(exp)
return &servicepb.CreateExperimentReply{Experiment: pbRetExp}, nil
}
func (s *server) CreateCheckpoint(ctx context.Context, req *servicepb.CreateCheckpointRequest) (*servicepb.CreateCheckpointReply, error) {
pbReqChk := req.GetCheckpoint()
args := project.CreateCheckpointArgs{
Path: pbReqChk.GetPath(),
Metrics: valueMapFromPb(pbReqChk.GetMetrics()),
PrimaryMetric: primaryMetricFromPb(pbReqChk.PrimaryMetric),
Step: pbReqChk.GetStep(),
}
proj, err := s.getProject()
if err != nil {
return nil, handleError(err)
}
chk, err := proj.CreateCheckpoint(args, true, s.workChan, req.Quiet)
if err != nil {
return nil, handleError(err)
}
pbRetChk := checkpointToPb(chk)
return &servicepb.CreateCheckpointReply{Checkpoint: pbRetChk}, nil
}
func (s *server) SaveExperiment(ctx context.Context, req *servicepb.SaveExperimentRequest) (*servicepb.SaveExperimentReply, error) {
expPb := req.GetExperiment()
exp := experimentFromPb(expPb)
proj, err := s.getProject()
if err != nil {
return nil, handleError(err)
}
exp, err = proj.SaveExperiment(exp, req.Quiet)
if err != nil {
return nil, handleError(err)
}
return &servicepb.SaveExperimentReply{Experiment: experimentToPb(exp)}, nil
}
func (s *server) StopExperiment(ctx context.Context, req *servicepb.StopExperimentRequest) (*servicepb.StopExperimentReply, error) {
if _, ok := s.heartbeatsByExperimentID[req.ExperimentID]; ok {
s.heartbeatsByExperimentID[req.ExperimentID].Kill()
delete(s.heartbeatsByExperimentID, req.ExperimentID)
}
proj, err := s.getProject()
if err != nil {
return nil, handleError(err)
}
if err := proj.StopExperiment(req.ExperimentID); err != nil {
return nil, handleError(err)
}
return &servicepb.StopExperimentReply{}, nil
}
func (s *server) GetExperiment(ctx context.Context, req *servicepb.GetExperimentRequest) (*servicepb.GetExperimentReply, error) {
proj, err := s.getProject()
if err != nil {
return nil, handleError(err)
}
exp, err := proj.ExperimentFromPrefix(req.ExperimentIDPrefix)
if err != nil {
return nil, handleError(err)
}
expPb := experimentToPb(exp)
return &servicepb.GetExperimentReply{Experiment: expPb}, nil
}
func (s *server) ListExperiments(ctx context.Context, req *servicepb.ListExperimentsRequest) (*servicepb.ListExperimentsReply, error) {
proj, err := s.getProject()
if err != nil {
return nil, handleError(err)
}
experiments, err := proj.Experiments()
if err != nil {
return nil, handleError(err)
}
experimentsPb := experimentsToPb(experiments)
return &servicepb.ListExperimentsReply{Experiments: experimentsPb}, nil
}
func (s *server) DeleteExperiment(ctx context.Context, req *servicepb.DeleteExperimentRequest) (*servicepb.DeleteExperimentReply, error) {
proj, err := s.getProject()
if err != nil {
return nil, handleError(err)
}
exp, err := proj.ExperimentByID(req.ExperimentID)
if err != nil {
return nil, handleError(err)
}
if err := s.project.DeleteExperiment(exp); err != nil {
return nil, handleError(err)
}
// This is slow, see https://github.com/replicate/replicate/issues/333
for _, checkpoint := range exp.Checkpoints {
if err := s.project.DeleteCheckpoint(checkpoint); err != nil {
return nil, handleError(err)
}
}
return &servicepb.DeleteExperimentReply{}, nil
}
func (s *server) CheckoutCheckpoint(ctx context.Context, req *servicepb.CheckoutCheckpointRequest) (*servicepb.CheckoutCheckpointReply, error) {
proj, err := s.getProject()
if err != nil {
return nil, handleError(err)
}
chk, exp, err := proj.CheckpointFromPrefix(req.CheckpointIDPrefix)
if err != nil {
return nil, handleError(err)
}
err = s.project.CheckoutCheckpoint(chk, exp, req.OutputDirectory, req.Quiet)
if err != nil {
return nil, handleError(err)
}
return &servicepb.CheckoutCheckpointReply{}, nil
}
func (s *server) GetExperimentStatus(ctx context.Context, req *servicepb.GetExperimentStatusRequest) (*servicepb.GetExperimentStatusReply, error) {
proj, err := s.getProject()
if err != nil {
return nil, handleError(err)
}
isRunning, err := proj.ExperimentIsRunning(req.ExperimentID)
if err != nil {
return nil, handleError(err)
}
var status servicepb.GetExperimentStatusReply_Status
if isRunning {
status = servicepb.GetExperimentStatusReply_RUNNING
} else {
status = servicepb.GetExperimentStatusReply_STOPPED
}
return &servicepb.GetExperimentStatusReply{Status: status}, nil
}
func (s *server) getProject() (*project.Project, error) {
// we get the project lazily so that we can return a protobuf exception to the client
// as part of a request flow
if s.project != nil {
return s.project, nil
}
proj, err := s.projectGetter()
if err != nil {
return nil, err
}
s.project = proj
return proj, nil
}
func Serve(projGetter projectGetter, socketPath string) error {
console.Debug("Starting daemon")
listener, err := net.Listen("unix", socketPath)
if err != nil {
return fmt.Errorf("Failed to open UNIX socket on %s: %w", socketPath, err)
}
grpcServer := grpc.NewServer()
s := &server{
// block if there already are two items on the queue, in case uploading is a bottleneck
// TODO(andreas): warn the user if the queue is full, so they know that they should
// upload at a lesser interval
workChan: make(chan func() error, 2),
projectGetter: projGetter,
heartbeatsByExperimentID: make(map[string]*HeartbeatProcess),
}
servicepb.RegisterDaemonServer(grpcServer, s)
// when the process exits, make sure any pending
// uploads are completed
completedChan := make(chan struct{})
sigc := make(chan os.Signal, 1)
signal.Notify(sigc,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
go func() {
<-sigc
console.Debug("Exiting...")
s.workChan <- nil // nil is an exit sentinel
// Wait a short sec so completedChan gets filled if workChan is empty. (Surely there's a more elegant way to do this.)
time.Sleep(1 * time.Millisecond)
select {
case <-completedChan:
console.Debug("No work left to do, exiting immediately")
// Wait a sec so the log messages displays after KeyboardInterrupt traceback from Python.
// If tasks complete within this time, then previous case will be selected and message will never be displayed.
// Anything slower than this and Python seems to beat it. This isn't a perfect solution,
// but it's just to make a log message prettier so it doesn't need to be perfect.
case <-time.After(250 * time.Millisecond):
console.Info("Your program has ended, but Replicate is still saving data. It will exit when it has finished. Hold on...")
select {
case <-completedChan:
console.Debug("Work completed")
case <-time.After(5 * time.Second):
console.Info("Replicate is still saving. If you force quit, you might lose data.")
<-completedChan
}
}
for _, hb := range s.heartbeatsByExperimentID {
hb.Kill()
}
grpcServer.Stop()
}()
go func() {
for {
work := <-s.workChan
if work == nil {
completedChan <- struct{}{}
return
}
if err := work(); err != nil {
console.Error("%v", err)
// TODO(andreas): poll status endpoint, put errors in chan of messages to return. also include progress in these messages
}
}
}()
if err := grpcServer.Serve(listener); err != nil {
return fmt.Errorf("Failed to start server: %w", err)
}
return nil
}
func handleError(err error) error {
reason := errors.Code(err)
if reason != "" {
st := status.New(codes.Internal, err.Error())
details := &errdetails.ErrorInfo{Reason: reason}
st, err := st.WithDetails(details)
if err != nil {
return err
}
return st.Err()
}
return status.Error(codes.Unknown, err.Error())
}