Skip to content
Snippets Groups Projects
Commit a86337d3 authored by AlexStocks's avatar AlexStocks
Browse files

Add: jsonrpc 2.0 server

parent 388d0857
No related branches found
No related tags found
No related merge requests found
Showing
with 937 additions and 136 deletions
......@@ -14,7 +14,7 @@ Apache License, Version 2.0
+ 4 Registry: ZooKeeper(√), Etcd(X), Redis(X)
+ 5 Strategy: Failover(√), Failfast(√)
+ 6 Load Balance: Random(√), RoundRobin(√)
+ 7 Role: Consumer(√), Provider(X)
+ 7 Role: Consumer(√), Provider()
## Code Example
......
......@@ -43,10 +43,11 @@ func main() {
time.Sleep(3e9)
gxlog.CInfo("\n\n\nstart to test jsonrpc")
for i := 0; i < 100; i++ {
testJsonrpc("A003")
time.Sleep(1e9)
}
testJsonrpc("A003")
time.Sleep(3e9)
gxlog.CInfo("\n\n\nstart to test jsonrpc illegal method")
testJsonrpcIllegalMethod("A003")
initSignal()
}
......
......@@ -2,6 +2,7 @@ package main
import (
"fmt"
"io/ioutil"
"os"
"path"
"time"
......@@ -10,7 +11,8 @@ import (
import (
"github.com/AlexStocks/goext/log"
log "github.com/AlexStocks/log4go"
config "github.com/koding/multiconfig"
jerrors "github.com/juju/errors"
yaml "gopkg.in/yaml.v2"
)
import (
......@@ -30,25 +32,25 @@ type (
// Client holds supported types by the multiconfig package
ClientConfig struct {
// pprof
Pprof_Enabled bool `default:"false"`
Pprof_Port int `default:"10086"`
Pprof_Enabled bool `default:"false" yaml:"pprof_enabled" json:"pprof_enabled,omitempty"`
Pprof_Port int `default:"10086" yaml:"pprof_port" json:"pprof_port,omitempty"`
// client
Connect_Timeout string `default:"100ms"`
Connect_Timeout string `default:"100ms" yaml:"connect_timeout" json:"connect_timeout,omitempty"`
connectTimeout time.Duration
Request_Timeout string `default:"5s"` // 500ms, 1m
Request_Timeout string `yaml:"request_timeout" default:"5s" json:"request_timeout,omitempty"` // 500ms, 1m
requestTimeout time.Duration
// codec & selector & transport & registry
Selector string `default:"cache"`
Selector_TTL string `default:"10m"`
Registry string `default:"zookeeper"`
Selector string `default:"cache" yaml:"selector" json:"selector,omitempty"`
Selector_TTL string `default:"10m" yaml:"selector_ttl" json:"selector_ttl,omitempty"`
Registry string `default:"zookeeper" yaml:"registry" json:"registry,omitempty"`
// application
Application_Config registry.ApplicationConfig
Registry_Config registry.RegistryConfig
Application_Config registry.ApplicationConfig `yaml:"application_config" json:"application_config,omitempty"`
Registry_Config registry.RegistryConfig `yaml:"registry_config" json:"registry_config,omitempty"`
// 一个客户端只允许使用一个service的其中一个group和其中一个version
Service_List []registry.ServiceConfig
Service_List []registry.ServiceConfig `yaml:"service_list" json:"service_list,omitempty"`
}
)
......@@ -63,12 +65,22 @@ func initClientConfig() error {
panic(fmt.Sprintf("application configure file name is nil"))
return nil // I know it is of no usage. Just Err Protection.
}
if path.Ext(confFile) != ".toml" {
panic(fmt.Sprintf("application configure file name{%v} suffix must be .toml", confFile))
if path.Ext(confFile) != ".yml" {
panic(fmt.Sprintf("application configure file name{%v} suffix must be .yml", confFile))
return nil
}
clientConfig = new(ClientConfig)
config.MustLoadWithPath(confFile, clientConfig)
confFileStream, err := ioutil.ReadFile(confFile)
if err != nil {
panic(fmt.Sprintf("ioutil.ReadFile(file:%s) = error:%s", confFile, jerrors.ErrorStack(err)))
return nil
}
err = yaml.Unmarshal(confFileStream, clientConfig)
if err != nil {
panic(fmt.Sprintf("yaml.Unmarshal() = error:%s", jerrors.ErrorStack(err)))
return nil
}
gxlog.CInfo("config{%#v}\n", clientConfig)
// log
......
......@@ -88,3 +88,74 @@ func testJsonrpc(userKey string) {
log.Info("response result:%s", user)
// gxlog.CInfo("response result:%s", user)
}
func testJsonrpcIllegalMethod(userKey string) {
var (
err error
service string
method string
serviceIdx int
user *JsonRPCUser
ctx context.Context
conf registry.ServiceConfig
req jsonrpc.Request
serviceURL *registry.ServiceURL
clt *jsonrpc.HTTPClient
)
clt = jsonrpc.NewHTTPClient(
&jsonrpc.HTTPOptions{
HandshakeTimeout: clientConfig.connectTimeout,
HTTPTimeout: clientConfig.requestTimeout,
},
)
serviceIdx = -1
service = "com.ikurento.user.UserProvider"
for i := range clientConfig.Service_List {
if clientConfig.Service_List[i].Service == service && clientConfig.Service_List[i].Protocol == public.CODECTYPE_JSONRPC.String() {
serviceIdx = i
break
}
}
if serviceIdx == -1 {
panic(fmt.Sprintf("can not find service in config service list:%#v", clientConfig.Service_List))
}
// Create request
method = string("GetUser1")
// gxlog.CInfo("jsonrpc selected service %#v", clientConfig.Service_List[serviceIdx])
conf = registry.ServiceConfig{
Group: clientConfig.Service_List[serviceIdx].Group,
Protocol: public.CodecType(public.CODECTYPE_JSONRPC).String(),
Version: clientConfig.Service_List[serviceIdx].Version,
Service: clientConfig.Service_List[serviceIdx].Service,
}
// Attention the last parameter : []UserKey{userKey}
req = clt.NewRequest(conf, method, []string{userKey})
serviceURL, err = clientRegistry.Filter(req.ServiceConfig(), 1)
if err != nil {
log.Error("registry.Filter(conf:%#v) = error:%s", req.ServiceConfig(), jerrors.ErrorStack(err))
// gxlog.CError("registry.Filter(conf:%#v) = error:%s", req.ServiceConfig(), jerrors.ErrorStack(err))
return
}
log.Debug("got serviceURL: %s", serviceURL)
// Set arbitrary headers in context
ctx = context.WithValue(context.Background(), public.DUBBOGO_CTX_KEY, map[string]string{
"X-Proxy-Id": "dubbogo",
"X-Services": service,
"X-Method": method,
})
user = new(JsonRPCUser)
// Call service
if err = clt.Call(ctx, *serviceURL, req, user); err != nil {
log.Error("client.Call() return error:%+v", jerrors.ErrorStack(err))
// gxlog.CError("client.Call() return error:%+v", jerrors.ErrorStack(err))
return
}
log.Info("response result:%s", user)
// gxlog.CInfo("response result:%s", user)
}
......@@ -13,5 +13,5 @@ export TARGET_EXEC_NAME="user_info_client"
# BUILD_PACKAGE="dubbogo-examples/user-info/client/app"
export BUILD_PACKAGE="app"
export TARGET_CONF_FILE="conf/client.toml"
export TARGET_CONF_FILE="conf/client.yml"
export TARGET_LOG_CONF_FILE="conf/log.xml"
# dubbo client toml configure file
# pprof
Pprof_Enabled = true
Pprof_Port = 10086
# client
Request_Timeout = "3500ms"
NET_IO_Timeout = "2s"
Retries = 1
# connect timeout
Connect_Timeout = "100ms"
Selector = "cache"
Selector_TTL = "10m"
Registry = "zookeeper"
# application config
[Application_Config]
Organization = "ikurento.com"
Name = "Pusher"
Module = "dubbogo user-info client"
Version = "0.0.1"
Owner = "ZX"
[Registry_Config]
# You can indent as you please. Tabs or spaces. TOML don't care.
Address = ["127.0.0.1:2181"]
Timeout = 3
[[Service_List]]
Protocol = "jsonrpc"
Service = "com.ikurento.user.UserProvider"
# dubbo client yaml configure file
# pprof
pprof_enabled : true
pprof_port : 10086
# client
request_timeout : "3500ms"
net_io_timeout : "2s"
retries : 1
# connect timeout
connect_timeout : "100ms"
selector : "cache"
selector_ttl : "10m"
registry : "zookeeper"
# application config
application_config:
organization : "ikurento.com"
name : "BDTService"
module : "dubbogo user-info client"
version : "0.0.1"
owner : "ZX"
registry_config:
timeout : 3
address:
- "127.0.0.1:2181"
service_list:
-
protocol : "jsonrpc"
service : "com.ikurento.user.UserProvider"
# dubbo client toml configure file
# pprof
Pprof_Enabled = true
Pprof_Port = 10086
# client
Request_Timeout = "350ms"
NET_IO_Timeout = "2s"
Retries = 2
# 连接池中每个地址的最大连接数
Pool_Size = 32
# 连接池中每个连接的有效时间
Pool_TTL = "10m"
# connect timeout
Connect_Timeout = "100ms"
Selector = "cache"
Selector_TTL = "10m"
Registry = "zookeeper"
# application config
[Application_Config]
Organization = "ikurento.com"
Name = "Pusher"
Module = "dubbogo user-info client"
Version = "0.0.1"
Owner = "ZX"
[Registry_Config]
# You can indent as you please. Tabs or spaces. TOML don't care.
Address = ["192.168.35.3:2181"]
Timeout = 3
[[Service_List]]
Protocol = "jsonrpc"
Service = "com.ikurento.user.UserProvider"
[[Service_List]]
Protocol = "dubbo"
Service = "com.ikurento.user.UserProvider"
Version = "2.0"
# dubbo client yaml configure file
# pprof
pprof_enabled : true
pprof_port : 10086
# client
request_timeout : "3500ms"
net_io_timeout : "2s"
retries : 1
# connect timeout
connect_timeout : "100ms"
selector : "cache"
selector_ttl : "10m"
registry : "zookeeper"
# application config
application_config:
organization : "ikurento.com"
name : "BDTService"
module : "dubbogo user-info client"
version : "0.0.1"
owner : "ZX"
registry_config:
timeout : 3
address:
- "127.0.0.1:2181"
service_list:
-
protocol : "jsonrpc"
service : "com.ikurento.user.UserProvider"
# dubbo client toml configure file
# pprof
Pprof_Enabled = true
Pprof_Port = 10086
# client
Request_Timeout = "350ms"
NET_IO_Timeout = "2s"
Retries = 2
# 连接池中每个地址的最大连接数
Pool_Size = 32
# 连接池中每个连接的有效时间
Pool_TTL = "10m"
# connect timeout
Connect_Timeout = "100ms"
Selector = "cache"
Selector_TTL = "10m"
Registry = "zookeeper"
# application config
[Application_Config]
Organization = "ikurento.com"
Name = "Pusher"
Module = "dubbogo user-info client"
Version = "0.0.1"
Owner = "ZX"
[Registry_Config]
# You can indent as you please. Tabs or spaces. TOML don't care.
Address = ["192.168.35.3:2181"]
Timeout = 3
[[Service_List]]
Protocol = "jsonrpc"
Service = "com.ikurento.user.UserProvider"
[[Service_List]]
Protocol = "dubbo"
Service = "com.ikurento.user.UserProvider"
Version = "2.0"
# dubbo client yaml configure file
# pprof
pprof_enabled : true
pprof_port : 10086
# client
request_timeout : "3500ms"
net_io_timeout : "2s"
retries : 1
# connect timeout
connect_timeout : "100ms"
selector : "cache"
selector_ttl : "10m"
registry : "zookeeper"
# application config
application_config:
organization : "ikurento.com"
name : "BDTService"
module : "dubbogo user-info client"
version : "0.0.1"
owner : "ZX"
registry_config:
timeout : 3
address:
- "127.0.0.1:2181"
service_list:
-
protocol : "jsonrpc"
service : "com.ikurento.user.UserProvider"
/******************************************************
# DESC : env var & configure
# AUTHOR : Alex Stocks
# VERSION : 1.0
# LICENCE : Apache License 2.0
# EMAIL : alexstocks@foxmail.com
# MOD : 2016-07-21 16:41
# FILE : config.go
******************************************************/
package main
import (
"fmt"
"io/ioutil"
"os"
"path"
"time"
"github.com/AlexStocks/goext/log"
log "github.com/AlexStocks/log4go"
jerrors "github.com/juju/errors"
"github.com/dubbo/dubbo-go/registry"
yaml "gopkg.in/yaml.v2"
)
const (
APP_CONF_FILE string = "APP_CONF_FILE"
APP_LOG_CONF_FILE string = "APP_LOG_CONF_FILE"
)
var (
conf *ServerConfig
)
type (
ServerConfig struct {
// pprof
Pprof_Enabled bool `default:"false" yaml:"pprof_enabled" json:"pprof_enabled,omitempty"`
Pprof_Port int `default:"10086" yaml:"pprof_port" json:"pprof_port,omitempty"`
// transport & registry
Transport string `default:"http" yaml:"transport" json:"transport,omitempty"`
NetTimeout string `default:"100ms" yaml:"net_timeout" json:"net_timeout,omitempty"` // in ms
netTimeout time.Duration
// application
Application_Config registry.ApplicationConfig `yaml:"application_config" json:"application_config,omitempty"`
// Registry_Address string `default:"192.168.35.3:2181"`
Registry_Config registry.RegistryConfig `yaml:"registry_config" json:"registry_config,omitempty"`
Service_List []registry.ServiceConfig `yaml:"service_list" json:"service_list,omitempty"`
Server_List []registry.ServerConfig `yaml:"server_list" json:"server_list,omitempty"`
}
)
func initServerConf() *ServerConfig {
var (
err error
confFile string
)
confFile = os.Getenv(APP_CONF_FILE)
if confFile == "" {
panic(fmt.Sprintf("application configure file name is nil"))
return nil
}
if path.Ext(confFile) != ".yml" {
panic(fmt.Sprintf("application configure file name{%v} suffix must be .yml", confFile))
return nil
}
conf = &ServerConfig{}
confFileStream, err := ioutil.ReadFile(confFile)
if err != nil {
panic(fmt.Sprintf("ioutil.ReadFile(file:%s) = error:%s", confFile, jerrors.ErrorStack(err)))
return nil
}
err = yaml.Unmarshal(confFileStream, conf)
if err != nil {
panic(fmt.Sprintf("yaml.Unmarshal() = error:%s", jerrors.ErrorStack(err)))
return nil
}
if conf.netTimeout, err = time.ParseDuration(conf.NetTimeout); err != nil {
panic(fmt.Sprintf("time.ParseDuration(NetTimeout:%#v) = error:%s", conf.NetTimeout, err))
return nil
}
gxlog.CInfo("config{%#v}\n", conf)
return conf
}
func configInit() error {
var (
confFile string
)
initServerConf()
confFile = os.Getenv(APP_LOG_CONF_FILE)
if confFile == "" {
panic(fmt.Sprintf("log configure file name is nil"))
return nil
}
if path.Ext(confFile) != ".xml" {
panic(fmt.Sprintf("log configure file name{%v} suffix must be .xml", confFile))
return nil
}
log.LoadConfiguration(confFile)
return nil
}
/******************************************************
# DESC : provider example
# AUTHOR : Alex Stocks
# VERSION : 1.0
# LICENCE : Apache License 2.0
# EMAIL : alexstocks@foxmail.com
# MOD : 2016-07-21 16:41
# FILE : server.go
******************************************************/
package main
import (
"fmt"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"strconv"
"syscall"
// "github.com/AlexStocks/gocolor"
"github.com/AlexStocks/goext/net"
"github.com/AlexStocks/goext/time"
log "github.com/AlexStocks/log4go"
"github.com/dubbo/dubbo-go/jsonrpc"
"github.com/dubbo/dubbo-go/registry"
jerrors "github.com/juju/errors"
)
var (
survivalTimeout int = 3e9
servo *jsonrpc.Server
)
func main() {
var (
err error
)
err = configInit()
if err != nil {
log.Error("configInit() = error{%#v}", err)
return
}
initProfiling()
servo = initServer()
err = servo.Handle(&UserProvider{})
if err != nil {
panic(err)
return
}
servo.Start()
initSignal()
}
func initServer() *jsonrpc.Server {
var (
err error
serverRegistry *registry.ZkProviderRegistry
srv *jsonrpc.Server
)
if conf == nil {
panic(fmt.Sprintf("conf is nil"))
return nil
}
// registry
serverRegistry, err = registry.NewZkProviderRegistry(
registry.ApplicationConf(conf.Application_Config),
registry.RegistryConf(conf.Registry_Config),
registry.BalanceMode(registry.SM_RoundRobin),
registry.ServiceTTL(conf.netTimeout),
)
if err != nil || serverRegistry == nil {
panic(fmt.Sprintf("fail to init registry.Registy, err:%s", jerrors.ErrorStack(err)))
return nil
}
// provider
srv = jsonrpc.NewServer(
jsonrpc.Registry(serverRegistry),
jsonrpc.ConfList(conf.Server_List),
jsonrpc.ServiceConfList(conf.Service_List),
)
return srv
}
func uninitServer() {
if servo != nil {
servo.Stop()
}
log.Close()
}
func initProfiling() {
if !conf.Pprof_Enabled {
return
}
const (
PprofPath = "/debug/pprof/"
)
var (
err error
ip string
addr string
)
ip, err = gxnet.GetLocalIP()
if err != nil {
panic("cat not get local ip!")
}
addr = ip + ":" + strconv.Itoa(conf.Pprof_Port)
log.Info("App Profiling startup on address{%v}", addr+PprofPath)
go func() {
log.Info(http.ListenAndServe(addr, nil))
}()
}
func initSignal() {
signals := make(chan os.Signal, 1)
// It is not possible to block SIGKILL or syscall.SIGSTOP
signal.Notify(signals, os.Interrupt, os.Kill, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
sig := <-signals
log.Info("get signal %s", sig.String())
switch sig {
case syscall.SIGHUP:
// reload()
default:
go gxtime.Future(survivalTimeout, func() {
log.Warn("app exit now by force...")
os.Exit(1)
})
// 要么fastFailTimeout时间内执行完毕下面的逻辑然后程序退出,要么执行上面的超时函数程序强行退出
uninitServer()
fmt.Println("provider app exit now...")
return
}
}
}
/*****************************************************
# DESC : UserProvider Service
# AUTHOR : Alex Stocks
# VERSION : 1.0
# LICENCE : Apache License 2.0
# EMAIL : alexstocks@foxmail.com
# MOD : 2016-07-21 19:22
# FILE : user.go
******************************************************/
package main
import (
// "encoding/json"
"context"
"fmt"
"time"
)
import (
"github.com/AlexStocks/goext/log"
"github.com/AlexStocks/goext/time"
)
type Gender int
const (
MAN = iota
WOMAN
)
var genderStrings = [...]string{
"MAN",
"WOMAN",
}
func (g Gender) String() string {
return genderStrings[g]
}
type (
User struct {
Id string `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
sex Gender
Birth int `json:"time"`
Sex string `json:"sex"`
}
UserId struct {
Id string
}
UserProvider struct {
user map[string]User
}
)
var (
DefaultUser = User{
Id: "0", Name: "Alex Stocks", Age: 31,
// Birth: int(time.Date(1985, time.November, 10, 23, 0, 0, 0, time.UTC).Unix()),
Birth: gxtime.YMD(1985, 11, 24, 15, 15, 0),
sex: Gender(MAN),
}
userMap = UserProvider{user: make(map[string]User)}
)
func init() {
DefaultUser.Sex = DefaultUser.sex.String()
userMap.user["A000"] = DefaultUser
userMap.user["A001"] = User{Id: "001", Name: "ZhangSheng", Age: 18, sex: MAN}
userMap.user["A002"] = User{Id: "002", Name: "Lily", Age: 20, sex: WOMAN}
userMap.user["A003"] = User{Id: "113", Name: "Moorse", Age: 30, sex: MAN}
for k, v := range userMap.user {
v.Birth = int(time.Now().AddDate(-1*v.Age, 0, 0).Unix())
v.Sex = userMap.user[k].sex.String()
userMap.user[k] = v
}
}
/*
// you can define your json unmarshal function here
func (this *UserId) UnmarshalJSON(value []byte) error {
this.Id = string(value)
this.Id = strings.TrimPrefix(this.Id, "\"")
this.Id = strings.TrimSuffix(this.Id, `"`)
return nil
}
*/
func (this *UserProvider) getUser(userId string) (*User, error) {
if user, ok := userMap.user[userId]; ok {
return &user, nil
}
return nil, fmt.Errorf("invalid user id:%s", userId)
}
/*
// can not work
func (this *UserProvider) GetUser(ctx context.Context, req *UserId, rsp *User) error {
var (
err error
user *User
)
user, err = this.getUser(req.Id)
if err == nil {
*rsp = *user
gxlog.CInfo("rsp:%#v", rsp)
// s, _ := json.Marshal(rsp)
// fmt.Println(string(s))
// s, _ = json.Marshal(*rsp)
// fmt.Println(string(s))
}
return err
}
*/
/*
// work
func (this *UserProvider) GetUser(ctx context.Context, req *string, rsp *User) error {
var (
err error
user *User
)
gxlog.CInfo("req:%#v", *req)
user, err = this.getUser(*req)
if err == nil {
*rsp = *user
gxlog.CInfo("rsp:%#v", rsp)
// s, _ := json.Marshal(rsp)
// fmt.Println(string(s))
// s, _ = json.Marshal(*rsp)
// fmt.Println(string(s))
}
return err
}
*/
func (this *UserProvider) GetUser(ctx context.Context, req []string, rsp *User) error {
var (
err error
user *User
)
gxlog.CInfo("req:%#v", req)
user, err = this.getUser(req[0])
if err == nil {
*rsp = *user
gxlog.CInfo("rsp:%#v", rsp)
// s, _ := json.Marshal(rsp)
// fmt.Println(string(s))
// s, _ = json.Marshal(*rsp)
// fmt.Println(string(s))
}
return err
}
func (this *UserProvider) Service() string {
return "com.ikurento.user.UserProvider"
}
func (this *UserProvider) Version() string {
return ""
}
/******************************************************
# DESC : client version
# AUTHOR : Alex Stocks
# VERSION : 1.0
# LICENCE : Apache License 2.0
# EMAIL : alexstocks@foxmail.com
# MOD : 2016-07-21 16:41
# FILE : version.go
******************************************************/
package main
var (
Version string = "0.2.0"
)
#!/usr/bin/env bash
# ******************************************************
# DESC : dubbogo app devops script
# AUTHOR : Alex Stocks
# VERSION : 1.0
# LICENCE : Apache License 2.0
# EMAIL : alexstocks@foxmail.com
# MOD : 2016-05-13 02:01
# FILE : load.sh
# ******************************************************
APP_NAME="APPLICATION_NAME"
APP_ARGS=""
PROJECT_HOME=""
OS_NAME=`uname`
if [[ ${OS_NAME} != "Windows" ]]; then
PROJECT_HOME=`pwd`
PROJECT_HOME=${PROJECT_HOME}"/"
fi
export APP_CONF_FILE=${PROJECT_HOME}"TARGET_CONF_FILE"
export APP_LOG_CONF_FILE=${PROJECT_HOME}"TARGET_LOG_CONF_FILE"
usage() {
echo "Usage: $0 start"
echo " $0 stop"
echo " $0 term"
echo " $0 restart"
echo " $0 list"
echo " $0 monitor"
echo " $0 crontab"
exit
}
start() {
APP_LOG_PATH="${PROJECT_HOME}logs/"
mkdir -p ${APP_LOG_PATH}
APP_BIN=${PROJECT_HOME}sbin/${APP_NAME}
chmod u+x ${APP_BIN}
# CMD="nohup ${APP_BIN} ${APP_ARGS} >>${APP_NAME}.nohup.out 2>&1 &"
CMD="${APP_BIN}"
eval ${CMD}
PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'`
if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then
PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'`
fi
CUR=`date +%FT%T`
if [ "${PID}" != "" ]; then
for p in ${PID}
do
echo "start ${APP_NAME} ( pid =" ${p} ") at " ${CUR}
done
fi
}
stop() {
PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'`
if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then
PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'`
fi
if [ "${PID}" != "" ];
then
for ps in ${PID}
do
echo "kill -SIGINT ${APP_NAME} ( pid =" ${ps} ")"
kill -2 ${ps}
done
fi
}
term() {
PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $2}'`
if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then
PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{print $1}'`
fi
if [ "${PID}" != "" ];
then
for ps in ${PID}
do
echo "kill -9 ${APP_NAME} ( pid =" ${ps} ")"
kill -9 ${ps}
done
fi
}
list() {
PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{printf("%s,%s,%s,%s\n", $1, $2, $9, $10)}'`
if [[ ${OS_NAME} != "Linux" && ${OS_NAME} != "Darwin" ]]; then
PID=`ps aux | grep -w ${APP_NAME} | grep -v grep | awk '{printf("%s,%s,%s,%s,%s\n", $1, $4, $6, $7, $8)}'`
fi
if [ "${PID}" != "" ]; then
echo "list ${APP_NAME}"
if [[ ${OS_NAME} == "Linux" || ${OS_NAME} == "Darwin" ]]; then
echo "index: user, pid, start, duration"
else
echo "index: PID, WINPID, UID, STIME, COMMAND"
fi
idx=0
for ps in ${PID}
do
echo "${idx}: ${ps}"
((idx ++))
done
fi
}
opt=$1
case C"$opt" in
Cstart)
start
;;
Cstop)
stop
;;
Cterm)
term
;;
Crestart)
term
start
;;
Clist)
list
;;
C*)
usage
;;
esac
# dubbogo application configure script
# ******************************************************
# DESC : application environment variable
# AUTHOR : Alex Stocks
# VERSION : 1.0
# LICENCE : Apache License 2.0
# EMAIL : alexstocks@foxmail.com
# MOD : 2016-07-12 16:29
# FILE : app.properties
# ******************************************************
TARGET_EXEC_NAME="user_info_server"
# BUILD_PACKAGE="dubbogo-examples/user-info/server/app"
BUILD_PACKAGE="app"
TARGET_CONF_FILE="conf/server.yml"
TARGET_LOG_CONF_FILE="conf/log.xml"
#!/usr/bin/env bash
# ******************************************************
# DESC : build script
# AUTHOR : Alex Stocks
# VERSION : 1.0
# LICENCE : Apache License 2.0
# EMAIL : alexstocks@foxmail.com
# MOD : 2016-07-12 16:28
# FILE : build.sh
# ******************************************************
rm -rf target/
PROJECT_HOME=`pwd`
TARGET_FOLDER=${PROJECT_HOME}/target/${GOOS}
TARGET_SBIN_NAME=${TARGET_EXEC_NAME}
version=`cat app/version.go | grep Version | awk -F '=' '{print $2}' | awk -F '"' '{print $2}'`
if [[ ${GOOS} == "windows" ]]; then
TARGET_SBIN_NAME=${TARGET_SBIN_NAME}.exe
fi
TARGET_NAME=${TARGET_FOLDER}/${TARGET_SBIN_NAME}
if [[ $PROFILE = "test" ]]; then
# GFLAGS=-gcflags "-N -l" -race -x -v # -x会把go build的详细过程输出
# GFLAGS=-gcflags "-N -l" -race -v
# GFLAGS="-gcflags \"-N -l\" -v"
cd ${BUILD_PACKAGE} && go build -gcflags "-N -l" -x -v -i -o ${TARGET_NAME} && cd -
else
# -s去掉符号表(然后panic时候的stack trace就没有任何文件名/行号信息了,这个等价于普通C/C++程序被strip的效果),
# -w去掉DWARF调试信息,得到的程序就不能用gdb调试了。-s和-w也可以分开使用,一般来说如果不打算用gdb调试,
# -w基本没啥损失。-s的损失就有点大了。
cd ${BUILD_PACKAGE} && go build -ldflags "-w" -x -v -i -o ${TARGET_NAME} && cd -
fi
TAR_NAME=${TARGET_EXEC_NAME}-${version}-`date "+%Y%m%d-%H%M"`-${PROFILE}
mkdir -p ${TARGET_FOLDER}/${TAR_NAME}
SBIN_DIR=${TARGET_FOLDER}/${TAR_NAME}/sbin
BIN_DIR=${TARGET_FOLDER}/${TAR_NAME}
CONF_DIR=${TARGET_FOLDER}/${TAR_NAME}/conf
mkdir -p ${SBIN_DIR}
mkdir -p ${CONF_DIR}
mv ${TARGET_NAME} ${SBIN_DIR}
cp -r assembly/bin ${BIN_DIR}
# modify APPLICATION_NAME
# OS=`uname`
# if [[ $OS=="Darwin" ]]; then
if [ "$(uname)" == "Darwin" ]; then
sed -i "" "s~APPLICATION_NAME~${TARGET_EXEC_NAME}~g" ${BIN_DIR}/bin/*
else
sed -i "s~APPLICATION_NAME~${TARGET_EXEC_NAME}~g" ${BIN_DIR}/bin/*
fi
# modify TARGET_CONF_FILE
if [ "$(uname)" == "Darwin" ]; then
sed -i "" "s~TARGET_CONF_FILE~${TARGET_CONF_FILE}~g" ${BIN_DIR}/bin/*
else
sed -i "s~TARGET_CONF_FILE~${TARGET_CONF_FILE}~g" ${BIN_DIR}/bin/*
fi
# modify TARGET_LOG_CONF_FILE
if [ "$(uname)" == "Darwin" ]; then
sed -i "" "s~TARGET_LOG_CONF_FILE~${TARGET_LOG_CONF_FILE}~g" ${BIN_DIR}/bin/*
else
sed -i "s~TARGET_LOG_CONF_FILE~${TARGET_LOG_CONF_FILE}~g" ${BIN_DIR}/bin/*
fi
cp -r profiles/${PROFILE}/* ${CONF_DIR}
cd ${TARGET_FOLDER}
tar czf ${TAR_NAME}.tar.gz ${TAR_NAME}/*
#!/usr/bin/env bash
# ******************************************************
# DESC : build script for dev env
# AUTHOR : Alex Stocks
# VERSION : 1.0
# LICENCE : Apache License 2.0
# EMAIL : alexstocks@foxmail.com
# MOD : 2018-06-24 17:32
# FILE : dev.sh
# ******************************************************
set -e
export GOOS=linux
export GOARCH=amd64
PROFILE=dev
PROJECT_HOME=`pwd`
if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then
. ${PROJECT_HOME}/assembly/common/app.properties
fi
if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then
. ${PROJECT_HOME}/assembly/common/build.sh
fi
#!/usr/bin/env bash
# ******************************************************
# DESC : build script for release env
# AUTHOR : Alex Stocks
# VERSION : 1.0
# LICENCE : Apache License 2.0
# EMAIL : alexstocks@foxmail.com
# MOD : 2016-07-12 16:25
# FILE : release.sh
# ******************************************************
set -e
export GOOS=linux
export GOARCH=amd64
PROFILE=release
PROJECT_HOME=`pwd`
if [ -f "${PROJECT_HOME}/assembly/common/app.properties" ]; then
. ${PROJECT_HOME}/assembly/common/app.properties
fi
if [ -f "${PROJECT_HOME}/assembly/common/build.sh" ]; then
. ${PROJECT_HOME}/assembly/common/build.sh
fi
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment