This repository has been archived by the owner on Oct 22, 2021. It is now read-only.
generated from beyondstorage/go-service-example
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
119 lines (98 loc) · 2.4 KB
/
utils.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
package hdfs
import (
"errors"
"fmt"
"os"
"path"
"path/filepath"
"github.com/beyondstorage/go-endpoint"
ps "github.com/beyondstorage/go-storage/v4/pairs"
"github.com/beyondstorage/go-storage/v4/services"
"github.com/beyondstorage/go-storage/v4/types"
"github.com/colinmarc/hdfs/v2"
)
// Storage is the example client.
type Storage struct {
hdfs *hdfs.Client
defaultPairs DefaultStoragePairs
features StorageFeatures
workDir string
types.UnimplementedStorager
types.UnimplementedDirer
types.UnimplementedMover
types.UnimplementedAppender
}
// String implements Storager.String
func (s *Storage) String() string {
return fmt.Sprintf("Storager hdfs {WorkDir: %s}", s.workDir)
}
// NewStorager will create Storager only.
func NewStorager(pairs ...types.Pair) (types.Storager, error) {
return newStorager(pairs...)
}
func newStorager(pairs ...types.Pair) (store *Storage, err error) {
defer func() {
if err != nil {
err = services.InitError{Op: "new_storager", Type: Type, Err: formatError(err), Pairs: pairs}
}
}()
opt, err := parsePairStorageNew(pairs)
if err != nil {
return nil, err
}
store = &Storage{
workDir: "/",
}
if opt.HasWorkDir {
store.workDir = opt.WorkDir
}
ep, err := endpoint.Parse(opt.Endpoint)
if err != nil {
return nil, err
}
var addr string
switch ep.Protocol() {
case endpoint.ProtocolTCP:
addr, _, _ = ep.TCP()
default:
return nil, services.PairUnsupportedError{Pair: ps.WithEndpoint(opt.Endpoint)}
}
store.hdfs, err = hdfs.New(addr)
if err != nil {
return nil, errors.New("hdfs address is not exist")
}
return store, nil
}
func formatError(err error) error {
if _, ok := err.(services.InternalError); ok {
return err
}
switch {
case errors.Is(err, os.ErrNotExist):
return fmt.Errorf("%w: %v", services.ErrObjectNotExist, err)
case errors.Is(err, os.ErrPermission):
return fmt.Errorf("%w: %v", services.ErrPermissionDenied, err)
default:
return fmt.Errorf("%w: %v", services.ErrUnexpected, err)
}
}
func (s *Storage) getAbsPath(fp string) string {
if filepath.IsAbs(fp) {
return fp
}
return path.Join(s.workDir, fp)
}
func (s *Storage) formatError(op string, err error, path ...string) error {
if err == nil {
return nil
}
return services.StorageError{
Op: op,
Err: formatError(err),
Storager: s,
Path: path,
}
}
func (s *Storage) newObject(done bool) *types.Object {
return types.NewObject(s, done)
}