forked from pachyderm/pachyderm
/
main.go
331 lines (310 loc) · 8.82 KB
/
main.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package main
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/pachyderm/pachyderm/src/client"
ppsclient "github.com/pachyderm/pachyderm/src/client/pps"
"github.com/pachyderm/pachyderm/src/server/pfs/fuse"
"github.com/pachyderm/pachyderm/src/server/pkg/cmdutil"
"github.com/pachyderm/pachyderm/src/server/pkg/sync"
ppsserver "github.com/pachyderm/pachyderm/src/server/pps"
log "github.com/Sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/net/context"
"golang.org/x/sync/errgroup"
)
const (
// PFSInputPrefix is where the input repos reside
PFSInputPrefix = "/pfs"
// PFSOutputPrefix is where the output data resides
PFSOutputPrefix = "/pfs/out"
// FUSEMountPoint is where we mount FUSE
FUSEMountPoint = "/pfs/prev"
)
type appEnv struct {
PachydermAddress string `env:"PACHD_PORT_650_TCP_ADDR,required"`
PodName string `env:"PPS_POD_NAME,required"`
HeartbeatSecs string `env:"PPS_HEARTBEAT_SECS,required"`
MaxHeartbeatRetries string `env:"PPS_MAX_HEARTBEAT_RETRIES,required"`
}
func main() {
cmdutil.Main(do, &appEnv{})
}
func downloadInput(puller *sync.Puller, c *client.APIClient, commitMounts []*fuse.CommitMount) error {
var g errgroup.Group
for _, commitMount := range commitMounts {
commitMount := commitMount
if commitMount.Alias == "prev" || commitMount.Alias == "out" {
continue
}
g.Go(func() error {
return puller.Pull(c, filepath.Join(PFSInputPrefix, commitMount.Commit.Repo.Name),
commitMount.Commit, commitMount.DiffMethod, commitMount.Shard, commitMount.Lazy)
})
}
return g.Wait()
}
func uploadOutput(c *client.APIClient, out *fuse.CommitMount, overwrite bool) error {
return sync.Push(c, PFSOutputPrefix, out.Commit, overwrite)
}
func do(appEnvObj interface{}) error {
appEnv := appEnvObj.(*appEnv)
rootCmd := &cobra.Command{
Use: os.Args[0] + " job-id",
Short: `Pachyderm job-shim, coordinates with ppsd to create an output commit and run user work.`,
Long: `Pachyderm job-shim, coordinates with ppsd to create an output commit and run user work.`,
Run: cmdutil.RunFixedArgs(1, func(args []string) (retErr error) {
heartbeatSecs, err := strconv.Atoi(appEnv.HeartbeatSecs)
if err != nil {
panic(fmt.Sprintf("invalid heartbeat period: %s", appEnv.HeartbeatSecs))
}
maxRetries, err := strconv.Atoi(appEnv.MaxHeartbeatRetries)
if err != nil {
panic(fmt.Sprintf("invalid max heartbeat retries: %s", appEnv.MaxHeartbeatRetries))
}
defer func() {
// We always clear the output directory, this prevents filling
// up disk with completed container images.
if err := os.RemoveAll(PFSInputPrefix); err != nil && retErr == nil {
retErr = err
}
}()
ppsClient, err := ppsserver.NewInternalPodAPIClientFromAddress(fmt.Sprintf("%v:650", appEnv.PachydermAddress))
if err != nil {
return err
}
response, err := ppsClient.StartPod(
context.Background(),
&ppsserver.StartPodRequest{
Job: &ppsclient.Job{
ID: args[0],
},
PodName: appEnv.PodName,
})
if err != nil {
log.Errorf("error from StartPod: %s", err.Error())
return err
}
// Start sending ContinuePod to PPS to signal that we are alive
exitCh := make(chan struct{})
go func() {
tick := time.Tick(time.Duration(heartbeatSecs) * time.Second)
var numHeartbeatRetries int
for {
<-tick
res, err := ppsClient.ContinuePod(
context.Background(),
&ppsserver.ContinuePodRequest{
ChunkID: response.ChunkID,
PodName: appEnv.PodName,
},
)
if err != nil && numHeartbeatRetries < maxRetries {
log.Errorf("error from heartbeat: %s; retrying...", err.Error())
numHeartbeatRetries++
continue
}
// reset
numHeartbeatRetries = 0
if res != nil && res.Restart {
log.Errorf("chunk was revoked. restarting...")
}
if err != nil || res != nil && res.Restart {
select {
case exitCh <- struct{}{}:
// If someone received this signal, then they are
// responsible to exiting the program and release
// all resources.
log.Errorf("releasing resources...")
return
default:
// Otherwise, we just terminate the program.
// We use a non-zero exit code so k8s knows to create
// a new pod.
log.Errorf("terminating...")
os.Exit(1)
}
}
}
}()
if response.Transform.Debug {
log.SetLevel(log.DebugLevel)
}
// We want to make sure that we only send FinishPod once.
// The most bulletproof way would be to check that on server side,
// but this is easier.
var finished bool
// Make sure that we call FinishPod even if something caused a panic
defer func() {
if r := recover(); r != nil && !finished {
log.Errorf("job shim crashed; this is like a bug in pachyderm")
if _, err := ppsClient.FinishPod(
context.Background(),
&ppsserver.FinishPodRequest{
ChunkID: response.ChunkID,
PodName: appEnv.PodName,
Success: false,
},
); err != nil && retErr == nil {
retErr = err
}
}
}()
c, err := client.NewFromAddress(fmt.Sprintf("%v:650", appEnv.PachydermAddress))
if err != nil {
return err
}
// Setup the hostPath mount to use a unique directory for this pod
podDataDir := filepath.Join(ppsserver.JobDataPath, appEnv.PodName)
if err := os.Mkdir(podDataDir, 0777); err != nil {
return err
}
if err := os.Symlink(podDataDir, "/pfs"); err != nil {
return err
}
puller := sync.NewPuller()
defer func() {
if err := puller.CleanUp(); err != nil && retErr == nil {
retErr = err
}
}()
if err := downloadInput(puller, c, response.CommitMounts); err != nil {
return err
}
// Create /pfs/out
if err := os.MkdirAll(PFSOutputPrefix, 0777); err != nil {
return err
}
// mount /pfs/prev
var mounts []*fuse.CommitMount
for _, m := range response.CommitMounts {
if m.Alias == "prev" {
mounts = append(mounts, m)
}
}
if len(mounts) > 0 {
mounter := fuse.NewMounter(appEnv.PachydermAddress, c)
ready := make(chan bool)
errCh := make(chan error)
go func() {
if err := mounter.MountAndCreate(
FUSEMountPoint,
nil,
mounts,
ready,
response.Transform.Debug,
false,
true,
); err != nil {
errCh <- err
}
}()
select {
case <-ready:
case err := <-errCh:
return err
}
defer func() {
errCh := make(chan error)
go func() {
errCh <- mounter.Unmount(FUSEMountPoint)
}()
select {
case err := <-errCh:
if err != nil && retErr == nil {
retErr = err
}
case <-time.After(time.Duration(10 * time.Second)):
log.Errorf("unable to unmount FUSE")
}
}()
}
var readers []io.Reader
for _, line := range response.Transform.Stdin {
readers = append(readers, strings.NewReader(line+"\n"))
}
if len(response.Transform.Cmd) == 0 {
log.Errorf("unable to run; a cmd needs to be provided")
if _, err := ppsClient.FinishPod(
context.Background(),
&ppsserver.FinishPodRequest{
ChunkID: response.ChunkID,
PodName: appEnv.PodName,
Success: false,
},
); err != nil {
return err
}
finished = true
return
}
cmdCh := make(chan bool)
go func() {
cmd := exec.Command(response.Transform.Cmd[0], response.Transform.Cmd[1:]...)
cmd.Stdin = io.MultiReader(readers...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
success := true
if err := cmd.Run(); err != nil {
success = false
if exiterr, ok := err.(*exec.ExitError); ok {
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
for _, returnCode := range response.Transform.AcceptReturnCode {
if int(returnCode) == status.ExitStatus() {
success = true
}
}
}
}
if !success {
fmt.Fprintf(os.Stderr, "Error from exec: %s\n", err.Error())
}
}
cmdCh <- success
}()
var success bool
select {
case <-exitCh:
// Returning an error to ensure that this pod will be restarted
return errors.New("")
case success = <-cmdCh:
}
var outputMount *fuse.CommitMount
for _, c := range response.CommitMounts {
if c.Alias == "out" {
outputMount = c
break
}
}
if err := uploadOutput(c, outputMount, response.Transform.Overwrite); err != nil {
log.Errorf("err from uploading output: %s\n", err)
success = false
}
res, err := ppsClient.FinishPod(
context.Background(),
&ppsserver.FinishPodRequest{
ChunkID: response.ChunkID,
PodName: appEnv.PodName,
Success: success,
},
)
if err != nil {
return err
}
finished = true
if res.Restart {
return errors.New("restarting")
}
return nil
}),
}
return rootCmd.Execute()
}