tunasynctl.go 13 KB

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