forked from dreamans/syncd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
syncd.go
130 lines (111 loc) · 2.81 KB
/
syncd.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
// Copyright 2019 syncd Author. All Rights Reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package syncd
import (
"errors"
"encoding/base64"
"fmt"
"os"
"io"
"github.com/gin-gonic/gin"
"github.com/dreamans/syncd/util/golog"
"github.com/dreamans/syncd/util/gopath"
)
var (
App *syncd
)
const (
Version = "v2.0.0"
)
func init() {
App = newSyncd()
}
type syncd struct {
Gin *gin.Engine
DB *DB
Logger *golog.Logger
Mail *SendMail
LocalSpace string
LocalTmpSpace string
LocalTarSpace string
RemoteSpace string
CipherKey []byte
AppHost string
FeServeEnable int
config *Config
}
func newSyncd() *syncd {
return &syncd{
Gin: gin.New(),
}
}
func (s *syncd) Init(cfg *Config) error {
s.config = cfg
if err := s.registerOrm(); err != nil {
return err
}
s.registerMail()
s.registerLog()
if err := s.initEnv(); err != nil {
return err
}
return nil
}
func (s *syncd) Start() error {
return s.Gin.Run(s.config.Serve.Addr)
}
func (s *syncd) registerOrm() error {
s.DB = NewDatabase(s.config.Db)
return s.DB.Open()
}
func (s *syncd) registerLog() {
var loggerHandler io.Writer
switch s.config.Log.Path {
case "stdout":
loggerHandler = os.Stdout
case "stderr":
loggerHandler = os.Stderr
case "":
loggerHandler = os.Stdout
default:
loggerHandler = golog.NewFileHandler(s.config.Log.Path)
}
s.Logger = golog.New(loggerHandler)
}
func (s *syncd) registerMail() {
sendmail := &SendMail{
Enable: s.config.Mail.Enable,
Smtp: s.config.Mail.Smtp,
Port: s.config.Mail.Port,
User: s.config.Mail.User,
Pass: s.config.Mail.Pass,
}
s.Mail = NewSendMail(sendmail)
}
func (s *syncd) initEnv() error {
s.AppHost = s.config.Syncd.AppHost
s.FeServeEnable = s.config.Serve.FeServeEnable
s.LocalSpace = s.config.Syncd.LocalSpace
s.LocalTmpSpace = s.LocalSpace + "/tmp"
s.LocalTarSpace = s.LocalSpace + "/tar"
if err := gopath.CreatePath(s.LocalSpace); err != nil {
return err
}
if err := gopath.CreatePath(s.LocalTmpSpace); err != nil {
return err
}
if err := gopath.CreatePath(s.LocalTarSpace); err != nil {
return err
}
s.RemoteSpace = s.config.Syncd.RemoteSpace
if s.config.Syncd.Cipher == "" {
return errors.New("syncd config 'Cipher' not setting")
}
dec, err := base64.StdEncoding.DecodeString(s.config.Syncd.Cipher)
if err != nil {
return errors.New(fmt.Sprintf("decode Cipher failed, %s", err.Error()))
}
s.CipherKey = dec
return nil
}