tunasynctl.go 13 KB

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