forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rsync.go
376 lines (323 loc) · 10.8 KB
/
rsync.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
package rsync
import (
"errors"
"fmt"
"io"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"github.com/golang/glog"
"github.com/spf13/cobra"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions"
"github.com/openshift/origin/pkg/util/fsnotification"
)
const (
// RsyncRecommendedName is the recommended name for the rsync command
RsyncRecommendedName = "rsync"
noRsyncUnixWarning = "WARNING: rsync command not found in path. Please use your package manager to install it.\n"
noRsyncWindowsWarning = "WARNING: rsync command not found in path. Download cwRsync for Windows and add it to your PATH.\n"
)
var (
rsyncLong = templates.LongDesc(`
Copy local files to or from a pod container
This command will copy local files to or from a remote container.
It only copies the changed files using the rsync command from your OS.
To ensure optimum performance, install rsync locally. In UNIX systems,
use your package manager. In Windows, install cwRsync from
https://www.itefix.net/cwrsync.
If no container is specified, the first container of the pod is used
for the copy.
The following flags are passed to rsync by default:
--archive --no-owner --no-group --omit-dir-times --numeric-ids
`)
rsyncExample = templates.Examples(`
# Synchronize a local directory with a pod directory
%[1]s ./local/dir/ POD:/remote/dir
# Synchronize a pod directory with a local directory
%[1]s POD:/remote/dir/ ./local/dir`)
rsyncDefaultFlags = []string{"--archive", "--no-owner", "--no-group", "--omit-dir-times", "--numeric-ids"}
)
// copyStrategy
type copyStrategy interface {
Copy(source, destination *pathSpec, out, errOut io.Writer) error
Validate() error
String() string
}
// executor executes commands
type executor interface {
Execute(command []string, in io.Reader, out, err io.Writer) error
}
// forwarder forwards pod ports to the local machine
type forwarder interface {
ForwardPorts(ports []string, stopChan <-chan struct{}) error
}
// podChecker can check if pods are valid (exists, etc)
type podChecker interface {
CheckPod() error
}
// RsyncOptions holds the options to execute the sync command
type RsyncOptions struct {
Namespace string
ContainerName string
Source *pathSpec
Destination *pathSpec
Strategy copyStrategy
StrategyName string
Quiet bool
Delete bool
Watch bool
Compress bool
SuggestedCmdUsage string
RsyncInclude []string
RsyncExclude []string
RsyncProgress bool
RsyncNoPerms bool
genericclioptions.IOStreams
}
func NewRsyncOptions(streams genericclioptions.IOStreams) *RsyncOptions {
return &RsyncOptions{
IOStreams: streams,
}
}
// NewCmdRsync creates a new sync command
func NewCmdRsync(name, parent string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
o := NewRsyncOptions(streams)
cmd := &cobra.Command{
Use: fmt.Sprintf("%s SOURCE DESTINATION", name),
Short: "Copy files between local filesystem and a pod",
Long: rsyncLong,
Example: fmt.Sprintf(rsyncExample, parent+" "+name),
Run: func(c *cobra.Command, args []string) {
kcmdutil.CheckErr(o.Complete(f, c, args))
kcmdutil.CheckErr(o.Validate())
kcmdutil.CheckErr(o.RunRsync())
},
}
// NOTE: When adding new flags to the command, please update the rshExcludeFlags in copyrsync.go
// if those flags should not be passed to the rsh command.
cmd.Flags().StringVarP(&o.ContainerName, "container", "c", "", "Container within the pod")
cmd.Flags().StringVar(&o.StrategyName, "strategy", "", "Specify which strategy to use for copy: rsync, rsync-daemon, or tar")
// Flags for rsync options, Must match rsync flag names
cmd.Flags().BoolVarP(&o.Quiet, "quiet", "q", false, "Suppress non-error messages")
cmd.Flags().BoolVar(&o.Delete, "delete", false, "If true, delete files not present in source")
cmd.Flags().StringSliceVar(&o.RsyncExclude, "exclude", nil, "If true, exclude files matching specified pattern")
cmd.Flags().StringSliceVar(&o.RsyncInclude, "include", nil, "If true, include files matching specified pattern")
cmd.Flags().BoolVar(&o.RsyncProgress, "progress", false, "If true, show progress during transfer")
cmd.Flags().BoolVar(&o.RsyncNoPerms, "no-perms", false, "If true, do not transfer permissions")
cmd.Flags().BoolVarP(&o.Watch, "watch", "w", false, "Watch directory for changes and resync automatically")
cmd.Flags().BoolVar(&o.Compress, "compress", false, "compress file data during the transfer")
return cmd
}
func warnNoRsync(out io.Writer) {
if isWindows() {
fmt.Fprintf(out, noRsyncWindowsWarning)
return
}
fmt.Fprintf(out, noRsyncUnixWarning)
}
func (o *RsyncOptions) determineStrategy(f kcmdutil.Factory, cmd *cobra.Command, name string) (copyStrategy, error) {
switch name {
case "":
// Default case, use an rsync strategy first and then fallback to Tar
strategies := copyStrategies{}
if hasLocalRsync() {
if isWindows() {
strategy, err := newRsyncDaemonStrategy(f, cmd, o)
if err != nil {
return nil, err
}
strategies = append(strategies, strategy)
} else {
strategy, err := newRsyncStrategy(f, cmd, o)
if err != nil {
return nil, err
}
strategies = append(strategies, strategy)
}
} else {
warnNoRsync(o.ErrOut)
}
strategy, err := newTarStrategy(f, cmd, o)
if err != nil {
return nil, err
}
strategies = append(strategies, strategy)
return strategies, nil
case "rsync":
return newRsyncStrategy(f, cmd, o)
case "rsync-daemon":
return newRsyncDaemonStrategy(f, cmd, o)
case "tar":
return newTarStrategy(f, cmd, o)
default:
return nil, fmt.Errorf("unknown strategy: %s", name)
}
}
// Complete verifies command line arguments and loads data from the command environment
func (o *RsyncOptions) Complete(f kcmdutil.Factory, cmd *cobra.Command, args []string) error {
switch n := len(args); {
case n == 0:
cmd.Help()
fallthrough
case n < 2:
return kcmdutil.UsageErrorf(cmd, "SOURCE_DIR and POD:DESTINATION_DIR are required arguments")
case n > 2:
return kcmdutil.UsageErrorf(cmd, "only SOURCE_DIR and POD:DESTINATION_DIR should be specified as arguments")
}
var err error
namespace, _, err := f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return err
}
o.Namespace = namespace
// allow and parse resources specified in the <kind>/<name> format
parsedSourcePath, err := resolveResourceKindPath(f, args[0], namespace)
if err != nil {
return err
}
parsedDestPath, err := resolveResourceKindPath(f, args[1], namespace)
if err != nil {
return err
}
// Set main command arguments
o.Source, err = parsePathSpec(parsedSourcePath)
if err != nil {
return err
}
o.Destination, err = parsePathSpec(parsedDestPath)
if err != nil {
return err
}
fullCmdName := ""
cmdParent := cmd.Parent()
if cmdParent != nil {
fullCmdName = cmdParent.CommandPath()
}
if len(fullCmdName) > 0 && kcmdutil.IsSiblingCommandExists(cmd, "describe") {
o.SuggestedCmdUsage = fmt.Sprintf("Use '%s describe pod/%s -n %s' to see all of the containers in this pod.", fullCmdName, o.PodName(), o.Namespace)
}
o.Strategy, err = o.determineStrategy(f, cmd, o.StrategyName)
if err != nil {
return err
}
return nil
}
// Validate checks that SyncOptions has all necessary fields
func (o *RsyncOptions) Validate() error {
if o.Out == nil || o.ErrOut == nil {
return errors.New("output and error streams must be specified")
}
if o.Source == nil || o.Destination == nil {
return errors.New("source and destination must be specified")
}
if err := o.Source.Validate(); err != nil {
return err
}
if err := o.Destination.Validate(); err != nil {
return err
}
// If source and destination are both local or both remote throw an error
if o.Source.Local() == o.Destination.Local() {
return errors.New("rsync is only valid between a local directory and a pod directory; " +
"specify a pod directory as [PODNAME]:[DIR]")
}
if o.Destination.Local() && o.Watch {
return errors.New("\"--watch\" can only be used with a local source directory")
}
if err := o.Strategy.Validate(); err != nil {
return err
}
return nil
}
// RunRsync copies files from source to destination
func (o *RsyncOptions) RunRsync() error {
if err := o.Strategy.Copy(o.Source, o.Destination, o.Out, o.ErrOut); err != nil {
return err
}
if !o.Watch {
return nil
}
return o.WatchAndSync()
}
// WatchAndSync sets up a recursive filesystem watch on the sync path
// and invokes rsync each time the path changes.
func (o *RsyncOptions) WatchAndSync() error {
// these variables must be accessed while holding the changeLock
// mutex as they are shared between goroutines to communicate
// sync state/events.
var (
changeLock sync.Mutex
dirty bool
lastChange time.Time
watchError error
)
watcher, err := fsnotify.NewWatcher()
if err != nil {
return fmt.Errorf("error setting up filesystem watcher: %v", err)
}
defer watcher.Close()
go func() {
for {
select {
case event := <-watcher.Events:
changeLock.Lock()
glog.V(5).Infof("filesystem watch event: %s", event)
lastChange = time.Now()
dirty = true
if event.Op&fsnotify.Remove == fsnotify.Remove {
if e := watcher.Remove(event.Name); e != nil {
glog.V(5).Infof("error removing watch for %s: %v", event.Name, e)
}
} else {
if e := fsnotification.AddRecursiveWatch(watcher, event.Name); e != nil && watchError == nil {
watchError = e
}
}
changeLock.Unlock()
case err := <-watcher.Errors:
changeLock.Lock()
watchError = fmt.Errorf("error watching filesystem for changes: %v", err)
changeLock.Unlock()
}
}
}()
err = fsnotification.AddRecursiveWatch(watcher, o.Source.Path)
if err != nil {
return fmt.Errorf("error watching source path %s: %v", o.Source.Path, err)
}
delay := 2 * time.Second
ticker := time.NewTicker(delay)
defer ticker.Stop()
for {
changeLock.Lock()
if watchError != nil {
return watchError
}
// if a change happened more than 'delay' seconds ago, sync it now.
// if a change happened less than 'delay' seconds ago, sleep for 'delay' seconds
// and see if more changes happen, we don't want to sync when
// the filesystem is in the middle of changing due to a massive
// set of changes (such as a local build in progress).
if dirty && time.Now().After(lastChange.Add(delay)) {
glog.V(1).Info("Synchronizing filesystem changes...")
err = o.Strategy.Copy(o.Source, o.Destination, o.Out, o.ErrOut)
if err != nil {
return err
}
glog.V(1).Info("Done.")
dirty = false
}
changeLock.Unlock()
<-ticker.C
}
}
// PodName returns the name of the pod as specified in either the
// the source or destination arguments
func (o *RsyncOptions) PodName() string {
if len(o.Source.PodName) > 0 {
return o.Source.PodName
}
return o.Destination.PodName
}