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

*: Support SHOW PLACEMENT for placement policies #27531

Merged
merged 20 commits into from
Aug 31, 2021
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
2 changes: 2 additions & 0 deletions executor/show.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,8 @@ func (e *ShowExec) fetchAll(ctx context.Context) error {
return e.fetchShowBRIE(ast.BRIEKindRestore)
case ast.ShowPlacementLabels:
return e.fetchShowPlacementLabels(ctx)
case ast.ShowPlacement:
return e.fetchShowPlacement(ctx)
}
return nil
}
Expand Down
21 changes: 21 additions & 0 deletions executor/show_placement.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,24 @@ func (e *ShowExec) fetchShowPlacementLabels(ctx context.Context) error {

return nil
}

func (e *ShowExec) fetchShowPlacement(_ context.Context) error {
err := e.fetchAllPlacementPolicies()
if err != nil {
return err
}

return nil
}
xhebox marked this conversation as resolved.
Show resolved Hide resolved

func (e *ShowExec) fetchAllPlacementPolicies() error {
policies := e.is.AllPlacementPolicies()
sort.Slice(policies, func(i, j int) bool { return policies[i].Name.O < policies[j].Name.O })
for _, policy := range policies {
name := policy.Name
settings := policy.PlacementSettings
e.appendRow([]interface{}{"POLICY " + name.String(), settings.String(), "SCHEDULED"})
}

return nil
}
85 changes: 85 additions & 0 deletions executor/show_placement_labels_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Copyright 2021 PingCAP, Inc.
//
// 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 executor

import (
gjson "encoding/json"

. "github.com/pingcap/check"
"github.com/pingcap/tidb/store/helper"
"github.com/pingcap/tidb/types/json"
)

var _ = SerialSuites(&testShowPlacementLabelSuit{})

type testShowPlacementLabelSuit struct {
}

func (s *testShowPlacementLabelSuit) TestShowPlacementLabelsBuilder(c *C) {
cases := []struct {
stores [][]*helper.StoreLabel
expects [][]interface{}
}{
{
stores: nil,
expects: nil,
},
{
stores: [][]*helper.StoreLabel{
{{Key: "zone", Value: "z1"}, {Key: "rack", Value: "r3"}, {Key: "host", Value: "h1"}},
{{Key: "zone", Value: "z1"}, {Key: "rack", Value: "r1"}, {Key: "host", Value: "h2"}},
{{Key: "zone", Value: "z1"}, {Key: "rack", Value: "r2"}, {Key: "host", Value: "h2"}},
{{Key: "zone", Value: "z2"}, {Key: "rack", Value: "r1"}, {Key: "host", Value: "h2"}},
nil,
{{Key: "k1", Value: "v1"}},
},
expects: [][]interface{}{
{"host", []string{"h1", "h2"}},
{"k1", []string{"v1"}},
{"rack", []string{"r1", "r2", "r3"}},
{"zone", []string{"z1", "z2"}},
},
},
}

b := &showPlacementLabelsResultBuilder{}
toBinaryJSON := func(obj interface{}) (bj json.BinaryJSON) {
d, err := gjson.Marshal(obj)
c.Assert(err, IsNil)
err = bj.UnmarshalJSON(d)
c.Assert(err, IsNil)
return
}

for _, ca := range cases {
for _, store := range ca.stores {
bj := toBinaryJSON(store)
err := b.AppendStoreLabels(bj)
c.Assert(err, IsNil)
}

rows, err := b.BuildRows()
c.Assert(err, IsNil)
c.Assert(len(rows), Equals, len(ca.expects))
for idx, expect := range ca.expects {
row := rows[idx]
bj := toBinaryJSON(expect[1])

c.Assert(row[0].(string), Equals, expect[0].(string))
c.Assert(row[1].(json.BinaryJSON).TypeCode, Equals, bj.TypeCode)
c.Assert(row[1].(json.BinaryJSON).Value, BytesEquals, bj.Value)
}
}
}
99 changes: 40 additions & 59 deletions executor/show_placement_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,74 +12,55 @@
// See the License for the specific language governing permissions and
// limitations under the License.

package executor
package executor_test

