2
0

tunasynctl.go 13 KB

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