tunasynctl.go 13 KB

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