Skip to content

Commit

Permalink
将存储引擎由文件替换成Mongo
Browse files Browse the repository at this point in the history
Commit by Andy.Zhang
Email: [email protected]
  • Loading branch information
andy-zhangtao committed May 15, 2017
1 parent 7985d7e commit 20e5c43
Show file tree
Hide file tree
Showing 14 changed files with 269 additions and 91 deletions.
2 changes: 1 addition & 1 deletion cmd/shadowsocks-server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func main() {
go ss.IsAboveRate()
// 用户数据持久化
go ss.Persistence()
go ss.PersistencePasswd()
// go ss.PersistencePasswd()

// 重新加载配置文件
go waitSignal(configFile, config)
Expand Down
2 changes: 1 addition & 1 deletion script/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ version
# build windows amd64 win64 local
# build windows 386 win32 local

build darwin amd64 mac64 server
#build darwin amd64 mac64 server
build linux amd64 linux64 server
# build linux 386 linux32 server
# build windows amd64 win64 server
Expand Down
113 changes: 75 additions & 38 deletions shadowsocks/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"log"

"github.com/andy-zhangtao/shadow-rest/shadowsocks/db"

"github.com/andy-zhangtao/shadow-rest/shadowsocks/util"

mgo "gopkg.in/mgo.v2"

// "log"
"os"
Expand Down Expand Up @@ -36,6 +43,8 @@ type Config struct {
var readTimeout time.Duration
var listenBakConf map[string]Listen

var mongoSession *mgo.Session

// GetServerArray 获取当前所有服务参数
func (config *Config) GetServerArray() []string {
// Specifying multiple servers in the "server" options is deprecated.
Expand Down Expand Up @@ -137,54 +146,82 @@ func UpdateConfig(old, new *Config) {

// ParseBackConfig 解析备份配置文件数据
func ParseBackConfig(config *Config) error {
con := os.Getenv("configdir")
if con == "" {
con = "/config"
if mongoSession == nil {
mongoSession = db.GetMongo()
}

// 解析口令配置文件
file, err := os.Open(con + "/passwd.json") // For read access.
var user []User
u := mongoSession.DB(os.Getenv(util.MONGODB)).C("user")
err := u.Find(nil).All(&user)
if err != nil {
return err
}
defer file.Close()

data, err := ioutil.ReadAll(file)
if err != nil {
return err
}

up := &UserPassBack{}
if err = json.Unmarshal(data, up); err != nil {
return err
}

pb := make(map[string]string)
for _, b := range up.Upb {
pb[b.Port] = b.Password
}

config.PortPassword = pb

// 解析网络备份文件
file, err = os.Open(con + "/user.json") // For read access.
if err != nil {
return err
}
listenBakConf = make(map[string]Listen)

data, err = ioutil.ReadAll(file)
if err != nil {
return err
for _, us := range user {
log.Println(us)
pb[us.ID] = us.Password
listenBakConf[us.ID] = Listen{
Port: us.ID,
Rate: us.Rate,
ExpiryDate: us.Expriy,
RateLimit: us.RateLimit,
Email: us.Email,
}
}

lb := &ListenBak{}
if err = json.Unmarshal(data, lb); err != nil {
return err
}
config.PortPassword = pb

listenBakConf = make(map[string]Listen)
for _, l := range lb.Lb {
listenBakConf[l.Port] = l
}
// con := os.Getenv("configdir")
// if con == "" {
// con = "/config"
// }

// // 解析口令配置文件
// file, err := os.Open(con + "/passwd.json") // For read access.
// if err != nil {
// return err
// }
// defer file.Close()

// data, err := ioutil.ReadAll(file)
// if err != nil {
// return err
// }

// up := &UserPassBack{}
// if err = json.Unmarshal(data, up); err != nil {
// return err
// }

// pb := make(map[string]string)
// for _, b := range up.Upb {
// pb[b.Port] = b.Password
// }

// config.PortPassword = pb

// // 解析网络备份文件
// file, err = os.Open(con + "/user.json") // For read access.
// if err != nil {
// return err
// }

// data, err = ioutil.ReadAll(file)
// if err != nil {
// return err
// }

// lb := &ListenBak{}
// if err = json.Unmarshal(data, lb); err != nil {
// return err
// }

// listenBakConf = make(map[string]Listen)
// for _, l := range lb.Lb {
// listenBakConf[l.Port] = l
// }
return nil
}
53 changes: 53 additions & 0 deletions shadowsocks/db/mongo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package db

import (
"fmt"
"log"
"os"
"time"

"github.com/andy-zhangtao/shadow-rest/shadowsocks/util"

mgo "gopkg.in/mgo.v2"
)

var Session *mgo.Session

func init() {
log.Println("==================")
var err error
if Session == nil {
login := &mgo.DialInfo{
Addrs: []string{os.Getenv(util.MONGOURL)},
Timeout: 3600 * time.Second,
Database: os.Getenv(util.MONGODB),
Username: os.Getenv(util.USERNAME),
Password: os.Getenv(util.PASSWORD),
}

// log.Printf("Connectting mongodb,env: [%v] host:[%s] db:[%s] \n", login.Addrs, login.Database, os.Environ())
Session, err = mgo.DialWithInfo(login)
if err != nil {
fmt.Println(err.Error())
}

if err := Session.Ping(); err == nil {
log.Printf("MONGO CONNECT SUCCESS! [%s]\n", Session.LiveServers())
} else {
log.Printf("MONGO CONNECT FAILED!! [%s] Error Info [%s]\n", os.Getenv(util.MONGOURL), err.Error())
}

}
}

func GetMongo() *mgo.Session {

Session.Refresh()
session := Session.Clone()
if session == nil {
fmt.Println("MONGODB SESSION IS NIL!!")
return nil
}

return session
}
2 changes: 1 addition & 1 deletion shadowsocks/expiryDate.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func IsExpiry() {
l.listen.Close()
delete(listenMap, p)
KillUserPass(l.Port)
SendEmail(l.Port+" Will be closed. ExpiryDate:"+l.ExpiryDate, l.Email)
SendEmail(l.Port+" 将会被关闭. 过期时间为:"+l.ExpiryDate, l.Email)
}
}
}
Expand Down
16 changes: 12 additions & 4 deletions shadowsocks/handler/rateHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,29 @@ import (

// GetInfoHandler 获取当前所有的端口信息
func GetInfoHandler(w http.ResponseWriter, r *http.Request) {
keys := ss.GetRate()

keys, err := ss.GetRate()
if err != nil {
Sandstorm.HTTPError(w, err.Error(), http.StatusInternalServerError)
return
}
content, _ := json.Marshal(keys)

Sandstorm.HTTPSuccess(w, string(content))
}

// GetRateHandler 获取当前所有端口流量数据
func GetRateHandler(w http.ResponseWriter, r *http.Request) {
keys := ss.GetRate()
keys, err := ss.GetRate()
if err != nil {
Sandstorm.HTTPError(w, err.Error(), http.StatusInternalServerError)
return
}

rate := make([]*ss.Rate, len(keys))

for i, k := range keys {
r := &ss.Rate{
Port: k.Port,
Port: k.ID,
Rate: ss.ConvertRate(k.Rate),
}
rate[i] = r
Expand Down
2 changes: 1 addition & 1 deletion shadowsocks/handler/userHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
return
}

email := `<h1>Your account info is belowing:</h1> <h3> <br/> encrypt:aes-256-cfb <br/><br/> ` + conf.Port + `:` + conf.Password + ` <br/><br/> Rate:` + strconv.Itoa(conf.Rate) + `KB <br/><br/> Expriy:` + conf.Expriy + `D <br/><br/> <h2/> `
email := `<h1>创建成功,用户信息如下:</h1> <h3> <br/> 加密方式:aes-256-cfb <br/><br/> ` + conf.Port + `:` + conf.Password + ` <br/><br/> 流量限制:` + strconv.Itoa(conf.Rate) + `KB <br/><br/> 过期时间:` + conf.Expriy + `D <br/><br/> <h2/> `
err = ss.SendEmail(email, conf.Email)
if err != nil {
Sandstorm.HTTPSuccess(w, conf.Port+":"+conf.Password+" "+err.Error())
Expand Down
4 changes: 2 additions & 2 deletions shadowsocks/handler/versionHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
// GetVersion 获取当前版本信息
func GetVersion(w http.ResponseWriter, r *http.Request) {

dv := "Dev Version: " + "r52M 407787e"
rv := " Release Version: 0.1"
dv := "Dev Version: " + "r53M 7985d7e"
rv := " Release Version: 0.2"
Sandstorm.HTTPSuccess(w, dv+rv)
}
2 changes: 1 addition & 1 deletion shadowsocks/handler/versionHandler.go.template
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ import (
func GetVersion(w http.ResponseWriter, r *http.Request) {

dv := "Dev Version: " + "$GIT"
rv := " Release Version: 0.1"
rv := " Release Version: 0.2"
Sandstorm.HTTPSuccess(w, dv+rv)
}
30 changes: 24 additions & 6 deletions shadowsocks/listen.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@ package shadowsocks
import (
"errors"
"net"
"os"

"github.com/andy-zhangtao/shadow-rest/shadowsocks/db"

"github.com/andy-zhangtao/shadow-rest/configure"
"github.com/andy-zhangtao/shadow-rest/shadowsocks/util"
)

/**
Expand Down Expand Up @@ -117,14 +121,28 @@ func GetPortRate(port string) *Listen {
}

// GetRate 获取所有端口流量
func GetRate() []*Listen {
r := make([]*Listen, 0, len(listenMap))
for p := range listenMap {
l := listenMap[p]
r = append(r, &l)
func GetRate() ([]User, error) {
if mongoSession == nil {
mongoSession = db.GetMongo()
}

return r
u := mongoSession.DB(os.Getenv(util.MONGODB)).C("user")

var user []User

err := u.Find(nil).Sort("+id").All(&user)
if err != nil {
return nil, err
}

return user, nil
// r := make([]*Listen, 0, len(listenMap))
// for p := range listenMap {
// l := listenMap[p]
// r = append(r, &l)
// }

// return r
}

// ClearPortRate 端口流量清零
Expand Down
7 changes: 3 additions & 4 deletions shadowsocks/rate.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@ package shadowsocks
import (
"errors"
"fmt"
"log"
"strconv"
"strings"
"time"

"github.com/andy-zhangtao/golog"

"github.com/andy-zhangtao/shadow-rest/configure"
)

Expand Down Expand Up @@ -116,11 +115,11 @@ func IsAboveRate() {
// 0 表示无限制
if l.RateLimit != 0 {
if l.Rate >= l.RateLimit {
golog.Debug(l.Port, "流量超限需要被关闭")
log.Println(l.Port, "流量超限需要被关闭")
l.listen.Close()
delete(listenMap, p)
KillUserPass(l.Port)
golog.Debug(l.Port, "被关闭", l.Rate, l.RateLimit)
log.Println(l.Port, "被关闭", l.Rate, l.RateLimit)
SendEmail(l.Port+" Will be closed. Curreny Rate:"+strconv.Itoa(l.Rate)+" Max Rate:"+strconv.Itoa(l.RateLimit), l.Email)
}
}
Expand Down
Loading

0 comments on commit 20e5c43

Please sign in to comment.