Skip to content

Commit

Permalink
Merge branch 'master' into fix-store-init-error
Browse files Browse the repository at this point in the history
  • Loading branch information
bisakhmondal committed Apr 30, 2021
1 parent 836be0d commit b9aea51
Show file tree
Hide file tree
Showing 5 changed files with 292 additions and 90 deletions.
249 changes: 159 additions & 90 deletions api/cmd/managerapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ var (
showVersion bool
Version string
GitHash string
service *Service
)

func printInfo() {
Expand All @@ -65,6 +66,14 @@ func printVersion() {

// NewManagerAPICommand creates the manager-api command.
func NewManagerAPICommand() *cobra.Command {
cobra.OnInitialize(func() {
var err error
service, err = createService()
if err != nil {
fmt.Fprintf(os.Stderr, "error occurred while initializing service: %s", err)
}
})

cmd := &cobra.Command{
Use: "manager-api [flags]",
Short: "APISIX Manager API",
Expand All @@ -74,119 +83,165 @@ func NewManagerAPICommand() *cobra.Command {
printVersion()
os.Exit(0)
}
err := manageAPI()
return err
},
}

conf.InitConf()
log.InitLogger()
cmd.PersistentFlags().StringVarP(&conf.WorkDir, "work-dir", "p", ".", "current work directory")
cmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "show manager-api version")

if err := utils.WritePID(conf.PIDPath); err != nil {
log.Errorf("failed to write pid: %s", err)
panic(err)
}
utils.AppendToClosers(func() error {
if err := os.Remove(conf.PIDPath); err != nil {
log.Errorf("failed to remove pid path: %s", err)
return err
}
return nil
})
cmd.AddCommand(newStartCommand(), newInstallCommand(), newStatusCommand(), newStopCommand(), newRemoveCommand())
return cmd
}

quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
func manageAPI() error {
conf.InitConf()
log.InitLogger()

defer func() {
utils.CloseAll()
log.Infof("The Manager API server exited")
signal.Stop(quit)
}()

droplet.Option.Orchestrator = func(mws []droplet.Middleware) []droplet.Middleware {
var newMws []droplet.Middleware
// default middleware order: resp_reshape, auto_input, traffic_log
// We should put err_transform at second to catch all error
newMws = append(newMws, mws[0], &handler.ErrorTransformMiddleware{}, &filter.AuthenticationMiddleware{})
newMws = append(newMws, mws[1:]...)
return newMws
}
if err := utils.WritePID(conf.PIDPath); err != nil {
log.Errorf("failed to write pid: %s", err)
panic(err)
}
utils.AppendToClosers(func() error {
if err := os.Remove(conf.PIDPath); err != nil {
log.Errorf("failed to remove pid path: %s", err)
return err
}
return nil
})
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

if err := storage.InitETCDClient(conf.ETCDConfig); err != nil {
log.Errorf("init etcd client fail: %w", err)
panic(err)
}
if err := store.InitStores(); err != nil {
log.Errorf("init stores fail: %w", err)
fmt.Fprintf(os.Stderr, "%s\n", err)
utils.CloseAll()
os.Exit(1)
}
defer func() {
utils.CloseAll()
log.Infof("The Manager API server exited")
signal.Stop(quit)
}()

// routes
r := internal.SetUpRouter()
addr := fmt.Sprintf("%s:%d", conf.ServerHost, conf.ServerPort)
s := &http.Server{
Addr: addr,
Handler: r,
ReadTimeout: time.Duration(1000) * time.Millisecond,
WriteTimeout: time.Duration(5000) * time.Millisecond,
}
droplet.Option.Orchestrator = func(mws []droplet.Middleware) []droplet.Middleware {
var newMws []droplet.Middleware
// default middleware order: resp_reshape, auto_input, traffic_log
// We should put err_transform at second to catch all error
newMws = append(newMws, mws[0], &handler.ErrorTransformMiddleware{}, &filter.AuthenticationMiddleware{})
newMws = append(newMws, mws[1:]...)
return newMws
}

log.Infof("The Manager API is listening on %s", addr)
if err := storage.InitETCDClient(conf.ETCDConfig); err != nil {
log.Errorf("init etcd client fail: %w", err)
panic(err)
}
if err := store.InitStores(); err != nil {
log.Errorf("init stores fail: %w", err)
fmt.Fprintf(os.Stderr, "%s\n", err)
utils.CloseAll()
os.Exit(1)
}

go func() {
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
utils.CloseAll()
log.Fatalf("listen and serv fail: %s", err)
}
}()

// HTTPS
if conf.SSLCert != "" && conf.SSLKey != "" {
addrSSL := net.JoinHostPort(conf.ServerHost, strconv.Itoa(conf.SSLPort))
serverSSL := &http.Server{
Addr: addrSSL,
Handler: r,
ReadTimeout: time.Duration(1000) * time.Millisecond,
WriteTimeout: time.Duration(5000) * time.Millisecond,
TLSConfig: &tls.Config{
// Causes servers to use Go's default ciphersuite preferences,
// which are tuned to avoid attacks. Does nothing on clients.
PreferServerCipherSuites: true,
},
}
go func() {
err := serverSSL.ListenAndServeTLS(conf.SSLCert, conf.SSLKey)
if err != nil && err != http.ErrServerClosed {
utils.CloseAll()
log.Fatalf("listen and serve for HTTPS failed: %s", err)
}
}()
// routes
r := internal.SetUpRouter()
addr := net.JoinHostPort(conf.ServerHost, strconv.Itoa(conf.ServerPort))
s := &http.Server{
Addr: addr,
Handler: r,
ReadTimeout: time.Duration(1000) * time.Millisecond,
WriteTimeout: time.Duration(5000) * time.Millisecond,
}

log.Infof("The Manager API is listening on %s", addr)

go func() {
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
utils.CloseAll()
log.Fatalf("listen and serv fail: %s", err)
}
}()

