This is an automated email from the ASF dual-hosted git repository.

starsz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/apisix-dashboard.git


The following commit(s) were added to refs/heads/master by this push:
     new 39aac5b  chore: add stop subcommand (#741)
39aac5b is described below

commit 39aac5bd23d25dc08cfddbab41111bc3e886362c
Author: Alex Zhang <[email protected]>
AuthorDate: Mon Jan 25 14:14:21 2021 +0800

    chore: add stop subcommand (#741)
---
 Makefile                   |  3 +--
 api/cmd/managerapi.go      | 36 ++++++++++++++++++++++++++
 api/internal/conf/conf.go  |  1 +
 api/internal/utils/pid.go  | 53 ++++++++++++++++++++++++++++++++++++++
 api/test/shell/cli_test.sh | 64 +++++++++++++++++++++++++++++++++-------------
 docs/deploy.md             |  5 +++-
 6 files changed, 141 insertions(+), 21 deletions(-)

diff --git a/Makefile b/Makefile
index 79de9e0..0937206 100644
--- a/Makefile
+++ b/Makefile
@@ -69,8 +69,7 @@ api-run: api-default
 
 ### api-stop:          Stop the manager-api
 api-stop:
-       kill $(ps aux | grep 'manager-api' | awk '{print $2}')
-
+       cd api && go run -ldflags "${GOLDFLAGS}" ./cmd/manager stop
 
 ### go-lint:           Lint Go source code
 .PHONY: go-lint
diff --git a/api/cmd/managerapi.go b/api/cmd/managerapi.go
index d36c3d8..d0dc1d0 100644
--- a/api/cmd/managerapi.go
+++ b/api/cmd/managerapi.go
@@ -60,6 +60,19 @@ func NewManagerAPICommand() *cobra.Command {
                RunE: func(cmd *cobra.Command, args []string) error {
                        conf.InitConf()
                        log.InitLogger()
+
+                       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
+                       })
+
                        droplet.Option.Orchestrator = func(mws 
[]droplet.Middleware) []droplet.Middleware {
                                var newMws []droplet.Middleware
                                // default middleware order: resp_reshape, 
auto_input, traffic_log
@@ -119,5 +132,28 @@ func NewManagerAPICommand() *cobra.Command {
        }
 
        cmd.PersistentFlags().StringVarP(&conf.WorkDir, "work-dir", "p", ".", 
"current work directory")
+
+       cmd.AddCommand(newStopCommand())
+       return cmd
+}
+
+func newStopCommand() *cobra.Command {
+       cmd := &cobra.Command{
+               Use: "stop",
+               Run: func(cmd *cobra.Command, args []string) {
+                       pid, err := utils.ReadPID(conf.PIDPath)
+                       if err != nil {
+                               if syscall.ENOENT.Error() != err.Error() {
+                                       fmt.Fprintf(os.Stderr, "failed to get 
manager-api pid: %s\n", err)
+                               } else {
+                                       fmt.Fprintf(os.Stderr,  "pid path %s 
not found, is manager-api running?\n", conf.PIDPath)
+                               }
+                               return
+                       }
+                       if err := syscall.Kill(pid, syscall.SIGINT); err != nil 
{
+                               fmt.Fprintf(os.Stderr, "failed to kill 
manager-api: %s", err)
+                       }
+               },
+       }
        return cmd
 }
diff --git a/api/internal/conf/conf.go b/api/internal/conf/conf.go
index e01ef41..883b1a6 100644
--- a/api/internal/conf/conf.go
+++ b/api/internal/conf/conf.go
@@ -52,6 +52,7 @@ var (
        UserList         = make(map[string]User, 2)
        AuthConf         Authentication
        SSLDefaultStatus = 1 //enable ssl by default
+       PIDPath          = "/tmp/manager-api.pid"
 )
 
 type Etcd struct {
diff --git a/api/internal/utils/pid.go b/api/internal/utils/pid.go
new file mode 100644
index 0000000..066a4c3
--- /dev/null
+++ b/api/internal/utils/pid.go
@@ -0,0 +1,53 @@
+/*
+ * 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 utils
+
+import (
+       "fmt"
+       "io/ioutil"
+       "os"
+       "strconv"
+)
+
+// WritePID write pid to the given file path.
+func WritePID(filepath string) error {
+       pid := os.Getpid()
+       f, err := os.OpenFile(filepath, 
os.O_WRONLY|os.O_CREATE|os.O_TRUNC|os.O_CREATE, 0600)
+       if err != nil {
+               return err
+       }
+       defer f.Close()
+
+       if _, err := f.WriteString(strconv.Itoa(pid)); err != nil {
+               return err
+       }
+       return nil
+}
+
+// ReadPID reads the pid from the given file path.
+func ReadPID(filepath string) (int, error) {
+       data, err := ioutil.ReadFile(filepath)
+       if err != nil {
+               return -1, err
+       }
+       pid, err := strconv.Atoi(string(data))
+       if err != nil {
+               return -1, fmt.Errorf("invalid pid: %s", err)
+       }
+       return pid, nil
+}
diff --git a/api/test/shell/cli_test.sh b/api/test/shell/cli_test.sh
index f73e08c..85acf47 100755
--- a/api/test/shell/cli_test.sh
+++ b/api/test/shell/cli_test.sh
@@ -19,6 +19,7 @@
 
 set -ex
 VERSION=$(cat ./VERSION)
+KERNEL=$(uname -s)
 
 # test content in .githash
 if [[ -f ../.githash ]]; then
@@ -57,7 +58,8 @@ go build -o ./manager-api -ldflags "-X 
github.com/apisix/manager-api/cmd.Version
 
 ./manager-api &
 sleep 3
-pkill -f manager-api
+./manager-api stop
+sleep 6
 
 check_logfile
 
@@ -70,11 +72,15 @@ clean_logfile
 
 # change level and test signal
 
-sed -i 's/level: warn/level: info/' conf/conf.yaml
+if [[ $KERNEL = "Darwin" ]]; then
+  sed -i "" 's/level: warn/level: info/' conf/conf.yaml
+else
+  sed -i 's/level: warn/level: info/' conf/conf.yaml
+fi
 
 ./manager-api &>/dev/null &
 sleep 3
-pkill -2 -f manager-api
+./manager-api stop
 sleep 6
 
 check_logfile
@@ -93,11 +99,16 @@ clean_logfile
 
 # change path
 
-sed -i 's/logs\/error.log/.\/error.log/' conf/conf.yaml
+if [[ $KERNEL = "Darwin" ]]; then
+  sed -i "" 's/logs\/error.log/.\/error.log/' conf/conf.yaml
+else
+  sed -i 's/logs\/error.log/.\/error.log/' conf/conf.yaml
+fi
 
 ./manager-api &
 sleep 3
-pkill -f manager-api
+./manager-api stop
+sleep 6
 
 check_logfile
 
@@ -116,7 +127,7 @@ APISIX_API_WORKDIR=$workDir $workDir/manager-api &
 sleep 5
 
 res=$(curl http://127.0.0.1:9000)
-pkill -f manager-api
+$workDir/manager-api stop
 cd -
 rm -rf html
 
@@ -130,22 +141,21 @@ clean_up
 workDir=$(pwd)
 distDir=/tmp/manager-api
 cp -r $workDir $distDir
-cd $distDir
-rm -fr bin && mkdir bin && mv ./manager-api ./bin/
-rm -rf html && mkdir html && echo "hi~" >> html/index.html
-cd bin && ./manager-api -p $distDir &
+cd $distDir && rm -rf bin && mkdir bin && mv ./manager-api ./bin/
+cd $distDir && rm -rf html && mkdir html && echo "hi~" >> html/index.html
+cd $distDir/bin && ./manager-api -p $distDir &
 sleep 5
 
 res=$(curl http://127.0.0.1:9000)
-pkill -f manager-api
+$distDir/bin/manager-api stop
+sleep 6
 rm -fr $distDir
 
 if [[ $res != "hi~" ]]; then
     echo "failed: manager-api can't run with -p flag out of the default 
directory"
     exit 1
 fi
-cd $workDir
-clean_up
+cd $workDir && git checkout conf/conf.yaml
 
 # test start info
 
@@ -155,6 +165,8 @@ PORT=$(cat conf/conf.yaml | awk '$1=="port:"{print $2}')
 STDOUT=/tmp/manager-api
 ./manager-api &>/tmp/manager-api &
 sleep 3
+./manager-api stop
+sleep 6
 
 if [[ `grep -c "The manager-api is running successfully\!" ${STDOUT}` -ne '1' 
]]; then
     echo "failed: the manager server didn't show started info"
@@ -185,7 +197,12 @@ fi
 
 clean_up
 
-sed -i 's/127.0.0.1:2379/127.0.0.0:2379/' conf/conf.yaml
+if [[ $KERNEL = "Darwin" ]]; then
+  sed -i "" 's/127.0.0.1:2379/127.0.0.0:2379/' conf/conf.yaml
+else
+  sed -i 's/127.0.0.1:2379/127.0.0.0:2379/' conf/conf.yaml
+fi
+
 
 ./manager-api > output.log 2>&1 &
 sleep 6
@@ -197,6 +214,8 @@ if [[ `grep -c "cmd/managerapi.go" ${logfile}` -ne '1' ]]; 
then
     exit 1
 fi
 
+./manager-api stop
+sleep 6
 # clean config
 clean_up
 
@@ -206,7 +225,8 @@ sleep 3
 
 curl http://127.0.0.1:9000/apisix/admin/user/login -d '{"username":"admin", 
"password": "admin"}'
 
-pkill -f manager-api
+./manager-api stop
+sleep 6
 
 if [[ `grep -c "/apisix/admin/user/login" ./logs/access.log` -eq '0' ]]; then
     echo "failed: failed to write access log"
@@ -236,9 +256,17 @@ if [[ `grep -c "etcdserver: user name is empty" 
${logfile}` -eq '0' ]]; then
     exit 1
 fi
 
+./manager-api stop
+sleep 6
+
 # modify etcd auth config
-sed -i '1,$s/# username: "root"    # ignore etcd username if not enable etcd 
auth/username: "root"/g' conf/conf.yaml
-sed -i '1,$s/# password: "123456"  # ignore etcd password if not enable etcd 
auth/password: "root"/g' conf/conf.yaml
+if [[ $KERNEL = "Darwin" ]]; then
+  sed -i "" '1,$s/# username: "root"    # ignore etcd username if not enable 
etcd auth/username: "root"/g' conf/conf.yaml
+  sed -i "" '1,$s/# password: "123456"  # ignore etcd password if not enable 
etcd auth/password: "root"/g' conf/conf.yaml
+else
+  sed -i '1,$s/# username: "root"    # ignore etcd username if not enable etcd 
auth/username: "root"/g' conf/conf.yaml
+  sed -i '1,$s/# password: "123456"  # ignore etcd password if not enable etcd 
auth/password: "root"/g' conf/conf.yaml
+fi
 
 ./manager-api &
 sleep 3
@@ -260,6 +288,6 @@ if [ "$respCode" != "0" ] || [ $respMessage != "\"\"" ]; 
then
     exit 1
 fi
 
-pkill -f manager-api
+./manager-api stop
 
 check_logfile
diff --git a/docs/deploy.md b/docs/deploy.md
index f4e5048..3d55548 100644
--- a/docs/deploy.md
+++ b/docs/deploy.md
@@ -80,6 +80,9 @@ $ nohup ./manager-api &
 
 5. Stop the Dashboard
 
+`manager-api` provides a sub command `stop` to quit the program gracefully, 
just
+run:
+
 ```sh
-$ kill $(ps aux | grep 'manager-api' | awk '{print $2}')
+$ ./manager-api stop
 ```

Reply via email to