2
0

tunasynctl.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "os"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/BurntSushi/toml"
  12. "github.com/urfave/cli"
  13. "gopkg.in/op/go-logging.v1"
  14. tunasync "github.com/tuna/tunasync/internal"
  15. )
  16. var (
  17. buildstamp = ""
  18. githash = "No githash provided"
  19. )
  20. const (
  21. listJobsPath = "/jobs"
  22. listWorkersPath = "/workers"
  23. flushDisabledPath = "/jobs/disabled"
  24. cmdPath = "/cmd"
  25. systemCfgFile = "/etc/tunasync/ctl.conf" // system-wide conf
  26. userCfgFile = "$HOME/.config/tunasync/ctl.conf" // user-specific conf
  27. )
  28. var logger = logging.MustGetLogger("tunasynctl")
  29. var baseURL string
  30. var client *http.Client
  31. func initializeWrapper(handler cli.ActionFunc) cli.ActionFunc {
  32. return func(c *cli.Context) error {
  33. err := initialize(c)
  34. if err != nil {
  35. return cli.NewExitError(err.Error(), 1)
  36. }
  37. return handler(c)
  38. }
  39. }
  40. type config struct {
  41. ManagerAddr string `toml:"manager_addr"`
  42. ManagerPort int `toml:"manager_port"`
  43. CACert string `toml:"ca_cert"`
  44. }
  45. func loadConfig(cfgFile string, cfg *config) error {
  46. if cfgFile != "" {
  47. logger.Infof("Loading config: %s", cfgFile)
  48. if _, err := toml.DecodeFile(cfgFile, cfg); err != nil {
  49. // logger.Errorf(err.Error())
  50. return err
  51. }
  52. }
  53. return nil
  54. }
  55. func initialize(c *cli.Context) error {
  56. // init logger
  57. tunasync.InitLogger(c.Bool("verbose"), c.Bool("debug"), false)
  58. cfg := new(config)
  59. // default configs
  60. cfg.ManagerAddr = "localhost"
  61. cfg.ManagerPort = 14242
  62. // find config file and load config
  63. if _, err := os.Stat(systemCfgFile); err == nil {
  64. err = loadConfig(systemCfgFile, cfg)
  65. if err != nil {
  66. return err
  67. }
  68. }
  69. logger.Debug("user config file: %s", os.ExpandEnv(userCfgFile))
  70. if _, err := os.Stat(os.ExpandEnv(userCfgFile)); err == nil {
  71. err = loadConfig(os.ExpandEnv(userCfgFile), cfg)
  72. if err != nil {
  73. return err
  74. }
  75. }
  76. if c.String("config") != "" {
  77. err := loadConfig(c.String("config"), cfg)
  78. if err != nil {
  79. return err
  80. }
  81. }
  82. // override config using the command-line arguments
  83. if c.String("manager") != "" {
  84. cfg.ManagerAddr = c.String("manager")
  85. }
  86. if c.Int("port") > 0 {
  87. cfg.ManagerPort = c.Int("port")
  88. }
  89. if c.String("ca-cert") != "" {
  90. cfg.CACert = c.String("ca-cert")
  91. }
  92. // parse base url of the manager server
  93. if cfg.CACert != "" {
  94. baseURL = fmt.Sprintf("https://%s:%d", cfg.ManagerAddr, cfg.ManagerPort)
  95. } else {
  96. baseURL = fmt.Sprintf("http://%s:%d", cfg.ManagerAddr, cfg.ManagerPort)
  97. }
  98. logger.Infof("Use manager address: %s", baseURL)
  99. // create HTTP client
  100. var err error
  101. client, err = tunasync.CreateHTTPClient(cfg.CACert)
  102. if err != nil {
  103. err = fmt.Errorf("Error initializing HTTP client: %s", err.Error())
  104. // logger.Error(err.Error())
  105. return err
  106. }
  107. return nil
  108. }
  109. func listWorkers(c *cli.Context) error {
  110. var workers []tunasync.WorkerStatus
  111. _, err := tunasync.GetJSON(baseURL+listWorkersPath, &workers, client)
  112. if err != nil {
  113. return cli.NewExitError(
  114. fmt.Sprintf("Filed to correctly get informations from"+
  115. "manager server: %s", err.Error()), 1)
  116. }
  117. b, err := json.MarshalIndent(workers, "", " ")
  118. if err != nil {
  119. return cli.NewExitError(
  120. fmt.Sprintf("Error printing out informations: %s",
  121. err.Error()),
  122. 1)
  123. }
  124. fmt.Println(string(b))
  125. return nil
  126. }
  127. func listJobs(c *cli.Context) error {
  128. var genericJobs interface{}
  129. if c.Bool("all") {
  130. var jobs []tunasync.WebMirrorStatus
  131. _, err := tunasync.GetJSON(baseURL+listJobsPath, &jobs, client)
  132. if err != nil {
  133. return cli.NewExitError(
  134. fmt.Sprintf("Failed to correctly get information "+
  135. "of all jobs from manager server: %s", err.Error()),
  136. 1)
  137. }
  138. genericJobs = jobs
  139. } else {
  140. var jobs []tunasync.MirrorStatus
  141. args := c.Args()
  142. if len(args) == 0 {
  143. return cli.NewExitError(
  144. fmt.Sprintf("Usage Error: jobs command need at"+
  145. " least one arguments or \"--all\" flag."), 1)
  146. }
  147. ans := make(chan []tunasync.MirrorStatus, len(args))
  148. for _, workerID := range args {
  149. go func(workerID string) {
  150. var workerJobs []tunasync.MirrorStatus
  151. _, err := tunasync.GetJSON(fmt.Sprintf("%s/workers/%s/jobs",
  152. baseURL, workerID), &workerJobs, client)
  153. if err != nil {
  154. logger.Infof("Failed to correctly get jobs"+
  155. " for worker %s: %s", workerID, err.Error())
  156. }
  157. ans <- workerJobs
  158. }(workerID)
  159. }
  160. for range args {
  161. job := <-ans
  162. if job == nil {
  163. return cli.NewExitError(
  164. fmt.Sprintf("Failed to correctly get information "+
  165. "of jobs from at least one manager"),
  166. 1)
  167. }
  168. jobs = append(jobs, job...)
  169. }
  170. genericJobs = jobs
  171. }
  172. b, err := json.MarshalIndent(genericJobs, "", " ")
  173. if err != nil {
  174. return cli.NewExitError(
  175. fmt.Sprintf("Error printing out information: %s", err.Error()),
  176. 1)
  177. }
  178. fmt.Println(string(b))
  179. return nil
  180. }
  181. func updateMirrorSize(c *cli.Context) error {
  182. args := c.Args()
  183. if len(args) != 2 {
  184. return cli.NewExitError("Usage: tunasynctl -w <worker-id> <mirror> <size>", 1)
  185. }
  186. workerID := c.String("worker")
  187. mirrorID := args.Get(0)
  188. mirrorSize := args.Get(1)
  189. msg := struct {
  190. Name string `json:"name"`
  191. Size string `json:"size"`
  192. }{
  193. Name: mirrorID,
  194. Size: mirrorSize,
  195. }
  196. url := fmt.Sprintf(
  197. "%s/workers/%s/jobs/%s/size", baseURL, workerID, mirrorID,
  198. )
  199. resp, err := tunasync.PostJSON(url, msg, client)
  200. if err != nil {
  201. return cli.NewExitError(
  202. fmt.Sprintf("Failed to send request to manager: %s",
  203. err.Error()),
  204. 1)
  205. }
  206. defer resp.Body.Close()
  207. body, _ := ioutil.ReadAll(resp.Body)
  208. if resp.StatusCode != http.StatusOK {
  209. return cli.NewExitError(
  210. fmt.Sprintf("Manager failed to update mirror size: %s", body), 1,
  211. )
  212. }
  213. var status tunasync.MirrorStatus
  214. json.Unmarshal(body, &status)
  215. if status.Size != mirrorSize {
  216. return cli.NewExitError(
  217. fmt.Sprintf(
  218. "Mirror size error, expecting %s, manager returned %s",
  219. mirrorSize, status.Size,
  220. ), 1,
  221. )
  222. }
  223. fmt.Printf("Successfully updated mirror size to %s\n", mirrorSize)
  224. return nil
  225. }
  226. func removeWorker(c *cli.Context) error {
  227. args := c.Args()
  228. if len(args) != 0 {
  229. return cli.NewExitError("Usage: tunasynctl -w <worker-id>", 1)
  230. }
  231. workerID := c.String("worker")
  232. if len(workerID) == 0 {
  233. return cli.NewExitError("Please specify the <worker-id>", 1)
  234. }
  235. url := fmt.Sprintf("%s/workers/%s", baseURL, workerID)
  236. req, err := http.NewRequest("DELETE", url, nil)
  237. if err != nil {
  238. logger.Panicf("Invalid HTTP Request: %s", err.Error())
  239. }
  240. resp, err := client.Do(req)
  241. if err != nil {
  242. return cli.NewExitError(
  243. fmt.Sprintf("Failed to send request to manager: %s", err.Error()), 1)
  244. }
  245. defer resp.Body.Close()
  246. if resp.StatusCode != http.StatusOK {
  247. body, err := ioutil.ReadAll(resp.Body)
  248. if err != nil {
  249. return cli.NewExitError(
  250. fmt.Sprintf("Failed to parse response: %s", err.Error()),
  251. 1)
  252. }
  253. return cli.NewExitError(fmt.Sprintf("Failed to correctly send"+
  254. " command: HTTP status code is not 200: %s", body),
  255. 1)
  256. }
  257. res := map[string]string{}
  258. err = json.NewDecoder(resp.Body).Decode(&res)
  259. if res["message"] == "deleted" {
  260. fmt.Println("Successfully removed the worker")
  261. } else {
  262. return cli.NewExitError("Failed to remove the worker", 1)
  263. }
  264. return nil
  265. }
  266. func flushDisabledJobs(c *cli.Context) error {
  267. req, err := http.NewRequest("DELETE", baseURL+flushDisabledPath, nil)
  268. if err != nil {
  269. logger.Panicf("Invalid HTTP Request: %s", err.Error())
  270. }
  271. resp, err := client.Do(req)
  272. if err != nil {
  273. return cli.NewExitError(
  274. fmt.Sprintf("Failed to send request to manager: %s",
  275. err.Error()),
  276. 1)
  277. }
  278. defer resp.Body.Close()
  279. if resp.StatusCode != http.StatusOK {
  280. body, err := ioutil.ReadAll(resp.Body)
  281. if err != nil {
  282. return cli.NewExitError(
  283. fmt.Sprintf("Failed to parse response: %s", err.Error()),
  284. 1)
  285. }
  286. return cli.NewExitError(fmt.Sprintf("Failed to correctly send"+
  287. " command: HTTP status code is not 200: %s", body),
  288. 1)
  289. }
  290. fmt.Println("Successfully flushed disabled jobs")
  291. return nil
  292. }
  293. func cmdJob(cmd tunasync.CmdVerb) cli.ActionFunc {
  294. return func(c *cli.Context) error {
  295. var mirrorID string
  296. var argsList []string
  297. if len(c.Args()) == 1 {
  298. mirrorID = c.Args()[0]
  299. } else if len(c.Args()) == 2 {
  300. mirrorID = c.Args()[0]
  301. for _, arg := range strings.Split(c.Args()[1], ",") {
  302. argsList = append(argsList, strings.TrimSpace(arg))
  303. }
  304. } else {
  305. return cli.NewExitError("Usage Error: cmd command receive just "+
  306. "1 required positional argument MIRROR and 1 optional "+
  307. "argument WORKER", 1)
  308. }
  309. options := map[string]bool{}
  310. if c.Bool("force") {
  311. options["force"] = true
  312. }
  313. cmd := tunasync.ClientCmd{
  314. Cmd: cmd,
  315. MirrorID: mirrorID,
  316. WorkerID: c.String("worker"),
  317. Args: argsList,
  318. Options: options,
  319. }
  320. resp, err := tunasync.PostJSON(baseURL+cmdPath, cmd, client)
  321. if err != nil {
  322. return cli.NewExitError(
  323. fmt.Sprintf("Failed to correctly send command: %s",
  324. err.Error()),
  325. 1)
  326. }
  327. defer resp.Body.Close()
  328. if resp.StatusCode != http.StatusOK {
  329. body, err := ioutil.ReadAll(resp.Body)
  330. if err != nil {
  331. return cli.NewExitError(
  332. fmt.Sprintf("Failed to parse response: %s", err.Error()),
  333. 1)
  334. }
  335. return cli.NewExitError(fmt.Sprintf("Failed to correctly send"+
  336. " command: HTTP status code is not 200: %s", body),
  337. 1)
  338. }
  339. fmt.Println("Successfully send the command")
  340. return nil
  341. }
  342. }
  343. func cmdWorker(cmd tunasync.CmdVerb) cli.ActionFunc {
  344. return func(c *cli.Context) error {
  345. if c.String("worker") == "" {
  346. return cli.NewExitError("Please specify the worker with -w <worker-id>", 1)
  347. }
  348. cmd := tunasync.ClientCmd{
  349. Cmd: cmd,
  350. WorkerID: c.String("worker"),
  351. }
  352. resp, err := tunasync.PostJSON(baseURL+cmdPath, cmd, client)
  353. if err != nil {
  354. return cli.NewExitError(
  355. fmt.Sprintf("Failed to correctly send command: %s",
  356. err.Error()),
  357. 1)
  358. }
  359. defer resp.Body.Close()
  360. if resp.StatusCode != http.StatusOK {
  361. body, err := ioutil.ReadAll(resp.Body)
  362. if err != nil {
  363. return cli.NewExitError(
  364. fmt.Sprintf("Failed to parse response: %s", err.Error()),
  365. 1)
  366. }
  367. return cli.NewExitError(fmt.Sprintf("Failed to correctly send"+
  368. " command: HTTP status code is not 200: %s", body),
  369. 1)
  370. }
  371. fmt.Println("Successfully send the command")
  372. return nil
  373. }
  374. }
  375. func main() {
  376. cli.VersionPrinter = func(c *cli.Context) {
  377. var builddate string
  378. if buildstamp == "" {
  379. builddate = "No build date provided"
  380. } else {
  381. ts, err := strconv.Atoi(buildstamp)
  382. if err != nil {
  383. builddate = "No build date provided"
  384. } else {
  385. t := time.Unix(int64(ts), 0)
  386. builddate = t.String()
  387. }
  388. }
  389. fmt.Printf(
  390. "Version: %s\n"+
  391. "Git Hash: %s\n"+
  392. "Build Date: %s\n",
  393. c.App.Version, githash, builddate,
  394. )
  395. }
  396. app := cli.NewApp()
  397. app.EnableBashCompletion = true
  398. app.Version = tunasync.Version
  399. app.Name = "tunasynctl"
  400. app.Usage = "control client for tunasync manager"
  401. commonFlags := []cli.Flag{
  402. cli.StringFlag{
  403. Name: "config, c",
  404. Usage: "Read configuration from `FILE` rather than" +
  405. " ~/.config/tunasync/ctl.conf and /etc/tunasync/ctl.conf",
  406. },
  407. cli.StringFlag{
  408. Name: "manager, m",
  409. Usage: "The manager server address",
  410. },
  411. cli.StringFlag{
  412. Name: "port, p",
  413. Usage: "The manager server port",
  414. },
  415. cli.StringFlag{
  416. Name: "ca-cert",
  417. Usage: "Trust root CA cert file `CERT`",
  418. },
  419. cli.BoolFlag{
  420. Name: "verbose, v",
  421. Usage: "Enable verbosely logging",
  422. },
  423. cli.BoolFlag{
  424. Name: "debug",
  425. Usage: "Enable debugging logging",
  426. },
  427. }
  428. cmdFlags := []cli.Flag{
  429. cli.StringFlag{
  430. Name: "worker, w",
  431. Usage: "Send the command to `WORKER`",
  432. },
  433. }
  434. forceStartFlag := cli.BoolFlag{
  435. Name: "force, f",
  436. Usage: "Override the concurrent limit",
  437. }
  438. app.Commands = []cli.Command{
  439. {
  440. Name: "list",
  441. Usage: "List jobs of workers",
  442. Flags: append(commonFlags,
  443. []cli.Flag{
  444. cli.BoolFlag{
  445. Name: "all, a",
  446. Usage: "List all jobs of all workers",
  447. },
  448. }...),
  449. Action: initializeWrapper(listJobs),
  450. },
  451. {
  452. Name: "flush",
  453. Usage: "Flush disabled jobs",
  454. Flags: commonFlags,
  455. Action: initializeWrapper(flushDisabledJobs),
  456. },
  457. {
  458. Name: "workers",
  459. Usage: "List workers",
  460. Flags: commonFlags,
  461. Action: initializeWrapper(listWorkers),
  462. },
  463. {
  464. Name: "rm-worker",
  465. Usage: "Remove a worker",
  466. Flags: append(
  467. commonFlags,
  468. cli.StringFlag{
  469. Name: "worker, w",
  470. Usage: "worker-id of the worker to be removed",
  471. },
  472. ),
  473. Action: initializeWrapper(removeWorker),
  474. },
  475. {
  476. Name: "set-size",
  477. Usage: "Set mirror size",
  478. Flags: append(
  479. commonFlags,
  480. cli.StringFlag{
  481. Name: "worker, w",
  482. Usage: "specify worker-id of the mirror job",
  483. },
  484. ),
  485. Action: initializeWrapper(updateMirrorSize),
  486. },
  487. {
  488. Name: "start",
  489. Usage: "Start a job",
  490. Flags: append(append(commonFlags, cmdFlags...), forceStartFlag),
  491. Action: initializeWrapper(cmdJob(tunasync.CmdStart)),
  492. },
  493. {
  494. Name: "stop",
  495. Usage: "Stop a job",
  496. Flags: append(commonFlags, cmdFlags...),
  497. Action: initializeWrapper(cmdJob(tunasync.CmdStop)),
  498. },
  499. {
  500. Name: "disable",
  501. Usage: "Disable a job",
  502. Flags: append(commonFlags, cmdFlags...),
  503. Action: initializeWrapper(cmdJob(tunasync.CmdDisable)),
  504. },
  505. {
  506. Name: "restart",
  507. Usage: "Restart a job",
  508. Flags: append(commonFlags, cmdFlags...),
  509. Action: initializeWrapper(cmdJob(tunasync.CmdRestart)),
  510. },
  511. {
  512. Name: "reload",
  513. Usage: "Tell worker to reload configurations",
  514. Flags: append(commonFlags, cmdFlags...),
  515. Action: initializeWrapper(cmdWorker(tunasync.CmdReload)),
  516. },
  517. {
  518. Name: "ping",
  519. Flags: append(commonFlags, cmdFlags...),
  520. Action: initializeWrapper(cmdJob(tunasync.CmdPing)),
  521. },
  522. }
  523. app.Run(os.Args)
  524. }