// HTTPS
if conf.SSLCert != "" && conf.SSLKey != "" {
addrSSL := net.JoinHostPort(conf.ServerHost, strconv.Itoa(conf.SSLPort))
serverSSL := &http.Server{
Addr: addrSSL,
Handler: r,
ReadTimeout: time.Duration(1000) * time.Millisecond,
WriteTimeout: time.Duration(5000) * time.Millisecond,
TLSConfig: &tls.Config{
// Causes servers to use Go's default ciphersuite preferences,
// which are tuned to avoid attacks. Does nothing on clients.
PreferServerCipherSuites: true,
},
}
go func() {
err := serverSSL.ListenAndServeTLS(conf.SSLCert, conf.SSLKey)
if err != nil && err != http.ErrServerClosed {
utils.CloseAll()
log.Fatalf("listen and serve for HTTPS failed: %s", err)
}
}()
}

printInfo()
printInfo()

sig := <-quit
log.Infof("The Manager API server receive %s and start shutting down", sig.String())
sig := <-quit
log.Infof("The Manager API server receive %s and start shutting down", sig.String())

ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
defer cancel()
ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
defer cancel()

if err := s.Shutdown(ctx); err != nil {
log.Errorf("Shutting down server error: %s", err)
}
if err := s.Shutdown(ctx); err != nil {
log.Errorf("Shutting down server error: %s", err)
}

return nil
}

return nil
func newStartCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "start",
Short: "start Apache APISIX Dashboard service",
RunE: func(cmd *cobra.Command, args []string) error {
serviceState.startService = true
status, err := service.manageService()
fmt.Println(status)
return err
},
}
return cmd
}

cmd.PersistentFlags().StringVarP(&conf.WorkDir, "work-dir", "p", ".", "current work directory")
cmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "show manager-api version")
func newInstallCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "install",
Short: "re-install Apache APISIX Dashboard service",
RunE: func(cmd *cobra.Command, args []string) error {
serviceState.installService = true
status, err := service.manageService()
fmt.Println(status)
return err
},
}
return cmd
}

cmd.AddCommand(newStopCommand())
func newStatusCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "status",
Short: "inspect the status of Apache APISIX Dashboard service",
RunE: func(cmd *cobra.Command, args []string) error {
serviceState.status = true
status, err := service.manageService()
fmt.Println(status)
return err
},
}
return cmd
}

func newStopCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "stop",
Use: "stop",
Short: "stop Apache APISIX Dashboard service/program",
Run: func(cmd *cobra.Command, args []string) {
pid, err := utils.ReadPID(conf.PIDPath)
if err != nil {
Expand All @@ -204,3 +259,17 @@ func newStopCommand() *cobra.Command {
}
return cmd
}

func newRemoveCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "remove",
Short: "remove Apache APISIX Dashboard service",
RunE: func(cmd *cobra.Command, args []string) error {
serviceState.removeService = true
status, err := service.manageService()
fmt.Println(status)
return err
},
}
return cmd
}
93 changes: 93 additions & 0 deletions api/cmd/service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd

import (
"os"
"runtime"

"github.com/apisix/manager-api/internal/conf"
"github.com/takama/daemon"
)

type Service struct {
daemon.Daemon
}

var serviceState struct {
startService bool
stopService bool
installService bool
removeService bool
status bool
}

func createService() (*Service, error) {
var d daemon.Daemon
var err error
if runtime.GOOS == "darwin" {
d, err = daemon.New("apisix-dashboard", "Apache APISIX Dashboard", daemon.GlobalDaemon)
} else {
d, err = daemon.New("apisix-dashboard", "Apache APISIX Dashboard", daemon.SystemDaemon)
}
if err != nil {
return nil, err
}
service := &Service{d}
return service, nil
}

func (service *Service) manageService() (string, error) {
if serviceState.status {
return service.Status()
}
if serviceState.removeService {
return service.Remove()
}
if conf.WorkDir == "." {
dir, err := os.Getwd()
if err != nil {
return "proceed with --work-dir flag", err
}
conf.WorkDir = dir
}
if serviceState.installService {
return service.Install("-p", conf.WorkDir)
}
if serviceState.startService {
iStatus, err := service.Install("-p", conf.WorkDir)
if err != nil {
if err != daemon.ErrAlreadyInstalled {
return iStatus, err
}
iStatus = ""
}
sStatus, err := service.Start()
if iStatus != "" {
sStatus = iStatus + "\n" + sStatus
}
return sStatus, err
} else if serviceState.stopService {
return service.Stop()
}

err := manageAPI()
if err != nil {
return "Unable to start Manager API", err
}
return "The Manager API server exited", nil
}
1 change: 1 addition & 0 deletions api/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ require (
github.com/sony/sonyflake v1.0.0
github.com/spf13/cobra v0.0.3
github.com/stretchr/testify v1.6.1
github.com/takama/daemon v1.0.0
github.com/tidwall/gjson v1.6.7
github.com/tmc/grpc-websocket-proxy v0.0.0-20200427203606-3cfed13b9966 // indirect
github.com/xeipuuv/gojsonschema v1.2.0
Expand Down
Loading

0 comments on commit b9aea51

Please sign in to comment.