-
Notifications
You must be signed in to change notification settings - Fork 1
/
tar.go
121 lines (91 loc) · 1.7 KB
/
tar.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
package etcdtar
import (
"archive/tar"
"bufio"
"fmt"
"github.com/coreos/go-etcd/etcd"
"io"
"io/ioutil"
"os"
"strings"
)
func ExportFromEtcdToTar(client *etcd.Client, host, path string) {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
dirs := make(map[string]bool)
dirs[path] = true
outer:
for {
for dir, _ := range dirs {
r, err := client.Get(dir, false, true)
if nil != err {
panic(err)
}
for _, n := range r.Node.Nodes {
if !n.Dir {
continue
}
if !dirs[n.Key] {
dirs[n.Key] = true
continue outer
}
}
}
break
}
content := make(map[string]string)
for dir, _ := range dirs {
r, err := client.Get(dir, false, true)
if nil != err {
panic(err)
}
for _, n := range r.Node.Nodes {
if n.Dir {
continue
}
content[n.Key[1:]] = n.Value
}
}
buf := bufio.NewWriter(os.Stdout)
defer buf.Flush()
tw := tar.NewWriter(buf)
for path, content := range content {
hdr := &tar.Header{
Name: path,
Mode: 0640,
Size: int64(len(content)),
}
if err := tw.WriteHeader(hdr); err != nil {
panic(err)
}
if _, err := tw.Write([]byte(content)); err != nil {
panic(err)
}
}
if err := tw.Close(); err != nil {
panic(err)
}
}
func ExportFromTarToEtcd(client *etcd.Client, host string) {
buf := bufio.NewReader(os.Stdin)
tr := tar.NewReader(buf)
for {
hdr, err := tr.Next()
if err == io.EOF {
// end of tar archive
break
}
if nil != err {
panic(err)
}
byteValue, err := ioutil.ReadAll(tr)
if nil != err {
panic(err)
}
strValue := string(byteValue)
fmt.Printf("k: %s; v: %s\n", hdr.Name, strValue)
r, err := client.Set(hdr.Name, strValue, 0)
fmt.Println(r, err)
}
}