Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: server manager #1956

Merged
merged 4 commits into from
Jun 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 14 additions & 123 deletions api/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,28 +17,16 @@
package cmd

import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"

"github.com/shiningrush/droplet"
"github.com/spf13/cobra"

"github.com/apisix/manager-api/internal"
"github.com/apisix/manager-api/internal/conf"
"github.com/apisix/manager-api/internal/core/storage"
"github.com/apisix/manager-api/internal/core/store"
"github.com/apisix/manager-api/internal/filter"
"github.com/apisix/manager-api/internal/handler"
"github.com/apisix/manager-api/internal/core/server"
"github.com/apisix/manager-api/internal/log"
"github.com/apisix/manager-api/internal/utils"
)

var (
Expand Down Expand Up @@ -88,126 +76,29 @@ func manageAPI() error {
conf.InitConf()
log.InitLogger()

if err := utils.WritePID(conf.PIDPath, forceStart); err != nil {
log.Errorf("failed to write pid: %s", err)
s, err := server.NewServer(&server.Options{
ForceStart: forceStart,
})
if err != nil {
return 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
})

// start Manager API server
errSig := make(chan error, 5)
s.Start(errSig)

// Signal received to the process externally.
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

defer func() {
utils.CloseAll()
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 := storage.InitETCDClient(conf.ETCDConfig); err != nil {
log.Errorf("init etcd client fail: %w", err)
return err
}
if err := store.InitStores(); err != nil {
log.Errorf("init stores fail: %w", err)
return err
}

var server, serverSSL *http.Server
// For internal error handling across multiple goroutines.
errsig := make(chan error, 1)

// routes
r := internal.SetUpRouter()
addr := net.JoinHostPort(conf.ServerHost, strconv.Itoa(conf.ServerPort))
server = &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 := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Errorf("listen and serv fail: %s", err)
errsig <- 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 {
log.Errorf("listen and serve for HTTPS failed: %s", err)
errsig <- err
}
}()
}

printInfo()

select {
case err := <-errsig:
return err

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

shutdownServer(server)
shutdownServer(serverSSL)
s.Stop()
log.Infof("The Manager API server exited")
return nil
}
}

func shutdownServer(server *http.Server) {
if server != nil {
ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
defer cancel()

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

func printInfo() {
fmt.Fprint(os.Stdout, "The manager-api is running successfully!\n\n")
printVersion()
fmt.Fprintf(os.Stdout, "%-8s: %s:%d\n", "Listen", conf.ServerHost, conf.ServerPort)
if conf.SSLCert != "" && conf.SSLKey != "" {
fmt.Fprintf(os.Stdout, "%-8s: %s:%d\n", "HTTPS Listen", conf.SSLHost, conf.SSLPort)
case err := <-errSig:
log.Errorf("The Manager API server start failed: %s", err.Error())
return err
}
fmt.Fprintf(os.Stdout, "%-8s: %s\n", "Loglevel", conf.ErrorLogLevel)
fmt.Fprintf(os.Stdout, "%-8s: %s\n", "ErrorLogFile", conf.ErrorLogPath)
fmt.Fprintf(os.Stdout, "%-8s: %s\n\n", "AccessLogFile", conf.AccessLogPath)
return nil
}
11 changes: 1 addition & 10 deletions api/cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@
package cmd

import (
"fmt"
"os"

"github.com/spf13/cobra"

"github.com/apisix/manager-api/internal/utils"
Expand All @@ -30,13 +27,7 @@ func newVersionCommand() *cobra.Command {
Use: "version",
Short: "show manager-api version",
Run: func(cmd *cobra.Command, args []string) {
printVersion()
utils.PrintVersion()
},
}
}

func printVersion() {
gitHash, version := utils.GetHashAndVersion()
fmt.Fprintf(os.Stdout, "%-8s: %s\n", "Version", version)
fmt.Fprintf(os.Stdout, "%-8s: %s\n", "GitHash", gitHash)
}
72 changes: 72 additions & 0 deletions api/internal/core/server/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* 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 server

import (
"crypto/tls"
"net"
"net/http"
"strconv"
"time"

"github.com/shiningrush/droplet"

"github.com/apisix/manager-api/internal"
"github.com/apisix/manager-api/internal/conf"
"github.com/apisix/manager-api/internal/filter"
"github.com/apisix/manager-api/internal/handler"
)

func (s *server) setupAPI() {
// orchestrator
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
}

// routes
r := internal.SetUpRouter()

// HTTP
addr := net.JoinHostPort(conf.ServerHost, strconv.Itoa(conf.ServerPort))
s.server = &http.Server{
Addr: addr,
Handler: r,
ReadTimeout: time.Duration(1000) * time.Millisecond,
WriteTimeout: time.Duration(5000) * time.Millisecond,
}

// HTTPS
if conf.SSLCert != "" && conf.SSLKey != "" {
addrSSL := net.JoinHostPort(conf.SSLHost, strconv.Itoa(conf.SSLPort))
s.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,
},
}
}
}
Loading