-
Notifications
You must be signed in to change notification settings - Fork 47
/
main.go
143 lines (136 loc) · 3.65 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
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"time"
"cirello.io/dynamolock"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/urfave/cli"
)
func main() {
log.SetPrefix("lock: ")
log.SetFlags(0)
app := cli.NewApp()
app.HideVersion = true
app.Name = "lock"
app.Usage = "lock and execute given command"
app.Flags = []cli.Flag{
cli.BoolFlag{Name: "release-on-error,r"},
cli.BoolFlag{Name: "wait-for-lock,w"},
cli.StringFlag{
Name: "table",
Value: "locks",
},
}
app.Action = func(c *cli.Context) error {
lockName := c.Args().First()
if lockName == "" {
return errors.New("missing lock name")
}
cmd := c.Args().Tail()
if len(cmd) == 0 {
return errors.New("missing command")
}
tableName := c.String("table")
client, err := dialDynamoDB(tableName)
if err != nil {
return err
}
if err := createTable(client, tableName); err != nil {
return err
}
lock, err := grabLock(client, lockName, c.Bool("wait-for-lock"))
if err != nil {
return err
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
trap := make(chan os.Signal, 1)
signal.Notify(trap, os.Interrupt)
go func() {
<-trap
cancel()
}()
return runCommand(ctx, lock, c.Bool("release-on-error"), cmd)
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func dialDynamoDB(tableName string) (*dynamolock.Client, error) {
session, err := session.NewSession()
if err != nil {
return nil, fmt.Errorf("cannot create AWS session: %w", err)
}
client, err := dynamolock.New(
dynamodb.New(session),
tableName,
dynamolock.WithLeaseDuration(3*time.Second),
dynamolock.WithHeartbeatPeriod(1*time.Second),
dynamolock.WithPartitionKeyName("key"),
)
if err != nil {
return nil, fmt.Errorf("cannot start dynamolock client: %w", err)
}
return client, nil
}
func createTable(client *dynamolock.Client, tableName string) error {
_, err := client.CreateTable(tableName,
dynamolock.WithProvisionedThroughput(&dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(5),
WriteCapacityUnits: aws.Int64(5),
}),
dynamolock.WithCustomPartitionKeyName("key"),
)
if err != nil {
var awsErr awserr.RequestFailure
isTableAlreadyCreatedError := errors.As(err, &awsErr) && awsErr.StatusCode() == 400 && awsErr.Message() == "Cannot create preexisting table"
if !isTableAlreadyCreatedError {
return fmt.Errorf("cannot create dynamolock client table: %w", err)
}
}
return nil
}
func grabLock(client *dynamolock.Client, lockName string, wait bool) (*dynamolock.Lock, error) {
for {
lock, err := client.AcquireLock(lockName, dynamolock.WithDeleteLockOnRelease())
if err != nil && wait {
continue
} else if err != nil {
return nil, fmt.Errorf("cannot lock %s: %w", lockName, err)
}
return lock, err
}
}
func runCommand(ctx context.Context, lock *dynamolock.Lock, releaseOnError bool, cmd []string) error {
command := cmd[0]
var parameters []string
if len(cmd) > 1 {
parameters = cmd[1:]
}
wrappedCommand := exec.CommandContext(ctx, command, parameters...)
wrappedCommand.Stdin = os.Stdin
wrappedCommand.Stdout = os.Stdout
wrappedCommand.Stderr = os.Stderr
if err := wrappedCommand.Run(); err != nil {
if releaseOnError {
log.Println("errored, releasing lock")
if lockErr := lock.Close(); lockErr != nil {
log.Println("cannot release lock after failure:", lockErr)
}
}
return fmt.Errorf("error: %w", err)
}
if lockErr := lock.Close(); lockErr != nil {
log.Println("cannot release lock after completion:", lockErr)
}
return nil
}