Skip to content

Commit 4b63a1f

Browse files
author
auxten
committed
Make observer and explorer work in one http server
1 parent c04859b commit 4b63a1f

3 files changed

Lines changed: 56 additions & 33 deletions

File tree

cmd/cql/main.go

Lines changed: 33 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import (
2525
"fmt"
2626
"io"
2727
"math/rand"
28-
"net/http"
2928
"os"
3029
"os/user"
3130
"path/filepath"
@@ -36,7 +35,6 @@ import (
3635
"time"
3736

3837
sqlite3 "github.com/CovenantSQL/go-sqlite3-encrypt"
39-
"github.com/rakyll/statik/fs"
4038
"github.com/sirupsen/logrus"
4139
"github.com/xo/dburl"
4240
"github.com/xo/usql/drivers"
@@ -51,11 +49,10 @@ import (
5149
"github.com/CovenantSQL/CovenantSQL/crypto/asymmetric"
5250
"github.com/CovenantSQL/CovenantSQL/crypto/hash"
5351
"github.com/CovenantSQL/CovenantSQL/proto"
52+
"github.com/CovenantSQL/CovenantSQL/sqlchain/observer"
5453
"github.com/CovenantSQL/CovenantSQL/types"
5554
"github.com/CovenantSQL/CovenantSQL/utils"
5655
"github.com/CovenantSQL/CovenantSQL/utils/log"
57-
58-
_ "github.com/CovenantSQL/CovenantSQL/cmd/cql/statik" // to embed the shardchain-explorer
5956
)
6057

6158
const name = "cql"
@@ -72,11 +69,14 @@ var (
7269
singleTransaction bool
7370
showVersion bool
7471
variables varsFlag
72+
stopCh = make(chan struct{})
73+
logLevel string
7574

7675
// Shard chain explorer stuff
77-
tmpPath string // background observer and explorer block and log file path
78-
cLog *logrus.Logger // console logger
79-
bgLogLevel string // background log level
76+
tmpPath string // background observer and explorer block and log file path
77+
cLog *logrus.Logger // console logger
78+
bgLogLevel string // background log level
79+
explorerAddr string // explorer Web addr
8080

8181
// DML variables
8282
createDB string // as a instance meta json string or simply a node count
@@ -88,7 +88,6 @@ var (
8888
waitTxConfirmation bool // wait for transaction confirmation before exiting
8989

9090
waitTxConfirmationMaxDuration time.Duration
91-
explorerAddr string
9291
)
9392

9493
type userPermission struct {
@@ -230,6 +229,7 @@ func usqlRegister() {
230229
}
231230

232231
func init() {
232+
flag.StringVar(&logLevel, "log-level", "", "Service log level")
233233
flag.StringVar(&dsn, "dsn", "", "Database url")
234234
flag.StringVar(&command, "command", "", "Run only single command (SQL or usql internal command) and exit")
235235
flag.StringVar(&fileName, "file", "", "Execute commands from file and exit")
@@ -246,6 +246,7 @@ func init() {
246246
// Explorer
247247
flag.StringVar(&tmpPath, "tmp-path", "", "Explorer temp file path, use os.TempDir for default")
248248
flag.StringVar(&bgLogLevel, "bg-log-level", "", "Background service log level")
249+
flag.StringVar(&explorerAddr, "web", "", "Address to serve a database chain explorer, e.g. :8546")
249250

250251
// DML flags
251252
flag.StringVar(&createDB, "create", "", "Create database, argument can be instance requirement json or simply a node count requirement")
@@ -255,20 +256,18 @@ func init() {
255256
flag.BoolVar(&getBalance, "get-balance", false, "Get balance of current account")
256257
flag.StringVar(&getBalanceWithTokenName, "token-balance", "", "Get specific token's balance of current account, e.g. Particle, Wave, and etc.")
257258
flag.BoolVar(&waitTxConfirmation, "wait-tx-confirm", false, "Wait for transaction confirmation")
258-
259-
flag.StringVar(&explorerAddr, "web", "", "Address to serve a database chain explorer, e.g. :8546")
260259
}
261260

262-
func serverAsShardChainExplorer(addr string) {
263-
statikFS, err := fs.New()
261+
func serverAsShardChainExplorer(webAddr string) {
262+
service, httpServer, err := observer.StartObserver(webAddr, version)
264263
if err != nil {
265-
log.WithError(err).Fatal("unable to create statik fs")
264+
log.WithError(err).Fatal("start observer failed")
266265
}
266+
<-stopCh
267267

268-
http.Handle("/", http.FileServer(statikFS))
269-
if err := http.ListenAndServe(addr, nil); err != nil {
270-
log.WithError(err).Error("http.ListenAndServe")
271-
}
268+
_ = observer.StopObserver(service, httpServer)
269+
270+
log.Info("observer stopped")
272271
}
273272

274273
func main() {
@@ -277,6 +276,7 @@ func main() {
277276
rand.Seed(time.Now().UnixNano())
278277

279278
flag.Parse()
279+
log.SetStringLevel(logLevel, log.InfoLevel)
280280
if tmpPath == "" {
281281
tmpPath = os.TempDir()
282282
}
@@ -298,17 +298,25 @@ func main() {
298298
}
299299
cLog.Infof("cql build: %#v\n", version)
300300

301+
configFile = utils.HomeDirExpand(configFile)
302+
301303
if explorerAddr != "" {
302-
serverAsShardChainExplorer(explorerAddr)
303-
return
304-
}
304+
var err error
305+
conf.GConf, err = conf.LoadConfig(configFile)
306+
if err != nil {
307+
log.WithField("config", configFile).WithError(err).Fatal("load config failed")
308+
}
305309

306-
configFile = utils.HomeDirExpand(configFile)
307-
// init covenantsql driver
308-
if err = client.Init(configFile, []byte(password)); err != nil {
309-
cLog.WithError(err).Error("init covenantsql client failed")
310-
os.Exit(-1)
310+
serverAsShardChainExplorer(explorerAddr)
311+
defer close(stopCh)
311312
return
313+
} else {
314+
// init covenantsql driver
315+
if err = client.Init(configFile, []byte(password)); err != nil {
316+
cLog.WithError(err).Error("init covenantsql client failed")
317+
os.Exit(-1)
318+
return
319+
}
312320
}
313321

314322
// TODO(leventeliu): discover more specific confirmation duration from config. We don't have

sqlchain/observer/api.go

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,17 @@ import (
2222
"errors"
2323
"fmt"
2424
"net/http"
25+
"net/url"
2526
"strconv"
2627
"time"
2728

2829
"github.com/CovenantSQL/CovenantSQL/crypto/hash"
2930
"github.com/CovenantSQL/CovenantSQL/proto"
31+
_ "github.com/CovenantSQL/CovenantSQL/sqlchain/observer/statik" // to embed the shardchain-explorer
3032
"github.com/CovenantSQL/CovenantSQL/types"
3133
"github.com/CovenantSQL/CovenantSQL/utils/log"
3234
"github.com/gorilla/mux"
35+
"github.com/rakyll/statik/fs"
3336
)
3437

3538
var (
@@ -657,8 +660,23 @@ func (a *explorerAPI) getHash(vars map[string]string) (h *hash.Hash, err error)
657660
}
658661

659662
func startAPI(service *Service, listenAddr string, version string) (server *http.Server, err error) {
663+
statikFS, err := fs.New()
664+
if err != nil {
665+
log.WithError(err).Fatal("unable to create statik fs")
666+
}
667+
660668
router := mux.NewRouter()
661-
router.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
669+
fs := http.FileServer(statikFS)
670+
router.Handle("/", fs)
671+
router.Handle("/static/{type}/{file}", fs)
672+
router.PathPrefix("/dbs").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
673+
r2 := new(http.Request)
674+
*r2 = *request
675+
r2.URL = new(url.URL)
676+
r2.URL.Path = "/"
677+
fs.ServeHTTP(writer, r2)
678+
})
679+
router.HandleFunc("/version", func(rw http.ResponseWriter, r *http.Request) {
662680
sendResponse(http.StatusOK, true, nil, map[string]interface{}{
663681
"version": version,
664682
}, rw)
@@ -667,7 +685,7 @@ func startAPI(service *Service, listenAddr string, version string) (server *http
667685
api := &explorerAPI{
668686
service: service,
669687
}
670-
v1Router := router.PathPrefix("/v1").Subrouter()
688+
v1Router := router.PathPrefix("/apiproxy.covenantsql/v1").Subrouter()
671689
v1Router.HandleFunc("/ack/{db}/{hash}", api.GetAck).Methods("GET")
672690
v1Router.HandleFunc("/offset/{db}/{offset:[0-9]+}",
673691
func(writer http.ResponseWriter, request *http.Request) {
@@ -679,9 +697,9 @@ func startAPI(service *Service, listenAddr string, version string) (server *http
679697
v1Router.HandleFunc("/count/{db}/{count:[0-9]+}", api.GetBlockByCount).Methods("GET")
680698
v1Router.HandleFunc("/height/{db}/{height:[0-9]+}", api.GetBlockByHeight).Methods("GET")
681699
v1Router.HandleFunc("/head/{db}", api.GetHighestBlock).Methods("GET")
682-
v2Router := router.PathPrefix("/v2").Subrouter()
700+
v2Router := router.PathPrefix("/apiproxy.covenantsql/v2").Subrouter()
683701
v2Router.HandleFunc("/head/{db}", api.GetHighestBlockV2).Methods("GET")
684-
v3Router := router.PathPrefix("/v3").Subrouter()
702+
v3Router := router.PathPrefix("/apiproxy.covenantsql/v3").Subrouter()
685703
v3Router.HandleFunc("/response/{db}/{hash}", api.GetResponse).Methods("GET")
686704
v3Router.HandleFunc("/block/{db}/{hash}", api.GetBlockV3).Methods("GET")
687705
v3Router.HandleFunc("/count/{db}/{count:[0-9]+}", api.GetBlockByCountV3).Methods("GET")

sqlchain/observer/observer.go

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,7 @@ func startService() (service *Service, err error) {
5858

5959
func stopService(service *Service) (err error) {
6060
// stop subscription
61-
service.stop()
62-
63-
return
61+
return service.stop()
6462
}
6563

6664
func StartObserver(listenAddr string, version string) (service *Service, httpServer *http.Server, err error) {
@@ -85,7 +83,6 @@ func StartObserver(listenAddr string, version string) (service *Service, httpSer
8583
log.WithError(err).Fatal("register node failed")
8684
}
8785
return
88-
8986
}
9087

9188
func StopObserver(service *Service, httpServer *http.Server) (err error) {

0 commit comments

Comments
 (0)