client.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. package linode
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "time"
  10. "git.aetherial.dev/aeth/yosai/pkg/daemon"
  11. "git.aetherial.dev/aeth/yosai/pkg/keytags"
  12. )
  13. const LinodeApiUrl = "api.linode.com"
  14. const LinodeInstances = "linode/instances"
  15. const LinodeImages = "images"
  16. const LinodeApiVers = "v4"
  17. const LinodeRegions = "regions"
  18. const LinodeTypes = "linode/types"
  19. type GetAllLinodes struct {
  20. Data []GetLinodeResponse `json:"data"`
  21. }
  22. func (g GetAllLinodes) GetResult() string {
  23. resp, err := json.MarshalIndent(&g, " ", " ")
  24. if err != nil {
  25. return "Sorry, couldnt parse the json." + err.Error()
  26. }
  27. return string(resp)
  28. }
  29. type GetLinodeResponse struct {
  30. Id int `json:"id"`
  31. Ipv4 []string `json:"ipv4"`
  32. Label string `json:"label"`
  33. Created string `json:"created"`
  34. Region string `json:"region"`
  35. Status string `json:"status"`
  36. }
  37. type TypesResponse struct {
  38. Data []TypesResponseInner `json:"data"`
  39. }
  40. type TypesResponseInner struct {
  41. Id string `json:"id"`
  42. }
  43. type ImagesResponse struct {
  44. Data []ImagesResponseInner `json:"data"`
  45. }
  46. type ImagesResponseInner struct {
  47. Id string `json:"id"`
  48. }
  49. type RegionsResponse struct {
  50. Data []RegionResponseInner `json:"data"`
  51. }
  52. type RegionResponseInner struct {
  53. Id string `json:"id"`
  54. }
  55. type NewLinodeBody struct {
  56. Label string `json:"label"`
  57. AuthorizedKeys []string `json:"authorized_keys"`
  58. Booted bool `json:"booted"`
  59. Image string `json:"image"`
  60. RootPass string `json:"root_pass"`
  61. Region string `json:"region"`
  62. Type string `json:"type"`
  63. }
  64. type LinodeConnection struct {
  65. Client *http.Client
  66. Keyring daemon.DaemonKeyRing
  67. KeyTagger keytags.Keytagger
  68. Config daemon.Configuration
  69. }
  70. // Construct a NewLinodeBody struct for a CreateNewLinode call
  71. func NewLinodeBodyBuilder(image string, region string, linodeType string, label string, keyring daemon.DaemonKeyRing) (NewLinodeBody, error) {
  72. var newLnBody NewLinodeBody
  73. rootPass, err := keyring.GetKey(keytags.VPS_ROOT_PASS_KEYNAME)
  74. if err != nil {
  75. return newLnBody, &LinodeClientError{Msg: err.Error()}
  76. }
  77. rootSshKey, err := keyring.GetKey(keytags.VPS_SSH_KEY_KEYNAME)
  78. if err != nil {
  79. return newLnBody, &LinodeClientError{Msg: err.Error()}
  80. }
  81. return NewLinodeBody{AuthorizedKeys: []string{rootSshKey.GetPublic()},
  82. Label: label,
  83. RootPass: rootPass.GetSecret(),
  84. Booted: true,
  85. Image: image,
  86. Region: region,
  87. Type: linodeType}, nil
  88. }
  89. /*
  90. Get all regions that a server can be deployed in from Linode
  91. :param keyring: a daemon.DaemonKeyRing implementer that is able to return a linode API key
  92. */
  93. func (ln LinodeConnection) GetRegions() (RegionsResponse, error) {
  94. var regions RegionsResponse
  95. b, err := ln.Get(LinodeRegions)
  96. if err != nil {
  97. return regions, err
  98. }
  99. err = json.Unmarshal(b, &regions)
  100. if err != nil {
  101. return regions, err
  102. }
  103. return regions, nil
  104. }
  105. /*
  106. Get all of the available image types from linode
  107. :param keyring: a daemon.DaemonKeyRing interface implementer. Responsible for getting the linode API key
  108. */
  109. func (ln LinodeConnection) GetImages() (ImagesResponse, error) {
  110. var imgResp ImagesResponse
  111. b, err := ln.Get(LinodeImages)
  112. if err != nil {
  113. return imgResp, err
  114. }
  115. err = json.Unmarshal(b, &imgResp)
  116. if err != nil {
  117. return imgResp, &LinodeClientError{Msg: err.Error()}
  118. }
  119. return imgResp, nil
  120. }
  121. /*
  122. Get all of the available Linode types from linode
  123. :param keyring: a daemon.DaemonKeyRing interface implementer. Responsible for getting the linode API key
  124. */
  125. func (ln LinodeConnection) GetTypes() (TypesResponse, error) {
  126. var typesResp TypesResponse
  127. b, err := ln.Get(LinodeTypes)
  128. if err != nil {
  129. return typesResp, err
  130. }
  131. err = json.Unmarshal(b, &typesResp)
  132. if err != nil {
  133. return typesResp, &LinodeClientError{Msg: err.Error()}
  134. }
  135. return typesResp, nil
  136. }
  137. /*
  138. Get a Linode by its ID, used for assertion when deleting an old linode
  139. */
  140. func (ln LinodeConnection) GetLinode(id string) (GetLinodeResponse, error) {
  141. var getLnResp GetLinodeResponse
  142. b, err := ln.Get(fmt.Sprintf("%s/%s", LinodeInstances, id))
  143. if err != nil {
  144. return getLnResp, err
  145. }
  146. err = json.Unmarshal(b, &getLnResp)
  147. if err != nil {
  148. return getLnResp, &LinodeClientError{Msg: err.Error()}
  149. }
  150. return getLnResp, nil
  151. }
  152. /*
  153. List all linodes on your account
  154. :param keyring: a daemon.DaemonKeyRing implementer that can return the linode API key
  155. */
  156. func (ln LinodeConnection) ListLinodes() (GetAllLinodes, error) {
  157. var allLinodes GetAllLinodes
  158. b, err := ln.Get(LinodeInstances)
  159. if err != nil {
  160. return allLinodes, err
  161. }
  162. err = json.Unmarshal(b, &allLinodes)
  163. if err != nil {
  164. return allLinodes, &LinodeClientError{Msg: err.Error()}
  165. }
  166. return allLinodes, nil
  167. }
  168. /*
  169. Get linode by IP Address
  170. :param addr: the IPv4 address of your linode
  171. */
  172. func (ln LinodeConnection) GetByIp(addr string) (GetLinodeResponse, error) {
  173. var out GetLinodeResponse
  174. servers, err := ln.ListLinodes()
  175. if err != nil {
  176. return out, err
  177. }
  178. for i := range servers.Data {
  179. if servers.Data[i].Ipv4[0] == addr {
  180. return servers.Data[i], nil
  181. }
  182. }
  183. return out, &LinodeClientError{Msg: "Linode with Address of: " + addr + " not found."}
  184. }
  185. /*
  186. Get a linode by its name/label
  187. :param name: the name/label of the linode
  188. */
  189. func (ln LinodeConnection) GetByName(name string) (GetLinodeResponse, error) {
  190. var out GetLinodeResponse
  191. servers, err := ln.ListLinodes()
  192. if err != nil {
  193. return out, err
  194. }
  195. for i := range servers.Data {
  196. if servers.Data[i].Label == name {
  197. return servers.Data[i], nil
  198. }
  199. }
  200. return out, &LinodeClientError{Msg: "Linode with name: " + name + " not found."}
  201. }
  202. /*
  203. Create a new linode instance
  204. :param keyring: a daemon.DaemonKeyRing implementer that can return a linode API key
  205. :param body: the request body for the new linode request
  206. */
  207. func (ln LinodeConnection) CreateNewLinode(body NewLinodeBody) (GetLinodeResponse, error) {
  208. var newLnResp GetLinodeResponse
  209. reqBody, err := json.Marshal(&body)
  210. if err != nil {
  211. return newLnResp, err
  212. }
  213. apiKey, err := ln.Keyring.GetKey(ln.KeyTagger.LinodeApiKeyname())
  214. if err != nil {
  215. return newLnResp, &LinodeClientError{Msg: err.Error()}
  216. }
  217. req, err := http.NewRequest("POST", fmt.Sprintf("https://%s/%s/%s", LinodeApiUrl, LinodeApiVers, LinodeInstances), bytes.NewReader(reqBody))
  218. req.Header.Add("Authorization", apiKey.Prepare())
  219. req.Header.Add("Content-Type", "application/json")
  220. resp, err := ln.Client.Do(req)
  221. if err != nil {
  222. return newLnResp, err
  223. }
  224. defer resp.Body.Close()
  225. b, err := io.ReadAll(resp.Body)
  226. if err != nil {
  227. return newLnResp, &LinodeClientError{Msg: err.Error()}
  228. }
  229. if resp.StatusCode != 200 {
  230. return newLnResp, &LinodeClientError{Msg: resp.Status + "\n" + string(b)}
  231. }
  232. err = json.Unmarshal(b, &newLnResp)
  233. if err != nil {
  234. return newLnResp, &LinodeClientError{Msg: err.Error()}
  235. }
  236. return newLnResp, nil
  237. }
  238. /*
  239. Delete a linode instance. Internally, this function will check that the linode ID exists before deleting
  240. :param id: the id of the linode.
  241. */
  242. func (ln LinodeConnection) DeleteLinode(id string) error {
  243. _, err := ln.GetLinode(id)
  244. if err != nil {
  245. return &LinodeClientError{Msg: err.Error()}
  246. }
  247. _, err = ln.Delete(fmt.Sprintf("%s/%s", LinodeInstances, id))
  248. if err != nil {
  249. return &LinodeClientError{Msg: err.Error()}
  250. }
  251. return nil
  252. }
  253. /*
  254. Agnostic GET method for calling the upstream linode server
  255. :param keyring: a daemon.DaemonKeyRing implementer to get the linode API key from
  256. :param path: the path to GET, added into the base API url
  257. */
  258. func (ln LinodeConnection) Get(path string) ([]byte, error) {
  259. var b []byte
  260. apiKey, err := ln.Keyring.GetKey(ln.KeyTagger.LinodeApiKeyname())
  261. if err != nil {
  262. return b, &LinodeClientError{Msg: err.Error()}
  263. }
  264. req, err := http.NewRequest("GET", fmt.Sprintf("https://%s/%s/%s", LinodeApiUrl, LinodeApiVers, strings.TrimPrefix(path, "/")), nil)
  265. if err != nil {
  266. return b, &LinodeClientError{Msg: err.Error()}
  267. }
  268. req.Header.Add("Authorization", apiKey.Prepare())
  269. resp, err := ln.Client.Do(req)
  270. if err != nil {
  271. return b, &LinodeClientError{Msg: err.Error()}
  272. }
  273. defer resp.Body.Close()
  274. b, err = io.ReadAll(resp.Body)
  275. if err != nil {
  276. return b, &LinodeClientError{Msg: err.Error()}
  277. }
  278. return b, nil
  279. }
  280. /*
  281. Agnostic DELETE method for deleting a resource from Linode
  282. :param keyring: a daemon.DaemonKeyRing implementer for getting the linode API key
  283. :param path: the path to perform the DELETE method on
  284. */
  285. func (ln LinodeConnection) Delete(path string) ([]byte, error) {
  286. var b []byte
  287. apiKey, err := ln.Keyring.GetKey(ln.KeyTagger.LinodeApiKeyname())
  288. if err != nil {
  289. return b, &LinodeClientError{Msg: err.Error()}
  290. }
  291. req, err := http.NewRequest("DELETE", fmt.Sprintf("https://%s/%s/%s", LinodeApiUrl, LinodeApiVers, strings.TrimPrefix(path, "/")), nil)
  292. if err != nil {
  293. return b, &LinodeClientError{Msg: err.Error()}
  294. }
  295. req.Header.Add("Authorization", apiKey.Prepare())
  296. resp, err := ln.Client.Do(req)
  297. if err != nil {
  298. return b, &LinodeClientError{Msg: err.Error()}
  299. }
  300. defer resp.Body.Close()
  301. b, err = io.ReadAll(resp.Body)
  302. if err != nil {
  303. return b, &LinodeClientError{Msg: err.Error()}
  304. }
  305. return b, nil
  306. }
  307. /*
  308. Poll for new server creation
  309. :param name: the IPv4 address of the linode server
  310. :param max_tries: the number of calls the client will send to linode before exiting
  311. */
  312. func (ln LinodeConnection) ServerPoll(name string, max_tries int) error {
  313. var count int
  314. for {
  315. count = count + 1
  316. if count > max_tries {
  317. return &LinodeTimeOutError{Tries: max_tries}
  318. }
  319. ln.Config.Log("Polling for server status times: ", fmt.Sprint(count))
  320. resp, err := ln.GetByName(name)
  321. if err != nil {
  322. return err
  323. }
  324. if resp.Status == "running" {
  325. ln.Config.Log("Server: ", resp.Ipv4[0], " showing as: ", resp.Status)
  326. return nil
  327. }
  328. ln.Config.Log("Server inactive, showing status: ", resp.Status)
  329. time.Sleep(time.Second * 3)
  330. }
  331. }
  332. /*
  333. Bootstrap the cloud environment
  334. */
  335. func (ln LinodeConnection) Bootstrap() error { return nil }
  336. /*
  337. ############################################
  338. ########### DAEMON EVENT HANDLERS ##########
  339. ############################################
  340. */
  341. type DeleteLinodeRequest struct {
  342. Id string `json:"id"`
  343. }
  344. type AddLinodeRequest struct {
  345. Name string `json:"name"`
  346. }
  347. type PollLinodeRequest struct {
  348. Address string `json:"address"`
  349. }
  350. func (ln LinodeConnection) DeleteLinodeHandler(msg daemon.SockMessage) daemon.SockMessage {
  351. resp, err := ln.GetByName(ln.Config.ServerName())
  352. if err != nil {
  353. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  354. }
  355. err = ln.DeleteLinode(fmt.Sprint(resp.Id))
  356. if err != nil {
  357. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_ACCEPTED, []byte(err.Error()))
  358. }
  359. responseMessage := []byte("Server: " + ln.Config.ServerName() + " was deleted.")
  360. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, responseMessage)
  361. }
  362. /*
  363. Wraps the creation of a linode to make the LinodeRouter function slimmer
  364. :param msg: a daemon.SockMessage struct with request info
  365. */
  366. func (ln LinodeConnection) AddLinodeHandler(msg daemon.SockMessage) daemon.SockMessage {
  367. var payload AddLinodeRequest
  368. err := json.Unmarshal(msg.Body, &payload)
  369. if err != nil {
  370. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  371. }
  372. newLinodeReq, err := NewLinodeBodyBuilder(ln.Config.Image(),
  373. ln.Config.Region(),
  374. ln.Config.LinodeType(),
  375. ln.Config.ServerName(),
  376. ln.Keyring)
  377. if err != nil {
  378. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  379. }
  380. resp, err := ln.CreateNewLinode(newLinodeReq)
  381. if err != nil {
  382. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  383. }
  384. ln.Config.SetVpnServer(resp.Ipv4[0])
  385. ln.Config.SetVpnServerId(resp.Id)
  386. b, _ := json.Marshal(resp)
  387. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, b)
  388. }
  389. /*
  390. Wraps the polling feature of the client in a Handler function
  391. :param msg: a daemon.SockMessage that contains the request info
  392. */
  393. func (ln LinodeConnection) PollLinodeHandler(msg daemon.SockMessage) daemon.SockMessage {
  394. err := ln.ServerPoll(ln.Config.ServerName(), 15)
  395. if err != nil {
  396. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_TIMEOUT, []byte(err.Error()))
  397. }
  398. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, []byte("Server is running."))
  399. }
  400. /*
  401. Handles the routing for each method that can be performed on the cloud target
  402. :param msg: a daemon.SockMessage with request details
  403. */
  404. func (ln LinodeConnection) LinodeRouter(msg daemon.SockMessage) daemon.SockMessage {
  405. switch msg.Method {
  406. case "show":
  407. servers, err := ln.ListLinodes()
  408. if err != nil {
  409. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  410. }
  411. b, _ := json.Marshal(servers)
  412. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, b)
  413. case "delete":
  414. return ln.DeleteLinodeHandler(msg)
  415. case "add":
  416. return ln.AddLinodeHandler(msg)
  417. case "poll":
  418. return ln.PollLinodeHandler(msg)
  419. }
  420. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_UNRESOLVED, []byte("Unresolved Action"))
  421. }
  422. /*
  423. #####################
  424. ####### ERRORS ######
  425. #####################
  426. */
  427. type LinodeClientError struct {
  428. Msg string
  429. }
  430. func (ln *LinodeClientError) Error() string {
  431. return fmt.Sprintf("There was an error calling linode: '%s'", ln.Msg)
  432. }
  433. type LinodeTimeOutError struct {
  434. Tries int
  435. }
  436. func (ln *LinodeTimeOutError) Error() string {
  437. return "Polling timed out after: " + fmt.Sprint(ln.Tries) + " attempts"
  438. }