Skip to content

Commit

Permalink
move to api v2
Browse files Browse the repository at this point in the history
Signed-off-by: lhy1024 <admin@liudos.us>
  • Loading branch information
lhy1024 committed Dec 18, 2024
1 parent b9888e5 commit 4e7bf41
Show file tree
Hide file tree
Showing 7 changed files with 139 additions and 74 deletions.
34 changes: 0 additions & 34 deletions server/api/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (

"github.com/unrolled/render"

"github.com/tikv/pd/pkg/storage"
"github.com/tikv/pd/server"
"github.com/tikv/pd/server/cluster"
)
Expand Down Expand Up @@ -78,36 +77,3 @@ func (h *healthHandler) GetHealthStatus(w http.ResponseWriter, _ *http.Request)
// @Summary Ping PD servers.
// @Router /ping [get]
func (*healthHandler) Ping(http.ResponseWriter, *http.Request) {}

// ReadyStatus reflects the cluster's ready status.
// NOTE: This type is exported by HTTP API. Please pay more attention when modifying it.
type ReadyStatus struct {
RegionLoaded bool `json:"region_loaded"`
}

// @Summary It will return whether pd follower is ready to became leader.
// @Router /ready [get]
// @Param verbose query bool false "Whether to return details."
// @Success 200
// @Failure 500
func (h *healthHandler) Ready(w http.ResponseWriter, r *http.Request) {
s := h.svr.GetStorage()
regionLoaded := storage.AreRegionsLoaded(s)
if regionLoaded {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusInternalServerError)
}

if _, ok := r.URL.Query()["verbose"]; !ok {
return
}
resp := &ReadyStatus{
RegionLoaded: regionLoaded,
}
if regionLoaded {
h.rd.JSON(w, http.StatusOK, resp)
} else {
h.rd.JSON(w, http.StatusInternalServerError, resp)
}
}
39 changes: 0 additions & 39 deletions server/api/health_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,11 @@ package api
import (
"encoding/json"
"io"
"net/http"
"strings"
"testing"

"github.com/stretchr/testify/require"

"github.com/pingcap/failpoint"

tu "github.com/tikv/pd/pkg/utils/testutil"
"github.com/tikv/pd/server"
"github.com/tikv/pd/server/config"
)
Expand Down Expand Up @@ -73,38 +69,3 @@ func TestHealthSlice(t *testing.T) {
re.NoError(err)
checkSliceResponse(re, buf, cfgs, follower.GetConfig().Name)
}

func TestReady(t *testing.T) {
re := require.New(t)
_, svrs, clean := mustNewCluster(re, 1)
defer clean()
mustBootstrapCluster(re, svrs[0])
url := svrs[0].GetConfig().ClientUrls + apiPrefix + "/api/v1/ready"
failpoint.Enable("github.com/tikv/pd/pkg/storage/loadRegionSlow", `return()`)
checkReady(re, url, false)
failpoint.Disable("github.com/tikv/pd/pkg/storage/loadRegionSlow")
checkReady(re, url, true)
}

