Created
July 3, 2020 02:12
-
-
Save lysu/064958b4babb55369b171559503241fb to your computer and use it in GitHub Desktop.
generate rule
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/hex" | |
"encoding/json" | |
"fmt" | |
"github.com/pingcap/tidb/util/codec" | |
"os" | |
"strings" | |
) | |
type entry struct { | |
Key string `json:"key"` | |
Op string `json:"op"` | |
Values []string `json:"values"` | |
} | |
type rule struct { | |
GroupID string `json:"group_id"` | |
Index int `json:"index"` | |
ID string `json:"id"` | |
StartKey string `json:"start_key"` | |
EndKey string `json:"end_key"` | |
Role string `json:"role"` | |
Count int `json:"count"` | |
LabelConstraints []entry `json:"label_constraints"` | |
Override bool `json:"override"` | |
LocationLabels []string `json:"location_labels"` | |
} | |
//| a | [178, 187] | | |
//| b | [190, 199] | | |
//| c | [202, 211] | | |
//| d | [214, 223]| | |
//| e | [226, 235]| | |
func main() { | |
var tblName = []string{"a", "b", "c", "d", "e"} | |
var tblID = [][]int {{178, 187}, {190, 199}, {202, 211}, {214, 223}, {226, 235}} | |
idxG := 1 | |
var rs []rule | |
for i, n := range tblName { | |
kvIdx := 1 | |
for pid := tblID[i][0]; pid <= tblID[i][1]; pid++ { | |
host := fmt.Sprintf("tikv%d", kvIdx) | |
kvIdx++ | |
startKey := idToStart(int64(pid)) | |
endkey := idToStart(int64(pid+1)) | |
idx := idxG | |
idxG++ | |
rs = append(rs, rule{ | |
GroupID: "pd", | |
Index: idx, | |
ID: fmt.Sprintf("%s-p%d-1", n, kvIdx-1 ), | |
StartKey: startKey, | |
EndKey: endkey, | |
Role: "leader", | |
Count: 1, | |
LabelConstraints: []entry{ | |
{ | |
Key: "host", | |
Op: "in", | |
Values: []string{host}, | |
}, | |
}, | |
Override: true, | |
LocationLabels: []string{"host"}, | |
}) | |
idx = idxG | |
idxG++ | |
rs = append(rs, rule{ | |
GroupID: "pd", | |
Index: idx, | |
ID: fmt.Sprintf("%s-p%d-2", n, kvIdx-1), | |
StartKey: startKey, | |
EndKey: endkey, | |
Role: "follower", | |
Count: 2, | |
LabelConstraints: []entry{ | |
{ | |
Key: "host", | |
Op: "notIn", | |
Values: []string{host}, | |
}, | |
}, | |
Override: false, | |
LocationLabels: []string{"host"}, | |
}) | |
} | |
} | |
rs = append([]rule{{ | |
GroupID: "pd", | |
ID: "default", | |
StartKey: "", | |
EndKey: "", | |
Role: "voter", | |
Count: 3, | |
}}, rs...) | |
b, _ := json.Marshal(rs) | |
fmt.Println(string(b)) | |
} | |
func idToStart(tableID int64) string { | |
key := []byte{'t'} | |
key = codec.EncodeInt(key, tableID) | |
if tableID == 0 { | |
fmt.Println("table ID shouldn't be 0") | |
os.Exit(1) | |
} | |
key = codec.EncodeBytes([]byte{}, key) | |
return strings.ToUpper(hex.EncodeToString(key)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment