tunasynctl.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. cmd := tunasync.ClientCmd{
  289. Cmd: cmd,
  290. MirrorID: mirrorID,
  291. WorkerID: c.String("worker"),
  292. Args: argsList,
  293. }
  294. resp, err := tunasync.PostJSON(baseURL+cmdPath, cmd, client)
  295. if err != nil {
  296. return cli.NewExitError(
  297. fmt.Sprintf("Failed to correctly send command: %s",
  298. err.Error()),
  299. 1)
  300. }
  301. defer resp.Body.Close()
  302. if resp.StatusCode != http.StatusOK {
  303. body, err := ioutil.ReadAll(resp.Body)
  304. if err != nil {
  305. return cli.NewExitError(
  306. fmt.Sprintf("Failed to parse response: %s", err.Error()),
  307. 1)
  308. }
  309. return cli.NewExitError(fmt.Sprintf("Failed to correctly send"+
  310. " command: HTTP status code is not 200: %s", body),
  311. 1)
  312. }
  313. logger.Info("Succesfully send command")
  314. return nil
  315. }
  316. }
  317. func cmdWorker(cmd tunasync.CmdVerb) cli.ActionFunc {
  318. return func(c *cli.Context) error {
  319. cmd := tunasync.ClientCmd{
  320. Cmd: cmd,
  321. WorkerID: c.String("worker"),
  322. }
  323. resp, err := tunasync.PostJSON(baseURL+cmdPath, cmd, client)
  324. if err != nil {
  325. return cli.NewExitError(
  326. fmt.Sprintf("Failed to correctly send command: %s",
  327. err.Error()),
  328. 1)
  329. }
  330. defer resp.Body.Close()
  331. if resp.StatusCode != http.StatusOK {
  332. body, err := ioutil.ReadAll(resp.Body)
  333. if err != nil {
  334. return cli.NewExitError(
  335. fmt.Sprintf("Failed to parse response: %s", err.Error()),
  336. 1)
  337. }
  338. return cli.NewExitError(fmt.Sprintf("Failed to correctly send"+
  339. " command: HTTP status code is not 200: %s", body),
  340. 1)
  341. }
  342. logger.Info("Succesfully send command")
  343. return nil
  344. }
  345. }
  346. func main() {
  347. cli.VersionPrinter = func(c *cli.Context) {
  348. var builddate string
  349. if buildstamp == "" {
  350. builddate = "No build date provided"
  351. } else {
  352. ts, err := strconv.Atoi(buildstamp)
  353. if err != nil {
  354. builddate = "No build date provided"
  355. } else {
  356. t := time.Unix(int64(ts), 0)
  357. builddate = t.String()
  358. }
  359. }
  360. fmt.Printf(
  361. "Version: %s\n"+
  362. "Git Hash: %s\n"+
  363. "Build Date: %s\n",
  364. c.App.Version, githash, builddate,
  365. )
  366. }
  367. app := cli.NewApp()
  368. app.EnableBashCompletion = true
  369. app.Version = tunasync.Version
  370. app.Name = "tunasynctl"
  371. app.Usage = "control client for tunasync manager"
  372. commonFlags := []cli.Flag{
  373. cli.StringFlag{
  374. Name: "config, c",
  375. Usage: "Read configuration from `FILE` rather than" +
  376. " ~/.config/tunasync/ctl.conf and /etc/tunasync/ctl.conf",
  377. },
  378. cli.StringFlag{
  379. Name: "manager, m",
  380. Usage: "The manager server address",
  381. },
  382. cli.StringFlag{
  383. Name: "port, p",
  384. Usage: "The manager server port",
  385. },
  386. cli.StringFlag{
  387. Name: "ca-cert",
  388. Usage: "Trust root CA cert file `CERT`",
  389. },
  390. cli.BoolFlag{
  391. Name: "verbose, v",
  392. Usage: "Enable verbosely logging",
  393. },
  394. }
  395. cmdFlags := []cli.Flag{
  396. cli.StringFlag{
  397. Name: "worker, w",
  398. Usage: "Send the command to `WORKER`",
  399. },
  400. }
  401. app.Commands = []cli.Command{
  402. {
  403. Name: "list",
  404. Usage: "List jobs of workers",
  405. Flags: append(commonFlags,
  406. []cli.Flag{
  407. cli.BoolFlag{
  408. Name: "all, a",
  409. Usage: "List all jobs of all workers",
  410. },
  411. }...),
  412. Action: initializeWrapper(listJobs),
  413. },
  414. {
  415. Name: "flush",
  416. Usage: "Flush disabled jobs",
  417. Flags: commonFlags,
  418. Action: initializeWrapper(flushDisabledJobs),
  419. },
  420. {
  421. Name: "workers",
  422. Usage: "List workers",
  423. Flags: commonFlags,
  424. Action: initializeWrapper(listWorkers),
  425. },
  426. {
  427. Name: "rm-worker",
  428. Usage: "Remove a worker",
  429. Flags: append(
  430. commonFlags,
  431. cli.StringFlag{
  432. Name: "worker, w",
  433. Usage: "worker-id of the worker to be removed",
  434. },
  435. ),
  436. Action: initializeWrapper(removeWorker),
  437. },
  438. {
  439. Name: "set-size",
  440. Usage: "Set mirror size",
  441. Flags: append(
  442. commonFlags,
  443. cli.StringFlag{
  444. Name: "worker, w",
  445. Usage: "specify worker-id of the mirror job",
  446. },
  447. ),
  448. Action: initializeWrapper(updateMirrorSize),
  449. },
  450. {
  451. Name: "start",
  452. Usage: "Start a job",
  453. Flags: append(commonFlags, cmdFlags...),
  454. Action: initializeWrapper(cmdJob(tunasync.CmdStart)),
  455. },
  456. {
  457. Name: "stop",
  458. Usage: "Stop a job",
  459. Flags: append(commonFlags, cmdFlags...),
  460. Action: initializeWrapper(cmdJob(tunasync.CmdStop)),
  461. },
  462. {
  463. Name: "disable",
  464. Usage: "Disable a job",
  465. Flags: append(commonFlags, cmdFlags...),
  466. Action: initializeWrapper(cmdJob(tunasync.CmdDisable)),
  467. },
  468. {
  469. Name: "restart",
  470. Usage: "Restart a job",
  471. Flags: append(commonFlags, cmdFlags...),
  472. Action: initializeWrapper(cmdJob(tunasync.CmdRestart)),
  473. },
  474. {
  475. Name: "reload",
  476. Usage: "Tell worker to reload configurations",
  477. Flags: append(commonFlags, cmdFlags...),
  478. Action: initializeWrapper(cmdWorker(tunasync.CmdReload)),
  479. },
  480. {
  481. Name: "ping",
  482. Flags: append(commonFlags, cmdFlags...),
  483. Action: initializeWrapper(cmdJob(tunasync.CmdPing)),
  484. },
  485. }
  486. app.Run(os.Args)
  487. }