forked from canonical/lxd
/
transfer.go
128 lines (102 loc) · 2.55 KB
/
transfer.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
package main
import (
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"strings"
"github.com/gorilla/websocket"
"github.com/pborman/uuid"
"github.com/lxc/lxd/lxd/migration"
"github.com/lxc/lxd/lxd/rsync"
"github.com/lxc/lxd/shared"
)
// Send an rsync stream of a path over a websocket
func rsyncSend(conn *websocket.Conn, path string, rsyncArgs string) error {
cmd, dataSocket, stderr, err := rsyncSendSetup(path, rsyncArgs)
if err != nil {
return err
}
if dataSocket != nil {
defer dataSocket.Close()
}
readDone, writeDone := shared.WebsocketMirror(conn, dataSocket, io.ReadCloser(dataSocket), nil, nil)
output, err := ioutil.ReadAll(stderr)
if err != nil {
cmd.Process.Kill()
cmd.Wait()
return fmt.Errorf("Failed to rsync: %v\n%s", err, output)
}
err = cmd.Wait()
<-readDone
<-writeDone
if err != nil {
return fmt.Errorf("Failed to rsync: %v\n%s", err, output)
}
return nil
}
// Spawn the rsync process
func rsyncSendSetup(path string, rsyncArgs string) (*exec.Cmd, net.Conn, io.ReadCloser, error) {
auds := fmt.Sprintf("@lxc-to-lxd/%s", uuid.NewRandom().String())
if len(auds) > shared.ABSTRACT_UNIX_SOCK_LEN-1 {
auds = auds[:shared.ABSTRACT_UNIX_SOCK_LEN-1]
}
l, err := net.Listen("unix", auds)
if err != nil {
return nil, nil, nil, err
}
execPath, err := os.Readlink("/proc/self/exe")
if err != nil {
return nil, nil, nil, err
}
rsyncCmd := fmt.Sprintf("sh -c \"%s netcat %s\"", execPath, auds)
args := []string{
"-ar",
"--devices",
"--numeric-ids",
"--partial",
"--sparse",
"--xattrs",
"--delete",
"--compress",
"--compress-level=2",
}
if rsync.AtLeast("3.1.3") {
args = append(args, "--filter=-x security.selinux")
}
if rsync.AtLeast("3.1.0") {
args = append(args, "--ignore-missing-args")
}
if rsyncArgs != "" {
args = append(args, strings.Split(rsyncArgs, " ")...)
}
args = append(args, []string{path, "localhost:/tmp/foo"}...)
args = append(args, []string{"-e", rsyncCmd}...)
cmd := exec.Command("rsync", args...)
cmd.Stdout = os.Stderr
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, nil, nil, err
}
if err := cmd.Start(); err != nil {
return nil, nil, nil, err
}
conn, err := l.Accept()
if err != nil {
cmd.Process.Kill()
cmd.Wait()
return nil, nil, nil, err
}
l.Close()
return cmd, conn, stderr, nil
}
func protoSendError(ws *websocket.Conn, err error) {
migration.ProtoSendControl(ws, err)
if err != nil {
closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")
ws.WriteMessage(websocket.CloseMessage, closeMsg)
ws.Close()
}
}