import (
gjson "encoding/json"

. "github.com/pingcap/check"
"github.com/pingcap/tidb/store/helper"
"github.com/pingcap/tidb/types/json"
"github.com/pingcap/tidb/util/testkit"
)

var _ = SerialSuites(&testShowPlacementSuit{})
func (s *testSuite5) TestShowPlacement(c *C) {
tk := testkit.NewTestKit(c, s.store)
tk.MustExec("drop placement policy if exists p1")

type testShowPlacementSuit struct {
}
tk.MustExec("create placement policy pa1 " +
"PRIMARY_REGION=\"cn-east-1\" " +
"REGIONS=\"cn-east-1,cn-east-2\"" +
"SCHEDULE=\"EVEN\"")
defer tk.MustExec("drop placement policy pa1")

tk.MustExec("create placement policy pa2 " +
"LEADER_CONSTRAINTS=\"[+region=us-east-1]\" " +
"FOLLOWER_CONSTRAINTS=\"[+region=us-east-2]\" " +
"FOLLOWERS=3")
defer tk.MustExec("drop placement policy pa2")

func (s *testPartitionSuite) TestShowPlacementLabelsBuilder(c *C) {
cases := []struct {
stores [][]*helper.StoreLabel
expects [][]interface{}
}{
{
stores: nil,
expects: nil,
},
{
stores: [][]*helper.StoreLabel{
{{Key: "zone", Value: "z1"}, {Key: "rack", Value: "r3"}, {Key: "host", Value: "h1"}},
{{Key: "zone", Value: "z1"}, {Key: "rack", Value: "r1"}, {Key: "host", Value: "h2"}},
{{Key: "zone", Value: "z1"}, {Key: "rack", Value: "r2"}, {Key: "host", Value: "h2"}},
{{Key: "zone", Value: "z2"}, {Key: "rack", Value: "r1"}, {Key: "host", Value: "h2"}},
nil,
{{Key: "k1", Value: "v1"}},
},
expects: [][]interface{}{
{"host", []string{"h1", "h2"}},
{"k1", []string{"v1"}},
{"rack", []string{"r1", "r2", "r3"}},
{"zone", []string{"z1", "z2"}},
},
},
}
tk.MustExec("create placement policy pb1 " +
"VOTER_CONSTRAINTS=\"[+region=bj]\" " +
"LEARNER_CONSTRAINTS=\"[+region=sh]\" " +
"CONSTRAINTS=\"[+disk=ssd]\"" +
"VOTERS=5 " +
"LEARNERS=3")
defer tk.MustExec("drop placement policy pb1")

b := &showPlacementLabelsResultBuilder{}
toBinaryJSON := func(obj interface{}) (bj json.BinaryJSON) {
d, err := gjson.Marshal(obj)
c.Assert(err, IsNil)
err = bj.UnmarshalJSON(d)
c.Assert(err, IsNil)
return
}
tk.MustQuery("show placement").Check(testkit.Rows(
"POLICY pa1 PRIMARY_REGION=\"cn-east-1\" REGIONS=\"cn-east-1,cn-east-2\" SCHEDULE=\"EVEN\" SCHEDULED",
"POLICY pa2 LEADER_CONSTRAINTS=\"[+region=us-east-1]\" FOLLOWERS=3 FOLLOWER_CONSTRAINTS=\"[+region=us-east-2]\" SCHEDULED",
"POLICY pb1 CONSTRAINTS=\"[+disk=ssd]\" VOTERS=5 VOTER_CONSTRAINTS=\"[+region=bj]\" LEARNERS=3 LEARNER_CONSTRAINTS=\"[+region=sh]\" SCHEDULED",
))

for _, ca := range cases {
for _, store := range ca.stores {
bj := toBinaryJSON(store)
err := b.AppendStoreLabels(bj)
c.Assert(err, IsNil)
}
tk.MustQuery("show placement like 'POLICY%'").Check(testkit.Rows(
"POLICY pa1 PRIMARY_REGION=\"cn-east-1\" REGIONS=\"cn-east-1,cn-east-2\" SCHEDULE=\"EVEN\" SCHEDULED",
"POLICY pa2 LEADER_CONSTRAINTS=\"[+region=us-east-1]\" FOLLOWERS=3 FOLLOWER_CONSTRAINTS=\"[+region=us-east-2]\" SCHEDULED",
"POLICY pb1 CONSTRAINTS=\"[+disk=ssd]\" VOTERS=5 VOTER_CONSTRAINTS=\"[+region=bj]\" LEARNERS=3 LEARNER_CONSTRAINTS=\"[+region=sh]\" SCHEDULED",
))

rows, err := b.BuildRows()
c.Assert(err, IsNil)
c.Assert(len(rows), Equals, len(ca.expects))
for idx, expect := range ca.expects {
row := rows[idx]
bj := toBinaryJSON(expect[1])
tk.MustQuery("show placement like 'POLICY pa%'").Check(testkit.Rows(
"POLICY pa1 PRIMARY_REGION=\"cn-east-1\" REGIONS=\"cn-east-1,cn-east-2\" SCHEDULE=\"EVEN\" SCHEDULED",
"POLICY pa2 LEADER_CONSTRAINTS=\"[+region=us-east-1]\" FOLLOWERS=3 FOLLOWER_CONSTRAINTS=\"[+region=us-east-2]\" SCHEDULED",
))

c.Assert(row[0].(string), Equals, expect[0].(string))
c.Assert(row[1].(json.BinaryJSON).TypeCode, Equals, bj.TypeCode)
c.Assert(row[1].(json.BinaryJSON).Value, BytesEquals, bj.Value)
}
}
tk.MustQuery("show placement where Target='POLICY pb1'").Check(testkit.Rows(
"POLICY pb1 CONSTRAINTS=\"[+disk=ssd]\" VOTERS=5 VOTER_CONSTRAINTS=\"[+region=bj]\" LEARNERS=3 LEARNER_CONSTRAINTS=\"[+region=sh]\" SCHEDULED",
))
}
9 changes: 9 additions & 0 deletions infoschema/infoschema.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ type InfoSchema interface {
SetBundle(*placement.Bundle)
// RuleBundles will return a copy of all rule bundles.
RuleBundles() []*placement.Bundle
// AllPlacementPolicies returns all placement policies
AllPlacementPolicies() []*placementpolicy.PolicyInfo
}

type sortedTables []table.Table
Expand Down Expand Up @@ -406,6 +408,13 @@ func (is *infoSchema) SetBundle(bundle *placement.Bundle) {
is.ruleBundleMap[bundle.ID] = bundle
}

func (is *infoSchema) AllPlacementPolicies() (policies []*placementpolicy.PolicyInfo) {
for _, p := range is.policyMap {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

policyMutex?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After reading the current code, I found AllPlacementPolicies is not needed any more because PlacementPolicies did the same work. I'll remove this method and add PlacementPolicies to the interface.

But I think it is still safe without policyMutex because infoschema is immutable. The happens-before condition can be established for our current implement

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is just there in case, IMO. You are right that sometimes we are too cautious to do some great works. But this case is a little bit aggressive for me, especially that other policy APIs are following the conract of the mutex.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK. Actually I did not see policyMutex and just follow what the function AllSchemas did. As other policy APIs use policyMutex I think we should follow it either.

policies = append(policies, p)
}
return
}

func (is *infoSchema) deleteBundle(id string) {
is.ruleBundleMutex.Lock()
defer is.ruleBundleMutex.Unlock()
Expand Down
20 changes: 11 additions & 9 deletions meta/meta_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,17 @@ func TestPlacementPolicy(t *testing.T) {

// test the meta storage of placemnt policy.
policy := &placementpolicy.PolicyInfo{
Name: model.NewCIStr("aa"),
PrimaryRegion: "my primary",
Regions: "my regions",
Learners: 1,
Followers: 2,
Voters: 3,
Schedule: "even",
Constraints: "+disk=ssd",
LearnerConstraints: "+zone=shanghai",
Name: model.NewCIStr("aa"),
PlacementSettings: placementpolicy.PlacementSettings{
PrimaryRegion: "my primary",
Regions: "my regions",
Learners: 1,
Followers: 2,
Voters: 3,
Schedule: "even",
Constraints: "+disk=ssd",
LearnerConstraints: "+zone=shanghai",
},
}
err = m.CreatePolicy(policy)
require.NoError(t, err)
Expand Down
3 changes: 3 additions & 0 deletions planner/core/planbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -4127,6 +4127,9 @@ func buildShowSchema(s *ast.ShowStmt, isView bool, isSequence bool) (schema *exp
case ast.ShowPlacementLabels:
names = []string{"Key", "Values"}
ftypes = []byte{mysql.TypeVarchar, mysql.TypeJSON}
case ast.ShowPlacement:
names = []string{"Target", "Placement", "Scheduling_state"}
ftypes = []byte{mysql.TypeVarchar, mysql.TypeVarchar, mysql.TypeVarchar}
}

schema = expression.NewSchema(make([]*expression.Column, 0, len(names))...)
Expand Down
85 changes: 71 additions & 14 deletions util/placementpolicy/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,80 @@
package placementpolicy

import (
"fmt"
"strings"

"github.com/pingcap/parser/model"
)

// PlacementSettings is the settings of the placement
type PlacementSettings struct {
PrimaryRegion string `json:"primary_region"`
Regions string `json:"regions"`
Learners uint64 `json:"learners"`
Followers uint64 `json:"followers"`
Voters uint64 `json:"voters"`
Schedule string `json:"schedule"`
Constraints string `json:"constraints"`
LeaderConstraints string `json:"leader_constraints"`
LearnerConstraints string `json:"learner_constraints"`
FollowerConstraints string `json:"follower_constraints"`
VoterConstraints string `json:"voter_constraints"`
}

func (p *PlacementSettings) String() string {
settings := make([]string, 0)
AilinKid marked this conversation as resolved.
Show resolved Hide resolved
if len(p.PrimaryRegion) > 0 {
settings = append(settings, fmt.Sprintf("PRIMARY_REGION=\"%s\"", p.PrimaryRegion))
}

if len(p.Regions) > 0 {
settings = append(settings, fmt.Sprintf("REGIONS=\"%s\"", p.Regions))
}

if len(p.Schedule) > 0 {
settings = append(settings, fmt.Sprintf("SCHEDULE=\"%s\"", p.Schedule))
}

if len(p.Constraints) > 0 {
settings = append(settings, fmt.Sprintf("CONSTRAINTS=\"%s\"", p.Constraints))
}

if len(p.LeaderConstraints) > 0 {
settings = append(settings, fmt.Sprintf("LEADER_CONSTRAINTS=\"%s\"", p.LeaderConstraints))
}

if p.Voters > 0 {
settings = append(settings, fmt.Sprintf("VOTERS=%d", p.Voters))
}

if len(p.VoterConstraints) > 0 {
settings = append(settings, fmt.Sprintf("VOTER_CONSTRAINTS=\"%s\"", p.VoterConstraints))
}

if p.Followers > 0 {
settings = append(settings, fmt.Sprintf("FOLLOWERS=%d", p.Followers))
}

if len(p.FollowerConstraints) > 0 {
settings = append(settings, fmt.Sprintf("FOLLOWER_CONSTRAINTS=\"%s\"", p.FollowerConstraints))
}

if p.Learners > 0 {
settings = append(settings, fmt.Sprintf("LEARNERS=%d", p.Learners))
}

if len(p.LearnerConstraints) > 0 {
settings = append(settings, fmt.Sprintf("LEARNER_CONSTRAINTS=\"%s\"", p.LearnerConstraints))
}

return strings.Join(settings, " ")
}

// PolicyInfo is the struct to store the placement policy.
type PolicyInfo struct {
ID int64 `json:"id"`
Name model.CIStr `json:"name"`
PrimaryRegion string `json:"primary_region"`
Regions string `json:"regions"`
Learners uint64 `json:"learners"`
Followers uint64 `json:"followers"`
Voters uint64 `json:"voters"`
Schedule string `json:"schedule"`
Constraints string `json:"constraints"`
LeaderConstraints string `json:"leader_constraints"`
LearnerConstraints string `json:"learner_constraints"`
FollowerConstraints string `json:"follower_constraints"`
VoterConstraints string `json:"voter_constraints"`
State model.SchemaState `json:"state"`
PlacementSettings
AilinKid marked this conversation as resolved.
Show resolved Hide resolved
ID int64 `json:"id"`
Name model.CIStr `json:"name"`
State model.SchemaState `json:"state"`
}
Loading