-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
200 lines (173 loc) · 4.42 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
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"strings"
"time"
"github.com/bry00/fmutex/mutex"
)
const (
FlagRoot = "root"
EnvRoot = "FMUTEX_ROOT"
FlagId = "id"
FlagSilent = "s"
FlagPulse = "pulse"
FlagRefresh = "refresh"
FlagLimit = "limit"
FlagTimeout = "timeout"
)
var cmn = struct { // Common flags
Root string
Id string
Silent bool
}{
Root: ifEmptyStr(os.Getenv(EnvRoot), os.TempDir()),
Silent: false,
}
var lck = struct { // Lock flags
Pulse time.Duration
Refresh time.Duration
Limit time.Duration
Timeout time.Duration
}{
Pulse: mutex.DefaultPulse,
Refresh: mutex.DefaultRefresh,
Limit: mutex.DefaultDeadTimeout,
}
const (
CmdLock = "lock"
CmdRelease = "release"
CmdUnlock = "unlock" // An alias to CmdRelease
CmdTest = "test"
)
var (
cmdLock *flag.FlagSet
cmdRelease *flag.FlagSet
cmdTest *flag.FlagSet
cmdAll []*flag.FlagSet
cmdNames []string
)
func init() {
log.SetFlags(0)
log.SetPrefix(fmt.Sprintf("%s: ", getProg(os.Args)))
flag.Usage = usage
flag.StringVar(&cmn.Root, FlagRoot, cmn.Root, "root directory for mutex(es)")
flag.StringVar(&cmn.Id, FlagId, cmn.Id, "mutex id")
flag.BoolVar(&cmn.Silent, FlagSilent, cmn.Silent, "silent execution")
cmdLock = flag.NewFlagSet(CmdLock, flag.ExitOnError)
cmdLock.DurationVar(&lck.Pulse, FlagPulse, lck.Pulse, "determines frequency of locking attempts")
cmdLock.DurationVar(&lck.Refresh, FlagRefresh, lck.Refresh, "determines frequency of saving current timestamp in a locking file")
cmdLock.DurationVar(&lck.Limit, FlagLimit, lck.Limit, "determines how long takes to consider given mutex as \"dead\"")
cmdLock.DurationVar(&lck.Timeout, FlagTimeout, lck.Timeout, "locking timeout (if > 0)")
cmdRelease = flag.NewFlagSet(CmdRelease, flag.ExitOnError)
cmdTest = flag.NewFlagSet(CmdTest, flag.ExitOnError)
cmdAll, cmdNames = mkCommands(cmdLock, cmdRelease, cmdTest)
}
func main() {
flag.Parse()
if isEmptyStr(cmn.Id) {
log.Fatalf("Flag -%s is required.", FlagId)
}
if flag.NArg() < 1 {
log.Fatalf("Parameter error - expected command, one of: %s", strings.Join(cmdNames, ", "))
}
if cmn.Silent {
log.SetOutput(ioutil.Discard)
}
switch flag.Arg(0) {
case CmdLock:
cmdLock.Parse(flag.Args()[1:])
doLock()
if !cmn.Silent {
fmt.Println("LOCKED")
}
case CmdRelease, CmdUnlock:
cmdRelease.Parse(flag.Args()[1:])
doUnlock()
if !cmn.Silent {
fmt.Println("RELEASED")
}
case CmdTest:
cmdTest.Parse(flag.Args()[1:])
os.Exit(doTest())
default:
log.Fatalf("Fatal parameter error - unknown command \"%s\", valid commands are: %s", flag.Arg(0),
strings.Join(cmdNames, ", "))
}
}
func doTest() int {
m := newMutex()
lockPath := m.LockPath()
if tm := m.When(); tm.IsZero() {
log.Printf("Mutex \"%s\" (%s) is unlocked", m.Id(), lockPath)
return 1
} else {
log.Printf("Mutex \"%s\" (%s) is locked: %s", m.Id(), lockPath, tm.Format(time.RFC3339))
}
return 0
}
func doLock() {
m := newMutex()
if err := m.TryLock(lck.Timeout); err != nil {
log.Fatalf("Cannot lock mutex \"%s\": %v", m.Id(), err)
}
}
func doUnlock() {
m := newMutex()
if err := m.TryUnlock(); err != nil {
log.Fatalf("Cannot unlock mutex \"%s\": %v", m.Id(), err)
}
}
func newMutex() *mutex.Mutex {
result, err := mutex.NewMutexExt(cmn.Root, cmn.Id, lck.Pulse, lck.Refresh, lck.Limit)
if err != nil {
log.Fatalf("Cannot create mutex \"%s\": %v", cmn.Id, err)
}
return result
}
func ifEmptyStr(str string, defaultStr string) string {
if isEmptyStr(str) {
return defaultStr
}
return str
}
func isEmptyStr(str string) bool {
return strings.TrimSpace(str) == ""
}
func getProg(args []string) string {
base := path.Base(args[0])
if i := strings.LastIndex(base, "."); i < 0 {
return base
} else {
return base[0:i]
}
}
func mkCommands(cmds ...*flag.FlagSet) ([]*flag.FlagSet, []string) {
var result []string
for _, c := range cmds {
result = append(result, c.Name())
}
return cmds, result
}
func usage() {
prog := getProg(os.Args)
fmt.Fprintf(os.Stderr, "Program %s s designated to lock/unlock file-based mutexes.\n"+
"Usage:\n"+
"\t%s [options] {%s} [command-specific options]\n\n"+
"options:\n",
prog, prog, strings.Join(cmdNames, ", "))
flag.PrintDefaults()
for _, c := range cmdAll {
var options = 0
c.VisitAll(func(_ *flag.Flag) { options++ })
if options > 0 {
fmt.Fprintf(os.Stderr, "\n%s's options:\n", c.Name())
c.PrintDefaults()
}
}
fmt.Fprintln(os.Stderr)
}