github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/lorry/ctl/switchover.go (about) 1 /* 2 Copyright (C) 2022-2023 ApeCloud Co., Ltd 3 4 This file is part of KubeBlocks project 5 6 This program is free software: you can redistribute it and/or modify 7 it under the terms of the GNU Affero General Public License as published by 8 the Free Software Foundation, either version 3 of the License, or 9 (at your option) any later version. 10 11 This program is distributed in the hope that it will be useful 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU Affero General Public License for more details. 15 16 You should have received a copy of the GNU Affero General Public License 17 along with this program. If not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 package ctl 21 22 import ( 23 "fmt" 24 "io" 25 "net/http" 26 "os" 27 "strings" 28 29 "github.com/spf13/cobra" 30 31 "github.com/1aal/kubeblocks/pkg/constant" 32 ) 33 34 type SwitchOptions struct { 35 primary string 36 candidate string 37 lorryAddr string 38 } 39 40 var switchOptions = &SwitchOptions{} 41 var SwitchCmd = &cobra.Command{ 42 Use: "switchover", 43 Short: "execute a switchover request.", 44 Example: ` 45 lorryctl switchover --primary xxx --candidate xxx 46 `, 47 Args: cobra.MinimumNArgs(0), 48 Run: func(cmd *cobra.Command, args []string) { 49 var characterType string 50 if characterType = os.Getenv(constant.KBEnvCharacterType); characterType == "" { 51 fmt.Println("KB_SERVICE_CHARACTER_TYPE must be set") 52 return 53 } 54 55 url := "http://" + switchOptions.lorryAddr + "/v1.0/bindings/" + characterType 56 if switchOptions.primary == "" && switchOptions.candidate == "" { 57 fmt.Println("Primary or Candidate must be specified") 58 return 59 } 60 61 payload := fmt.Sprintf(`{"operation": "switchover", "metadata": {"leader": "%s", "candidate": "%s"}}`, switchOptions.primary, switchOptions.candidate) 62 // fmt.Println(payload) 63 64 client := http.Client{} 65 req, err := http.NewRequest("POST", url, strings.NewReader(payload)) 66 if err != nil { 67 fmt.Printf("New request error: %v", err) 68 } 69 70 resp, err := client.Do(req) 71 if err != nil { 72 fmt.Printf("Request Lorry error: %v", err) 73 return 74 } 75 fmt.Println("Lorry Response:") 76 bodyBytes, err := io.ReadAll(resp.Body) 77 if err != nil { 78 fmt.Printf("request error: %v", err) 79 } 80 fmt.Println(string(bodyBytes)) 81 }, 82 } 83 84 func init() { 85 SwitchCmd.Flags().StringVarP(&switchOptions.primary, "primary", "l", "", "The primary pod name") 86 SwitchCmd.Flags().StringVarP(&switchOptions.candidate, "candidate", "c", "", "The candidate pod name") 87 SwitchCmd.Flags().StringVarP(&switchOptions.lorryAddr, "lorry-addr", "", "localhost:3501", "The addr of lorry to request") 88 SwitchCmd.Flags().BoolP("help", "h", false, "Print this help message") 89 90 RootCmd.AddCommand(SwitchCmd) 91 }