github.com/pingcap/failpoint@v0.0.0-20240412033321-fd0796e60f86/failpoint-ctl/main.go (about) 1 // Copyright 2019 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package main 16 17 import ( 18 "fmt" 19 "os" 20 "path/filepath" 21 22 "github.com/pingcap/failpoint/code" 23 "github.com/pingcap/failpoint/failpoint-ctl/version" 24 ) 25 26 func main() { 27 if len(os.Args) < 2 || (os.Args[1] != "enable" && os.Args[1] != "disable" && os.Args[1] != "-V") { 28 usage() 29 } 30 31 if os.Args[1] == "-V" { 32 version.PrintVersion() 33 os.Exit(0) 34 } 35 36 // Use current work path if user does not specify any path 37 paths := os.Args[2:] 38 if len(paths) == 0 { 39 wd, err := os.Getwd() 40 if err != nil { 41 fmt.Println("Get work directory error: " + err.Error()) 42 os.Exit(1) 43 } 44 paths = append(paths, wd) 45 } 46 47 // Expand all paths to its absolute path form 48 for i := range paths { 49 absPath, err := filepath.Abs(paths[i]) 50 if err != nil { 51 fmt.Println("Error occurred in absolute path " + paths[i] + " with " + err.Error()) 52 os.Exit(1) 53 } 54 realPath, err := filepath.EvalSymlinks(absPath) 55 if err != nil { 56 fmt.Println("Error resolving symbolic link "+absPath+", ", err.Error()) 57 os.Exit(1) 58 } 59 paths[i] = realPath 60 } 61 62 switch os.Args[1] { 63 case "enable": 64 var rewritePath []string 65 var errOccurred bool 66 for _, path := range paths { 67 rewritePath = append(rewritePath, path) 68 rewriter := code.NewRewriter(path) 69 if err := rewriter.Rewrite(); err != nil { 70 fmt.Println("Rewrite error " + err.Error()) 71 errOccurred = true 72 break 73 } 74 } 75 // Restore all paths which have been rewrited if any error occurred 76 // to avoid partial rewrite state which maybe make user strange. 77 if errOccurred { 78 restoreFiles(rewritePath) 79 os.Exit(1) 80 } 81 case "disable": 82 restoreFiles(paths) 83 } 84 } 85 86 func usage() { 87 fmt.Println("failpoint-ctl enable/disable /target/path [/target/path2 /target/path3 ...]") 88 os.Exit(1) 89 } 90 91 func restoreFiles(paths []string) { 92 for i := range paths { 93 restorer := code.NewRestorer(paths[i]) 94 err := restorer.Restore() 95 if err != nil { 96 fmt.Println("Restore error " + err.Error()) 97 } 98 } 99 }