func checkReady(re *require.Assertions, url string, isReady bool) {
expectCode := http.StatusOK
if !isReady {
expectCode = http.StatusInternalServerError
}
resp, err := testDialClient.Get(url)
re.NoError(err)
defer resp.Body.Close()
buf, err := io.ReadAll(resp.Body)
re.NoError(err)
re.Empty(buf)
re.Equal(expectCode, resp.StatusCode)
r := &ReadyStatus{}
if isReady {
r.RegionLoaded = true
}
data, err := json.Marshal(r)
re.NoError(err)
err = tu.CheckGetJSON(testDialClient, url+"?verbose", data,
tu.Status(re, expectCode))
re.NoError(err)
}
1 change: 0 additions & 1 deletion server/api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,6 @@ func createRouter(prefix string, svr *server.Server) *mux.Router {
healthHandler := newHealthHandler(svr, rd)
registerFunc(apiRouter, "/health", healthHandler.GetHealthStatus, setMethods(http.MethodGet), setAuditBackend(prometheus))
registerFunc(apiRouter, "/ping", healthHandler.Ping, setMethods(http.MethodGet), setAuditBackend(prometheus))
registerFunc(apiRouter, "/ready", healthHandler.Ready, setMethods(http.MethodGet), setAuditBackend(prometheus))

// metric query use to query metric data, the protocol is compatible with prometheus.
registerFunc(apiRouter, "/metric/query", newqueryMetric(svr).queryMetric, setMethods(http.MethodGet, http.MethodPost), setAuditBackend(prometheus))
Expand Down
65 changes: 65 additions & 0 deletions server/apiv2/handlers/ready.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright 2024 TiKV Project Authors.
//
// Licensed 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 handlers

import (
"net/http"

"github.com/gin-gonic/gin"

"github.com/tikv/pd/pkg/storage"
"github.com/tikv/pd/server"
"github.com/tikv/pd/server/apiv2/middlewares"
)

// RegisterMicroService registers ready group handlers to the server.
func RegisterReadyRouter(r *gin.RouterGroup) {
router := r.Group("ready")
router.GET("", Ready)
}

// ReadyStatus reflects the cluster's ready status.
// NOTE: This type is exported by HTTP API. Please pay more attention when modifying it.
type ReadyStatus struct {
RegionLoaded bool `json:"region_loaded"`
}

// @Summary It will return whether pd follower is ready to became leader.
// @Router /ready [get]
// @Param verbose query bool false "Whether to return details."
// @Success 200
// @Failure 500
func Ready(c *gin.Context) {
svr := c.MustGet(middlewares.ServerContextKey).(*server.Server)
s := svr.GetStorage()
regionLoaded := storage.AreRegionsLoaded(s)
if regionLoaded {
c.Status(http.StatusOK)
} else {
c.Status(http.StatusInternalServerError)
}

if _, ok := c.GetQuery("verbose"); !ok {
return
}
resp := &ReadyStatus{
RegionLoaded: regionLoaded,
}
if regionLoaded {
c.IndentedJSON(http.StatusOK, resp)
} else {
c.AbortWithStatusJSON(http.StatusInternalServerError, resp)
}
}
1 change: 1 addition & 0 deletions server/apiv2/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,6 @@ func NewV2Handler(_ context.Context, svr *server.Server) (http.Handler, apiutil.
handlers.RegisterKeyspace(root)
handlers.RegisterTSOKeyspaceGroup(root)
handlers.RegisterMicroService(root)
handlers.RegisterReadyRouter(root)
return router, group, nil
}
72 changes: 72 additions & 0 deletions tests/server/apiv2/handlers/ready_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright 2024 TiKV Project Authors.
//
// Licensed 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 handlers

import (
"context"
"encoding/json"
"io"
"net/http"
"testing"

"github.com/stretchr/testify/require"

"github.com/pingcap/failpoint"

tu "github.com/tikv/pd/pkg/utils/testutil"
"github.com/tikv/pd/server/apiv2/handlers"
"github.com/tikv/pd/tests"
)

func TestReady(t *testing.T) {
re := require.New(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cluster, err := tests.NewTestCluster(ctx, 1)
re.NoError(err)
defer cluster.Destroy()
re.NoError(cluster.RunInitialServers())
re.NotEmpty(cluster.WaitLeader())
server := cluster.GetLeaderServer()
re.NoError(server.BootstrapCluster())
url := server.GetConfig().ClientUrls + v2Prefix + "/ready"
failpoint.Enable("github.com/tikv/pd/pkg/storage/loadRegionSlow", `return()`)
checkReady(re, url, false)
failpoint.Disable("github.com/tikv/pd/pkg/storage/loadRegionSlow")
checkReady(re, url, true)
}

func checkReady(re *require.Assertions, url string, isReady bool) {
expectCode := http.StatusOK
if !isReady {
expectCode = http.StatusInternalServerError
}
resp, err := tests.TestDialClient.Get(url)
re.NoError(err)
defer resp.Body.Close()
buf, err := io.ReadAll(resp.Body)
re.NoError(err)
re.Empty(buf)
re.Equal(expectCode, resp.StatusCode)
r := &handlers.ReadyStatus{}
if isReady {
r.RegionLoaded = true
}
data, err := json.Marshal(r)
re.NoError(err)
err = tu.CheckGetJSON(tests.TestDialClient, url+"?verbose", data,
tu.Status(re, expectCode))
re.NoError(err)
}
1 change: 1 addition & 0 deletions tests/server/apiv2/handlers/testutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import (
)

const (
v2Prefix = "/pd/api/v2"
keyspacesPrefix = "/pd/api/v2/keyspaces"
keyspaceGroupsPrefix = "/pd/api/v2/tso/keyspace-groups"
)
Expand Down

0 comments on commit 4e7bf41

Please sign in to comment.