-
Notifications
You must be signed in to change notification settings - Fork 66
/
replica.go
437 lines (398 loc) · 11.6 KB
/
replica.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/*
Copyright © 2020 The OpenEBS Authors
This file was originally authored by Rancher Labs
under Apache License 2018.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package app
import (
"errors"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/openebs/jiva/alertlog"
"github.com/openebs/jiva/sync"
"github.com/openebs/jiva/types"
"github.com/docker/go-units"
"github.com/openebs/jiva/controller/client"
"github.com/openebs/jiva/replica"
"github.com/openebs/jiva/replica/rest"
"github.com/openebs/jiva/replica/rpc"
"github.com/openebs/jiva/util"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
const (
maxLogFileSize = "maxLogFileSize"
retentionPeriod = "retentionPeriod"
maxBackups = "maxBackups"
defaultLogFileSize = 100
defaultRetentionPeriod = 180
defaultMaxBackups = 5
)
func ReplicaCmd() cli.Command {
return cli.Command{
Name: "replica",
UsageText: "longhorn controller DIRECTORY SIZE",
Flags: []cli.Flag{
cli.StringFlag{
Name: "listen",
Value: ":9502",
},
cli.StringFlag{
Name: "frontendIP",
Value: "",
},
cli.StringFlag{
Name: "cloneIP",
Value: "",
},
cli.StringFlag{
Name: "snapName",
Value: "",
},
cli.StringFlag{
Name: "backing-file",
Usage: "qcow file to use as the base image of this disk",
},
cli.BoolTFlag{
Name: "sync-agent",
},
cli.StringFlag{
Name: "size",
Usage: "Volume size in bytes or human readable 42kb, 42mb, 42gb",
},
cli.StringFlag{
Name: "type",
Value: "",
},
cli.BoolTFlag{
Name: "logtofile",
Usage: "Logs of replica will also be written to the file along with stdout",
},
cli.IntFlag{
Name: retentionPeriod,
Usage: "Retention period of log file in days",
Value: defaultRetentionPeriod,
},
cli.IntFlag{
Name: maxLogFileSize,
Usage: "Max size of log file in mb",
Value: defaultLogFileSize,
},
cli.IntFlag{
Name: maxBackups,
Usage: "Max number of log files to keep while creating new log file once size of log exceeds to maxLogFileSize",
Value: defaultMaxBackups,
},
},
Action: func(c *cli.Context) {
if err := startReplica(c); err != nil {
logrus.Fatalf("Error running start replica command: %v", err)
}
},
}
}
func CheckReplicaState(frontendIP string, replicaIP string) (string, error) {
url := "http://" + frontendIP + ":9501"
ControllerClient := client.NewControllerClient(url)
reps, err := ControllerClient.ListReplicas()
if err != nil {
return "", err
}
for _, rep := range reps {
if rep.Address == replicaIP {
return rep.Mode, nil
}
}
return "", err
}
func AutoConfigureReplica(s *replica.Server, frontendIP string, address string, replicaType string) {
retryCount := 10
checkagain:
retryCount--
state, err := CheckReplicaState(frontendIP, address)
if err != nil {
logrus.Warningf("Failed to check replica state, err: %v, will retry (%v retry left)", err, retryCount)
if retryCount == 0 {
logrus.Fatalf("Retry count exceeded, Shutting down...")
}
time.Sleep(5 * time.Second)
goto checkagain
} else if state == "ERR" {
retryCount++
logrus.Infof("Got replica state: %v", state)
// replica may be in errored state marked by controller and
// not yet removed. The cause of ERR state would be following:
// - I/O error while R/W operations
// - Failed to revert snapshot
time.Sleep(5 * time.Second)
goto checkagain
} else {
// Replica might be in rebuilding state, closing will change it to
// closed state, then it can be registered, else register replica
// will fail.
_ = s.Close()
// This is not required any more as while adding at controller, canAdd
// func checks if the replica is already present
// this is just to be sure that replica is not attached to
// controller. Assumption is replica might be in RO, RW or in
// "" state and not removed from controller.
// AutoRmReplica(frontendIP, address)
if err := AutoAddReplica(s, frontendIP, address, replicaType); err != nil {
s.Close()
logrus.Fatalf("Failed to add replica to controller, err: %v, Shutting down...", err)
}
}
}
func CloneReplica(s *replica.Server, address string, cloneIP string, snapName string) error {
var err error
url := "http://" + cloneIP + ":9501"
task := sync.NewTask(url)
if err = task.CloneReplica(s, url, address, cloneIP, snapName); err != nil {
alertlog.Logger.Errorw("",
"eventcode", "jiva.volume.replica.clone.failure",
"msg", "Failed to clone Jiva volume replica",
"rname", snapName,
)
return err
}
if s.Replica() != nil {
err = s.Replica().SetCloneStatus("completed")
}
if err != nil {
alertlog.Logger.Errorw("",
"eventcode", "jiva.volume.replica.clone.failure",
"msg", "Failed to clone Jiva volume replica",
"rname", snapName,
)
} else {
alertlog.Logger.Infow("",
"eventcode", "jiva.volume.replica.clone.success",
"msg", "Successfully cloned Jiva volume replica",
"rname", snapName,
)
}
return err
}
func startLoggingToFile(c *cli.Context) error {
dir := c.Args()[0]
lf := util.LogToFile{
Enable: true,
MaxLogFileSize: c.Int(maxLogFileSize),
MaxBackups: c.Int(maxBackups),
RetentionPeriod: c.Int(retentionPeriod),
}
path := dir + "/" + util.LogInfo
_, err := os.Stat(path)
if err == nil {
logrus.Info("Read log info")
lf, err = util.ReadLogInfo(dir)
if err != nil {
return err
}
} else if err != nil && os.IsNotExist(err) {
// do nothing as file will be created in StartLoggingToFile
} else if err != nil {
return err
}
if !lf.Enable {
logrus.Info("Logging to file is not enabled")
return nil
}
return util.StartLoggingToFile(dir, lf)
}
func startReplica(c *cli.Context) error {
formatter := &logrus.TextFormatter{
FullTimestamp: true,
}
logrus.SetFormatter(formatter)
if c.NArg() != 1 {
return errors.New("directory name is required")
}
types.MaxChainLength, _ = strconv.Atoi(os.Getenv("MAX_CHAIN_LENGTH"))
if types.MaxChainLength == 0 {
logrus.Infof("MAX_CHAIN_LENGTH env not set, default value is 512")
} else {
logrus.Infof("MAX_CHAIN_LENGTH: %v", types.MaxChainLength)
}
dir := c.Args()[0]
replicaType := c.String("type")
if err := os.Mkdir(dir, 0700); err != nil && !os.IsExist(err) {
logrus.Errorf("failed to create directory: %s", dir)
return err
}
if c.Bool("logtofile") {
if err := startLoggingToFile(c); err != nil {
return err
}
}
address := c.String("listen")
s := replica.NewServer(address, dir, 512, replicaType)
go replica.CreateHoles()
frontendIP := c.String("frontendIP")
cloneIP := c.String("cloneIP")
snapName := c.String("snapName")
size := c.String("size")
if size != "" {
//Units bails with an error size is provided with i, like Gi
//The following will convert - G, Gi, GiB into G
size = strings.Split(size, "i")[0]
size, err := units.RAMInBytes(size)
if err != nil {
return err
}
if err := s.Create(size); err != nil {
return err
}
}
if address == ":9502" {
host, _ := os.Hostname()
addrs, _ := net.LookupIP(host)
for _, addr := range addrs {
if ipv4 := addr.To4(); ipv4 != nil {
address = ipv4.String()
if address == "127.0.0.1" {
address = address + ":9502"
continue
}
address = address + ":9502"
break
}
}
}
controlAddress, dataAddress, syncAddress, err := util.ParseAddresses(address)
if err != nil {
return err
}
logrus.Infof("Starting replica having replicaType: %v, frontendIP: %v, size: %v, dir: %v", replicaType, frontendIP, size, dir)
logrus.Infof("Setting replicaAddr: %v, controlAddr: %v, dataAddr: %v, syncAddr: %v", address, controlAddress, dataAddress, syncAddress)
var resp error
controlResp := make(chan error)
syncResp := make(chan error)
rpcResp := make(chan error)
go func() {
server := rest.NewServer(s)
router := http.Handler(rest.NewRouter(server))
router = util.FilteredLoggingHandler(map[string]struct{}{
"/ping": {},
"/v1/replicas/1": {},
"/v1/replicas/1/volusage": {},
}, os.Stdout, router)
logrus.Infof("Listening on control %s", controlAddress)
controlResp <- http.ListenAndServe(controlAddress, router)
}()
go func() {
rpcServer := rpc.New(dataAddress, s)
logrus.Infof("Listening on data %s", dataAddress)
rpcResp <- rpcServer.ListenAndServe()
}()
if c.Bool("sync-agent") {
exe, err := exec.LookPath(os.Args[0])
if err != nil {
return err
}
exe, err = filepath.Abs(exe)
if err != nil {
return err
}
go func() {
cmd := exec.Command(exe, "sync-agent", "--listen", syncAddress)
cmd.SysProcAttr = &syscall.SysProcAttr{
Pdeathsig: syscall.SIGKILL,
}
cmd.Dir = dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
httpTimeout := os.Getenv(types.SyncHTTPClientTimeoutKey)
if httpTimeout != "" {
cmd.Env = []string{types.SyncHTTPClientTimeoutKey + "=" + httpTimeout}
}
syncResp <- cmd.Run()
}()
}
if frontendIP != "" {
if address == ":9502" {
address = "localhost:9502"
}
go AutoConfigureReplica(s, frontendIP, "tcp://"+address, replicaType)
}
for s.Replica() == nil {
logrus.Infof("Waiting for s.Replica() to be non nil")
time.Sleep(2 * time.Second)
}
if replicaType == "clone" && snapName != "" {
logrus.Infof("Starting clone process")
status := s.Replica().GetCloneStatus()
if status != "completed" {
logrus.Infof("Set clone status as inProgress")
if err = s.Replica().SetCloneStatus("inProgress"); err != nil {
logrus.Error("Error in setting the clone status as 'inProgress'")
return err
}
if err = CloneReplica(s, "tcp://"+address, cloneIP, snapName); err != nil {
logrus.Error("Error in cloning replica, setting clone status as 'error'")
if statusErr := s.Replica().SetCloneStatus("error"); err != nil {
logrus.Errorf("Error in setting the clone status as 'error', found error:%v", statusErr)
return err
}
return err
}
}
logrus.Infof("Set clone status as Completed")
if err := s.Replica().SetCloneStatus("completed"); err != nil {
logrus.Error("Error in setting the clone status as 'completed'")
return err
}
logrus.Infof("Clone process completed successfully")
} else {
logrus.Infof("Set clone status as NA")
if err := s.Replica().SetCloneStatus("NA"); err != nil {
logrus.Error("Error in setting the clone status as 'NA'")
return err
}
}
select {
case resp = <-controlResp:
alertlog.Logger.Errorw("",
"eventcode", "jiva.volume.replica.api.exited",
"msg", "Jiva volume replica API stopped",
"rname", address,
)
logrus.Fatalf("Rest API exited: %v", resp)
case resp = <-rpcResp:
alertlog.Logger.Errorw("",
"eventcode", "jiva.volume.replica.rpc.exited",
"msg", "Jiva volume replica RPC stopped",
"rname", address,
)
logrus.Fatalf("RPC listen exited: %v", resp)
case resp = <-syncResp:
alertlog.Logger.Errorw("",
"eventcode", "jiva.volume.replica.sync.exited",
"msg", "Jiva volume replica sync stopped",
"rname", address,
)
logrus.Fatalf("Sync process exited: %v", resp)
}
alertlog.Logger.Infow("",
"eventcode", "jiva.volume.replica.start.success",
"msg", "Successfully started Jiva volume replica",
"rname", address,
)
return resp
}