-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhdfs.go
105 lines (95 loc) · 2.04 KB
/
hdfs.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
package Figo
import (
"github.com/colinmarc/hdfs"
"io"
"log"
"os"
)
type HDFSClient struct {
client *hdfs.Client
nameNode string
user string
}
func NewHDFSClient(nameNode, user string) HDFSClient {
return HDFSClient{
nameNode: nameNode,
user: user,
}
}
func (p *HDFSClient) open() error {
if p.client != nil {
return nil
}
os.Setenv("HADOOP_USER_NAME", p.user)
client, err := hdfs.New(p.nameNode)
p.client = client
return err
}
func (p *HDFSClient) close() error {
if p.client != nil {
err := p.client.Close()
p.client = nil
return err
}
return nil
}
func (p *HDFSClient) Write(fullPath string, data []byte) error {
p.open()
defer p.close()
fullPath = FilePathFormat(fullPath)
folderName := NewFilePath(fullPath).FolderName()
if err := p.client.MkdirAll(folderName, 0644); err != nil {
return err
}
w, err := p.client.Create(fullPath)
if err != nil {
return err
}
_, err = w.Write(data)
w.Close()
return err
}
func (p *HDFSClient) CreateFile(fullPath string) error {
p.open()
defer p.close()
fullPath = FilePathFormat(fullPath)
folderName := NewFilePath(fullPath).FolderName()
if err := p.client.MkdirAll(folderName, 0644); err != nil {
return err
}
return p.client.CreateEmptyFile(fullPath)
}
func (p *HDFSClient) AppendFile(fullPath string, data []byte) error {
p.open()
defer p.close()
fullPath = FilePathFormat(fullPath)
w, err := p.client.Append(fullPath)
if err != nil {
return err
}
defer w.Close()
_, err = w.Write(data)
return err
}
func (p *HDFSClient) WriteFile(fullPath string, file *os.File) error {
p.open()
defer p.close()
fullPath = FilePathFormat(fullPath)
folderName := NewFilePath(fullPath).FolderName()
if err := p.client.MkdirAll(folderName, 0644); err != nil {
return err
}
w, err := p.client.Create(fullPath)
defer w.Close()
if err != nil {
return err
}
n, err := io.Copy(w, file)
log.Println("@WriteFile ", n, " Bytes")
return err
}
func (p *HDFSClient) Read(fullPath string) ([]byte, error) {
p.open()
defer p.close()
return p.client.ReadFile(fullPath)
}