client.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. package semaphore
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "git.aetherial.dev/aeth/yosai/pkg/daemon"
  12. "git.aetherial.dev/aeth/yosai/pkg/keytags"
  13. "gopkg.in/yaml.v3"
  14. )
  15. const ProjectsPath = "api/projects"
  16. const ProjectPath = "api/project"
  17. const YosaiProject = "Yosai VPN Sentinel"
  18. const YosaiServerInventory = "Yosai VPN Servers"
  19. const YosaiVpnRotationJob = "VPN Rotation playbook"
  20. const YosaiEnvironment = "VPN Server configuration environment variables"
  21. type SemaphoreConnection struct {
  22. Client *http.Client
  23. Keyring daemon.DaemonKeyRing
  24. KeyTagger keytags.Keytagger
  25. Config daemon.Configuration
  26. ServerUrl string
  27. HttpProto string
  28. ProjectId int
  29. }
  30. type TaskInfo struct {
  31. ID int `json:"id"`
  32. TemplateID int `json:"template_id"`
  33. Status string `json:"status"`
  34. Debug bool `json:"debug"`
  35. Playbook string `json:"playbook"`
  36. Environment string `json:"environment"`
  37. Secret string `json:"secret"`
  38. Limit string `json:"limit"`
  39. }
  40. type TaskOutput struct {
  41. TaskID int `json:"task_id"`
  42. Task string `json:"task"`
  43. Time time.Time `json:"time"`
  44. Output string `json:"output"`
  45. }
  46. type NewTemplateRequest struct {
  47. ProjectId int `json:"project_id"`
  48. Name string `json:"name"`
  49. InventoryId int `json:"inventory_id"`
  50. RepositoryId int `json:"repository_id"`
  51. EnvironmentId int `json:"environment_id"`
  52. Playbook string `json:"playbook"`
  53. Type string `json:"type"`
  54. }
  55. type JobTemplate struct {
  56. Id int `json:"id"`
  57. ProjectId int `json:"project_id"`
  58. Name string `json:"name"`
  59. InventoryId int `json:"inventory_id"`
  60. RepositoryId int `json:"repository_id"`
  61. EnvironmentId int `json:"environment_id"`
  62. Playbook string `json:"playbook"`
  63. }
  64. type StartTaskRequest struct {
  65. TemplateID int `json:"template_id"`
  66. ProjectId int `json:"project_id"`
  67. }
  68. type StartTaskResponse struct {
  69. Id int `json:"id"`
  70. TemplateID int `json:"template_id"`
  71. Debug bool `json:"debug"`
  72. DryRun bool `json:"dry_run"`
  73. Diff bool `json:"diff"`
  74. Playbook string `json:"playbook"`
  75. Environment string `json:"environment"`
  76. Limit string `json:"limit"`
  77. }
  78. type EnvironmentVariables struct {
  79. SecretsProviderUrl string `json:"SECRETS_PROVIDER_URL"`
  80. SecretsProviderApiKey string `json:"SECRETS_PROVIDER_API_KEY"`
  81. }
  82. type AddEnvironmentRequest struct {
  83. Name string `json:"name"`
  84. ProjectID int `json:"project_id"`
  85. Password string `json:"password"`
  86. JSON string `json:"json"`
  87. Env string `json:"env"`
  88. }
  89. type EnvironmentResponse struct {
  90. Id int `json:"id"`
  91. Name string `json:"name"`
  92. ProjectID int `json:"project_id"`
  93. Password string `json:"password"`
  94. JSON string `json:"json"`
  95. Env string `json:"env"`
  96. }
  97. type ProjectsResponse struct {
  98. Id int `json:"id"`
  99. Name string `json:"name"`
  100. Created string `json:"created"`
  101. Alert bool `json:"alert"`
  102. AlertChat string `json:"alert_chat"`
  103. MaxParallelTasks int `json:"max_parallel_tasks"`
  104. }
  105. type NewProjectReqeust struct {
  106. Name string `json:"name"`
  107. Alert bool `json:"alert"`
  108. AlertChat string `json:"alert_chat"`
  109. MaxParallelTasks int `json:"max_parallel_tasks"`
  110. }
  111. type NewRepoRequest struct {
  112. Name string `json:"name"` // name of the project
  113. ProjectId int `json:"project_id"` // the numerical ID of the project as per /api/project/<project id>
  114. GitUrl string `json:"git_url"` // the URL of the git repo (SSH address)
  115. GitBranch string `json:"git_branch"` // the branch to pull down
  116. SshKeyId int `json:"ssh_key_id"` // the numerical ID of the ssh key for the repository, as per /api/project/<project id>/keys
  117. }
  118. type NewRepoResponse struct {
  119. Id int `json:"id"` // the numerical ID assigned to the repo by Semaphore
  120. Name string `json:"name"` // name of the project
  121. ProjectId int `json:"project_id"` // the numerical ID of the project as per /api/project/<project id>
  122. GitUrl string `json:"git_url"` // the URL of the git repo (SSH address)
  123. GitBranch string `json:"git_branch"` // the branch to pull down
  124. SshKeyId int `json:"ssh_key_id"` // the numerical ID of the ssh key for the repository, as per /api/project/<project id>/keys
  125. }
  126. type AddKeyRequest struct {
  127. Name string `json:"name"`
  128. Type string `json:"type"`
  129. ProjectId int `json:"project_id"`
  130. LoginPassword loginPassword `json:"login_password"`
  131. Ssh sshKeyAdd `json:"ssh"`
  132. }
  133. func (a AddKeyRequest) GetPublic() string {
  134. if a.Type == "ssh" {
  135. return a.Ssh.Login
  136. } else {
  137. return a.LoginPassword.Login
  138. }
  139. }
  140. func (a AddKeyRequest) GetSecret() string {
  141. if a.Type == "ssh" {
  142. return a.Ssh.PrivateKey
  143. } else {
  144. return a.LoginPassword.Password
  145. }
  146. }
  147. func (a AddKeyRequest) Prepare() string {
  148. b, err := json.Marshal(a)
  149. if err != nil {
  150. return err.Error()
  151. }
  152. return string(b)
  153. }
  154. func (a AddKeyRequest) GetType() string {
  155. return a.Type
  156. }
  157. type KeyItemResponse struct {
  158. Id int `json:"id"`
  159. Name string `json:"name"`
  160. Type string `json:"type"`
  161. ProjectId int `json:"project_id"`
  162. LoginPassword loginPassword `json:"login_password"`
  163. Ssh sshKeyAdd `json:"ssh"`
  164. }
  165. type NewInventoryRequest struct {
  166. Name string `json:"name"`
  167. ProjectId int `json:"project_id"`
  168. Inventory string `json:"inventory"` // This field is where the YAML inventory file gets put, as a string (not a filepath!)
  169. Type string `json:"type"`
  170. SshKeyId int `json:"ssh_key_id"`
  171. BecomeKeyId int `json:"become_key_id"`
  172. }
  173. type InventoryResponse struct {
  174. Id int `json:"id"`
  175. Inventory string `json:"inventory"`
  176. Name string `json:"name"`
  177. ProjectId int `json:"project_id"`
  178. Type string `json:"type"`
  179. SshKeyId int `json:"ssh_key_id"`
  180. BecomeKeyId int `json:"become_key_id"`
  181. }
  182. /*
  183. ####################################################################
  184. ############ IMPLEMENTING daemon.Key FOR KeyItemResponse ###########
  185. ####################################################################
  186. */
  187. func (k KeyItemResponse) GetPublic() string {
  188. return k.Ssh.Login
  189. }
  190. func (k KeyItemResponse) GetSecret() string {
  191. return k.Ssh.PrivateKey
  192. }
  193. func (k KeyItemResponse) Prepare() string {
  194. return k.Type
  195. }
  196. func (k KeyItemResponse) GetType() string {
  197. return k.Type
  198. }
  199. type loginPassword struct {
  200. Password string `json:"password"`
  201. Login string `json:"login"`
  202. }
  203. type sshKeyAdd struct {
  204. PrivateKey string `json:"private_key"`
  205. Login string `json:"login"`
  206. }
  207. /*
  208. ###################################################################
  209. ########### IMPLEMENTING THE DaemonKeyRing INTERFACE ##############
  210. ###################################################################
  211. */
  212. /*
  213. Get SSH key by its name
  214. */
  215. func (s SemaphoreConnection) GetKey(name string) (daemon.Key, error) {
  216. var key KeyItemResponse
  217. keys, err := s.GetAllKeys()
  218. if err != nil {
  219. return key, daemon.KeyRingError
  220. }
  221. for i := range keys {
  222. if keys[i].Name == name {
  223. return keys[i], nil
  224. }
  225. }
  226. return key, daemon.KeyNotFound
  227. }
  228. /*
  229. Add SSH Key to a project
  230. :param name: the name to assign the key in the project
  231. :param keyring: a daemon.DaemonKeyRing implementer that can return the API key for Semaphore
  232. :param key: a daemon.Key implementer wrapping the SSH key
  233. */
  234. func (s SemaphoreConnection) AddKey(name string, key daemon.Key) error {
  235. _, err := s.GetKeyId(name)
  236. if err == nil { // return if the key exists
  237. return nil
  238. }
  239. path := fmt.Sprintf("%s/%v/keys", ProjectPath, s.ProjectId)
  240. _, err = s.Post(path, bytes.NewReader([]byte(key.Prepare())))
  241. if err != nil {
  242. return err
  243. }
  244. return nil
  245. }
  246. /*
  247. Drop a key from the Semaphore secret store
  248. */
  249. func (s SemaphoreConnection) RemoveKey(name string) error {
  250. _, err := s.Delete(name)
  251. return err
  252. }
  253. // Return the resource name for logging purposes
  254. func (s SemaphoreConnection) Source() string {
  255. return "Semaphore Keystore"
  256. }
  257. // NewKeyRequest builder function
  258. func (s SemaphoreConnection) NewKeyRequestBuilder(name string, key daemon.Key) daemon.Key {
  259. if key.GetType() == "ssh" {
  260. return AddKeyRequest{
  261. Name: name,
  262. Type: key.GetType(),
  263. ProjectId: s.ProjectId,
  264. Ssh: sshKeyAdd{
  265. Login: key.GetPublic(),
  266. PrivateKey: key.GetSecret(),
  267. },
  268. }
  269. } else {
  270. return AddKeyRequest{
  271. Name: name,
  272. Type: key.GetType(),
  273. ProjectId: s.ProjectId,
  274. LoginPassword: loginPassword{
  275. Login: key.GetPublic(),
  276. Password: key.GetSecret(),
  277. },
  278. }
  279. }
  280. }
  281. /*
  282. Create a new semaphore client
  283. :param url: the base url of the semaphore server, without the HTTP/S prefix
  284. :param proto: either HTTP or HTTPS, depending on the server's SSL setup
  285. :param log: an io.Writer to write logfile to
  286. :param keyring: a daemon.DaemonKeyRing implementer to get the Semaphore API key from
  287. */
  288. func NewSemaphoreClient(url string, proto string, log io.Writer, keyring daemon.DaemonKeyRing, conf daemon.Configuration, keytagger keytags.Keytagger) SemaphoreConnection {
  289. log.Write([]byte("Using HTTP mode: " + proto + "\n"))
  290. client := &http.Client{}
  291. semaphoreBootstrap := SemaphoreConnection{Client: client, ServerUrl: url, HttpProto: proto, Keyring: keyring, KeyTagger: keytagger}
  292. id, err := semaphoreBootstrap.GetProjectByName(YosaiProject)
  293. if err != nil {
  294. log.Write([]byte(YosaiProject + " NOT FOUND IN SEMAPHORE. Creating..."))
  295. err = semaphoreBootstrap.NewProject(YosaiProject)
  296. if err != nil {
  297. log.Write([]byte("FATAL ERROR CREATING PROJECT. ABANDONING SHIP. Error: " + err.Error()))
  298. }
  299. id, _ = semaphoreBootstrap.GetProjectByName(YosaiProject)
  300. log.Write([]byte("Found " + YosaiProject + " with project id: " + fmt.Sprint(id)))
  301. return SemaphoreConnection{
  302. Client: client,
  303. ServerUrl: url,
  304. HttpProto: proto,
  305. ProjectId: id,
  306. Keyring: keyring,
  307. Config: conf,
  308. KeyTagger: keytagger,
  309. }
  310. }
  311. return SemaphoreConnection{
  312. Client: &http.Client{},
  313. ServerUrl: url,
  314. HttpProto: proto,
  315. ProjectId: id,
  316. Keyring: keyring,
  317. Config: conf,
  318. KeyTagger: keytagger,
  319. }
  320. }
  321. /*
  322. Create a new 'Project' in Semaphore
  323. :param name: the name to assign the project
  324. :param keyring: a daemon.DaemonKeyRing implementer to get the Semaphore API key from
  325. */
  326. func (s SemaphoreConnection) NewProject(name string) error {
  327. _, err := s.GetProjectByName(name)
  328. if err == nil {
  329. return nil // return nil of project already exists
  330. }
  331. var b []byte
  332. newProj := NewProjectReqeust{
  333. Name: name,
  334. Alert: false,
  335. AlertChat: "",
  336. MaxParallelTasks: 0,
  337. }
  338. b, err = json.Marshal(&newProj)
  339. if err != nil {
  340. return &SemaphoreClientError{Msg: err.Error()}
  341. }
  342. _, err = s.Post(ProjectsPath, bytes.NewReader(b))
  343. if err != nil {
  344. return err
  345. }
  346. return nil
  347. }
  348. /*
  349. Add a repository to the project designated for the Yosai service
  350. :param giturl: the url for the git repo containing the ansible scripts for VPN server config
  351. :param branch: the branch to target on the git repo
  352. */
  353. func (s SemaphoreConnection) AddRepository(giturl string, branch string) error {
  354. _, err := s.GetRepoByName(fmt.Sprintf("%s:%s", giturl, branch))
  355. if err == nil { // return if the repo exists
  356. return nil
  357. }
  358. sshKeyId, err := s.GetKeyId(s.KeyTagger.GitSshKeyname())
  359. if err != nil {
  360. return err
  361. }
  362. repoAddRequest := NewRepoRequest{
  363. Name: fmt.Sprintf("%s:%s", giturl, branch),
  364. ProjectId: s.ProjectId,
  365. GitUrl: giturl,
  366. GitBranch: branch,
  367. SshKeyId: sshKeyId,
  368. }
  369. b, err := json.Marshal(&repoAddRequest)
  370. if err != nil {
  371. return &SemaphoreClientError{Msg: err.Error()}
  372. }
  373. _, err = s.Post(fmt.Sprintf("%s/%v/repositories", ProjectPath, s.ProjectId), bytes.NewReader(b))
  374. if err != nil {
  375. return err
  376. }
  377. return nil
  378. }
  379. /*
  380. Generic POST Request to sent to the Semaphore server
  381. :param path: the path to the API to POST. Preceeding slashes will be trimmed
  382. :param body: an io.Reader implementer to use as the POST body. Must comply with application/json Content-Type
  383. */
  384. func (s SemaphoreConnection) Put(path string, body io.Reader) ([]byte, error) {
  385. var b []byte
  386. apikey, err := s.Keyring.GetKey(s.KeyTagger.SemaphoreApiKeyname())
  387. if err != nil {
  388. return b, &SemaphoreClientError{Msg: err.Error()}
  389. }
  390. req, err := http.NewRequest(http.MethodPut, fmt.Sprintf("%s://%s/%s", s.HttpProto, s.ServerUrl, strings.TrimPrefix(path, "/")), body)
  391. if err != nil {
  392. return b, &SemaphoreClientError{Msg: err.Error()}
  393. }
  394. req.Header.Add("Authorization", apikey.Prepare())
  395. req.Header.Add("Content-Type", "application/json")
  396. resp, err := s.Client.Do(req)
  397. if err != nil {
  398. return b, &SemaphoreClientError{Msg: err.Error()}
  399. }
  400. defer resp.Body.Close()
  401. if resp.StatusCode >= 400 {
  402. return b, &SemaphoreClientError{Msg: resp.Status}
  403. }
  404. b, err = io.ReadAll(resp.Body)
  405. if err != nil {
  406. return b, &SemaphoreClientError{Msg: err.Error()}
  407. }
  408. return b, nil
  409. }
  410. /*
  411. Generic POST Request to sent to the Semaphore server
  412. :param path: the path to the API to POST. Preceeding slashes will be trimmed
  413. :param body: an io.Reader implementer to use as the POST body. Must comply with application/json Content-Type
  414. */
  415. func (s SemaphoreConnection) Post(path string, body io.Reader) ([]byte, error) {
  416. var b []byte
  417. apikey, err := s.Keyring.GetKey(s.KeyTagger.SemaphoreApiKeyname())
  418. if err != nil {
  419. return b, &SemaphoreClientError{Msg: err.Error()}
  420. }
  421. req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s://%s/%s", s.HttpProto, s.ServerUrl, strings.TrimPrefix(path, "/")), body)
  422. if err != nil {
  423. return b, &SemaphoreClientError{Msg: err.Error()}
  424. }
  425. req.Header.Add("Authorization", apikey.Prepare())
  426. req.Header.Add("Content-Type", "application/json")
  427. resp, err := s.Client.Do(req)
  428. if err != nil {
  429. return b, &SemaphoreClientError{Msg: err.Error()}
  430. }
  431. defer resp.Body.Close()
  432. b, err = io.ReadAll(resp.Body)
  433. if err != nil {
  434. return b, &SemaphoreClientError{Msg: err.Error()}
  435. }
  436. if resp.StatusCode >= 400 {
  437. return b, &SemaphoreClientError{Msg: resp.Status}
  438. }
  439. return b, nil
  440. }
  441. /*
  442. Agnostic GET method for calling the upstream Semaphore server
  443. :param path: the path to GET, added into the base API url
  444. */
  445. func (s SemaphoreConnection) Get(path string) ([]byte, error) {
  446. var b []byte
  447. apiKey, err := s.Keyring.GetKey(s.KeyTagger.SemaphoreApiKeyname())
  448. if err != nil {
  449. return b, &SemaphoreClientError{Msg: err.Error()}
  450. }
  451. req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s://%s/%s", s.HttpProto, s.ServerUrl, strings.TrimPrefix(path, "/")), nil)
  452. if err != nil {
  453. return b, &SemaphoreClientError{Msg: err.Error()}
  454. }
  455. req.Header.Add("Authorization", apiKey.Prepare())
  456. resp, err := s.Client.Do(req)
  457. if err != nil {
  458. return b, &SemaphoreClientError{Msg: err.Error()}
  459. }
  460. defer resp.Body.Close()
  461. b, err = io.ReadAll(resp.Body)
  462. if err != nil {
  463. return b, &SemaphoreClientError{Msg: err.Error()}
  464. }
  465. return b, nil
  466. }
  467. /*
  468. Generic DELETE method for calling the Semaphore server
  469. */
  470. func (s SemaphoreConnection) Delete(path string) ([]byte, error) {
  471. return []byte{}, nil
  472. }
  473. /*
  474. Retrieve the projects in Semaphore
  475. :param keyring: a daemon.DaemonKeyRing implementer to get the API key from for Semaphore
  476. */
  477. func (s SemaphoreConnection) GetProjects() ([]ProjectsResponse, error) {
  478. var projectsResp []ProjectsResponse
  479. b, err := s.Get(ProjectsPath)
  480. if err != nil {
  481. return projectsResp, err
  482. }
  483. err = json.Unmarshal(b, &projectsResp)
  484. if err != nil {
  485. return projectsResp, &SemaphoreClientError{Msg: err.Error()}
  486. }
  487. return projectsResp, nil
  488. }
  489. /*
  490. Get Project by its name, and return its ID
  491. */
  492. func (s SemaphoreConnection) GetProjectByName(name string) (int, error) {
  493. projects, err := s.GetProjects()
  494. if err != nil {
  495. return 0, err
  496. }
  497. for i := range projects {
  498. if projects[i].Name == name {
  499. return projects[i].Id, nil
  500. }
  501. }
  502. return 0, &SemaphoreClientError{Msg: fmt.Sprintf("Project with name: '%s' not found.", name)}
  503. }
  504. /*
  505. Get SSH Keys from the current project
  506. */
  507. func (s SemaphoreConnection) GetAllKeys() ([]KeyItemResponse, error) {
  508. var keys []KeyItemResponse
  509. b, err := s.Get(fmt.Sprintf("%s/%v/keys", ProjectPath, s.ProjectId))
  510. if err != nil {
  511. return keys, err
  512. }
  513. err = json.Unmarshal(b, &keys)
  514. if err != nil {
  515. return keys, &SemaphoreClientError{Msg: err.Error()}
  516. }
  517. return keys, nil
  518. }
  519. /*
  520. Return a key ID from the Semaphore keystore by it's name
  521. :param keyname: the name of the key in Semaphore
  522. */
  523. func (s SemaphoreConnection) GetKeyId(keyname string) (int, error) {
  524. keys, err := s.GetAllKeys()
  525. if err != nil {
  526. return 0, err
  527. }
  528. for i := range keys {
  529. if keys[i].Name == keyname {
  530. return keys[i].Id, nil
  531. }
  532. }
  533. return 0, &KeyNotFound{Keyname: keyname}
  534. }
  535. /*
  536. Get the output of a task
  537. :param taskId: the ID of the task that was ran
  538. */
  539. func (s SemaphoreConnection) GetTaskOutput(taskId int) ([]TaskOutput, error) {
  540. var taskout []TaskOutput
  541. b, err := s.Get(fmt.Sprintf("%s/%v/tasks/%v/output", ProjectPath, s.ProjectId, taskId))
  542. if err != nil {
  543. return taskout, err
  544. }
  545. err = json.Unmarshal(b, &taskout)
  546. if err != nil {
  547. return taskout, &SemaphoreClientError{Msg: "Could not unmarshall the response from getting task output." + err.Error()}
  548. }
  549. return taskout, nil
  550. }
  551. /*
  552. Get information relating to a task
  553. :param taskId: the ID of the task that was ran
  554. */
  555. func (s SemaphoreConnection) GetTaskInfo(taskId int) (TaskInfo, error) {
  556. var taskout TaskInfo
  557. b, err := s.Get(fmt.Sprintf("%s/%v/tasks/%v", ProjectPath, s.ProjectId, taskId))
  558. if err != nil {
  559. return taskout, err
  560. }
  561. err = json.Unmarshal(b, &taskout)
  562. if err != nil {
  563. return taskout, &SemaphoreClientError{Msg: "Could not unmarshall the response from getting task output." + err.Error()}
  564. }
  565. return taskout, nil
  566. }
  567. /*
  568. Poll for task completion
  569. :param taskId: the ID of the task to be polled
  570. :param max_tries: the number of times to poll the running task before timing out
  571. */
  572. func (s SemaphoreConnection) PollTask(taskId int, max_tries int) error {
  573. var attempts int
  574. for {
  575. attempts = attempts + 1
  576. s.Config.Log("Polling task: ", fmt.Sprint(taskId), " for ", fmt.Sprint(attempts), " times.")
  577. if attempts > max_tries {
  578. s.Config.Log("Polling for job completion timed out after: ", fmt.Sprint(attempts), " attempts.")
  579. return &SemaphoreTimeout{Tries: attempts}
  580. }
  581. resp, err := s.GetTaskInfo(taskId)
  582. if err != nil {
  583. return err
  584. }
  585. s.Config.Log("Job: ", fmt.Sprint(taskId), " is marked with status: ", resp.Status)
  586. if resp.Status == "success" {
  587. return nil
  588. }
  589. if resp.Status == "error" {
  590. return &SemaphoreTimeout{Tries: attempts}
  591. }
  592. time.Sleep(time.Second * 5)
  593. }
  594. }
  595. /*
  596. Add an inventory to semaphore
  597. :param hosts: a list of IP addresses to add to the inventory
  598. */
  599. func (s SemaphoreConnection) AddInventory(name string, hosts ...string) error {
  600. _, err := s.GetInventoryByName(name)
  601. if err == nil { // Returning on nil error because that means the inventory exists
  602. return &SemaphoreClientError{Msg: "Inventory Exists! Please update rather than create a new."}
  603. }
  604. sshKeyId, err := s.GetKeyId(s.KeyTagger.VpsSvcAccSshPubkeySeed())
  605. if err != nil {
  606. return err
  607. }
  608. becomeKeyId, err := s.GetKeyId(s.KeyTagger.VpsSvcAccKeyname())
  609. if err != nil {
  610. return err
  611. }
  612. pubkey, err := s.Keyring.GetKey(s.KeyTagger.WgClientKeypairKeyname())
  613. if err != nil {
  614. return &SemaphoreClientError{Msg: err.Error() + s.KeyTagger.WgClientKeypairKeyname()}
  615. }
  616. inv := s.YamlInventoryBuilder(hosts, pubkey.GetPublic())
  617. b, err := yaml.Marshal(inv)
  618. if err != nil {
  619. return &SemaphoreClientError{Msg: err.Error()}
  620. }
  621. body := NewInventoryRequest{
  622. Name: name,
  623. ProjectId: s.ProjectId,
  624. Inventory: string(b),
  625. SshKeyId: sshKeyId,
  626. BecomeKeyId: becomeKeyId,
  627. Type: "static-yaml",
  628. }
  629. requestBody, err := json.Marshal(&body)
  630. if err != nil {
  631. return &SemaphoreClientError{Msg: err.Error()}
  632. }
  633. _, err = s.Post(fmt.Sprintf("%s/%v/%s", ProjectPath, s.ProjectId, "inventory"), bytes.NewReader(requestBody))
  634. return err
  635. }
  636. /*
  637. Get Inventory by name and return its ID
  638. :param name: the name of the inventory to find
  639. */
  640. func (s SemaphoreConnection) GetInventoryByName(name string) (InventoryResponse, error) {
  641. var out InventoryResponse
  642. resp, err := s.GetAllInventories()
  643. if err != nil {
  644. return out, err
  645. }
  646. for i := range resp {
  647. if resp[i].Name == name {
  648. return resp[i], nil
  649. }
  650. }
  651. return out, &KeyNotFound{Keyname: name}
  652. }
  653. /*
  654. Get all inventories from Semaphore
  655. */
  656. func (s SemaphoreConnection) GetAllInventories() ([]InventoryResponse, error) {
  657. var resp []InventoryResponse
  658. b, err := s.Get(fmt.Sprintf("%s/%v/%s", ProjectPath, s.ProjectId, "inventory"))
  659. if err != nil {
  660. return resp, err
  661. }
  662. err = json.Unmarshal(b, &resp)
  663. if err != nil {
  664. return resp, &SemaphoreClientError{Msg: err.Error()}
  665. }
  666. return resp, nil
  667. }
  668. /*
  669. Update an inventory
  670. */
  671. func (s SemaphoreConnection) UpdateInventory(name string, inv YamlInventory) error {
  672. sshKeyId, err := s.GetKeyId(s.KeyTagger.VpsSvcAccSshPubkeySeed())
  673. if err != nil {
  674. return err
  675. }
  676. becomeKeyId, err := s.GetKeyId(s.KeyTagger.VpsSvcAccKeyname())
  677. if err != nil {
  678. return err
  679. }
  680. b, err := yaml.Marshal(inv)
  681. if err != nil {
  682. return &SemaphoreClientError{Msg: "Error unmarshalling YAML inventory payload: " + err.Error()}
  683. }
  684. targetInv, err := s.GetInventoryByName(name)
  685. if err != nil {
  686. return &SemaphoreClientError{Msg: "Target inventory: " + name + " was not found."}
  687. }
  688. body := InventoryResponse{
  689. Id: targetInv.Id,
  690. Name: name,
  691. ProjectId: s.ProjectId,
  692. Inventory: string(b),
  693. SshKeyId: sshKeyId,
  694. BecomeKeyId: becomeKeyId,
  695. Type: "static-yaml",
  696. }
  697. req, err := json.Marshal(body)
  698. if err != nil {
  699. return &SemaphoreClientError{Msg: "There was an error marshalling the JSON payload: " + err.Error()}
  700. }
  701. _, err = s.Put(fmt.Sprintf("%s/%v/inventory/%v", ProjectPath, s.ProjectId, targetInv.Id), bytes.NewReader(req))
  702. return err
  703. }
  704. /*
  705. Remove host from an inventory
  706. */
  707. func (s SemaphoreConnection) RemoveHostFromInv(name string, host ...string) error {
  708. resp, err := s.GetInventoryByName(name)
  709. if err != nil {
  710. return err
  711. }
  712. var inv YamlInventory
  713. err = yaml.Unmarshal([]byte(resp.Inventory), &inv)
  714. if err != nil {
  715. return &SemaphoreClientError{Msg: "Error unmarshalling inventory from server: " + resp.Inventory + err.Error()}
  716. }
  717. for i := range host {
  718. _, ok := inv.All.Hosts[host[i]]
  719. if !ok {
  720. return &SemaphoreClientError{Msg: "Host: " + host[i] + " not found in the inventory: " + resp.Inventory}
  721. }
  722. delete(inv.All.Hosts, host[i])
  723. }
  724. pubkey, err := s.Keyring.GetKey(s.KeyTagger.WgClientKeypairKeyname())
  725. if err != nil {
  726. return &SemaphoreClientError{Msg: err.Error() + s.KeyTagger.WgClientKeypairKeyname()}
  727. }
  728. var hosts []string
  729. for k := range inv.All.Hosts {
  730. hosts = append(hosts, k)
  731. }
  732. return s.UpdateInventory(name, s.YamlInventoryBuilder(hosts, pubkey.GetPublic()))
  733. }
  734. /*
  735. Add hosts to inventory
  736. */
  737. func (s SemaphoreConnection) AddHostToInv(name string, host ...string) error {
  738. resp, err := s.GetInventoryByName(name)
  739. if err != nil {
  740. return err
  741. }
  742. var inv YamlInventory
  743. err = yaml.Unmarshal([]byte(resp.Inventory), &inv)
  744. if err != nil {
  745. return &SemaphoreClientError{Msg: "Error unmarshalling inventory from server: " + resp.Inventory + err.Error()}
  746. }
  747. pubkey, err := s.Keyring.GetKey(s.KeyTagger.WgClientKeypairKeyname())
  748. if err != nil {
  749. return &SemaphoreClientError{Msg: err.Error() + s.KeyTagger.WgClientKeypairKeyname()}
  750. }
  751. var hosts []string
  752. for k := range inv.All.Hosts {
  753. hosts = append(hosts, k)
  754. }
  755. hosts = append(hosts, host...)
  756. return s.UpdateInventory(name, s.YamlInventoryBuilder(hosts, pubkey.GetPublic()))
  757. }
  758. /*
  759. Get a repo ID by its name
  760. :param name: the name of the repo
  761. */
  762. func (s SemaphoreConnection) GetRepoByName(name string) (int, error) {
  763. resp, err := s.GetAllRepos()
  764. if err != nil {
  765. return 0, err
  766. }
  767. for i := range resp {
  768. if resp[i].Name == name {
  769. return resp[i].Id, nil
  770. }
  771. }
  772. return 0, &KeyNotFound{Keyname: name}
  773. }
  774. /*
  775. Get all repositories from Semaphore
  776. */
  777. func (s SemaphoreConnection) GetAllRepos() ([]NewRepoResponse, error) {
  778. var resp []NewRepoResponse
  779. b, err := s.Get(fmt.Sprintf("%s/%v/%s", ProjectPath, s.ProjectId, "repositories"))
  780. if err != nil {
  781. return resp, &SemaphoreClientError{Msg: err.Error()}
  782. }
  783. err = json.Unmarshal(b, &resp)
  784. if err != nil {
  785. return resp, &SemaphoreClientError{Msg: err.Error()}
  786. }
  787. return resp, nil
  788. }
  789. // Create an environment variable configuration, currently unimplemented
  790. func (s SemaphoreConnection) AddEnvironment(envVars EnvironmentVariables) error {
  791. envBytes, err := json.Marshal(envVars)
  792. if err != nil {
  793. return &SemaphoreClientError{Msg: "Couldnt unmarshall the environment variable payload: " + err.Error()}
  794. }
  795. _, err = s.GetEnvironmentId(YosaiEnvironment)
  796. if err == nil {
  797. return nil // environment exists, dont add another with same name
  798. }
  799. var body AddEnvironmentRequest
  800. body = AddEnvironmentRequest{
  801. Name: YosaiEnvironment,
  802. ProjectID: s.ProjectId,
  803. JSON: "{}",
  804. Env: string(envBytes),
  805. }
  806. b, err := json.Marshal(body)
  807. if err != nil {
  808. return &SemaphoreClientError{Msg: "couldnt marshal the JSON payload"}
  809. }
  810. _, err = s.Post(fmt.Sprintf("%s/%v/environment", ProjectPath, s.ProjectId), bytes.NewBuffer(b))
  811. return err
  812. }
  813. // Get an environment configuration ID by name.
  814. func (s SemaphoreConnection) GetEnvironmentId(name string) (int, error) {
  815. var env []EnvironmentResponse
  816. b, err := s.Get(fmt.Sprintf("%s/%v/environment", ProjectPath, s.ProjectId))
  817. if err != nil {
  818. return 0, err
  819. }
  820. err = json.Unmarshal(b, &env)
  821. if err != nil {
  822. return 0, &SemaphoreClientError{Msg: "Couldnt unmarshall the response"}
  823. }
  824. for i := range env {
  825. if env[i].Name == name {
  826. return env[i].Id, nil
  827. }
  828. }
  829. return 0, &KeyNotFound{Keyname: "Couldnt find environment: " + name}
  830. }
  831. /*
  832. Add job template to the Yosai project on Semaphore
  833. :param playbook: the name of the playbook file
  834. :param repoName: the name of the repo that the playbook belongs to
  835. */
  836. func (s SemaphoreConnection) AddJobTemplate(playbook string, repoName string) error {
  837. _, err := s.JobTemplateByName(YosaiVpnRotationJob)
  838. if err == nil {
  839. return nil // return nil because template exists
  840. }
  841. repoId, err := s.GetRepoByName(repoName)
  842. if err != nil {
  843. return err
  844. }
  845. InventoryItem, err := s.GetInventoryByName(YosaiServerInventory)
  846. if err != nil {
  847. return err
  848. }
  849. envId, err := s.GetEnvironmentId(YosaiEnvironment)
  850. if err != nil {
  851. return err
  852. }
  853. templ := NewTemplateRequest{
  854. ProjectId: s.ProjectId,
  855. Name: YosaiVpnRotationJob,
  856. InventoryId: InventoryItem.Id,
  857. RepositoryId: repoId,
  858. EnvironmentId: envId,
  859. Playbook: playbook,
  860. Type: "",
  861. }
  862. b, err := json.Marshal(templ)
  863. if err != nil {
  864. return &SemaphoreClientError{Msg: err.Error()}
  865. }
  866. b, err = s.Post(fmt.Sprintf("%s/%v/%s", ProjectPath, s.ProjectId, "templates"), bytes.NewReader(b))
  867. if err != nil {
  868. return &SemaphoreClientError{Msg: fmt.Sprintf("Error: %s\nServer Response: %s", err.Error(), string(b))}
  869. }
  870. return nil
  871. }
  872. /*
  873. Start a task in Semaphore by the template name
  874. :param name: the name of the job template to start
  875. */
  876. func (s SemaphoreConnection) StartJob(name string) (StartTaskResponse, error) {
  877. var resp StartTaskResponse
  878. template, err := s.JobTemplateByName(name)
  879. if err != nil {
  880. return resp, &SemaphoreClientError{Msg: "Could not start job template: " + name + "Error: " + err.Error()}
  881. }
  882. var jobReq StartTaskRequest
  883. jobReq = StartTaskRequest{
  884. TemplateID: template.Id,
  885. ProjectId: s.ProjectId,
  886. }
  887. b, err := json.Marshal(&jobReq)
  888. if err != nil {
  889. return resp, &SemaphoreClientError{Msg: "Couldnt marshal data into byte array: " + err.Error()}
  890. }
  891. rb, err := s.Post(fmt.Sprintf("%s/%v/tasks", ProjectPath, s.ProjectId), bytes.NewReader(b))
  892. if err != nil {
  893. return resp, err
  894. }
  895. err = json.Unmarshal(rb, &resp)
  896. if err != nil {
  897. return resp, &SemaphoreClientError{Msg: "Couldnt unmarshal the response from semaphore: " + err.Error()}
  898. }
  899. return resp, nil
  900. }
  901. /*
  902. Get a job template ID by name
  903. :param name: the name of the job template ID
  904. */
  905. func (s SemaphoreConnection) GetAllTemplates() ([]JobTemplate, error) {
  906. var jobs []JobTemplate
  907. resp, err := s.Get(fmt.Sprintf("%s/%v/templates", ProjectPath, s.ProjectId))
  908. if err != nil {
  909. return jobs, err
  910. }
  911. err = json.Unmarshal(resp, &jobs)
  912. if err != nil {
  913. return jobs, &SemaphoreClientError{Msg: "Error unmarshalling payload response: " + err.Error()}
  914. }
  915. return jobs, nil
  916. }
  917. /*
  918. Bootstrap the Semaphore environment
  919. */
  920. /*
  921. Get a job template ID by name
  922. :param name: the name of the job template ID
  923. */
  924. func (s SemaphoreConnection) JobTemplateByName(name string) (JobTemplate, error) {
  925. var job JobTemplate
  926. jobs, err := s.GetAllTemplates()
  927. if err != nil {
  928. return job, err
  929. }
  930. for i := range jobs {
  931. if jobs[i].Name == name {
  932. return jobs[i], nil
  933. }
  934. }
  935. return job, &SemaphoreClientError{Msg: "Job with name" + name + "not found"}
  936. }
  937. /*
  938. ##########################################################
  939. ################## DAEMON ROUTE HANDLERS #################
  940. ##########################################################
  941. */
  942. type SemaphoreRequest struct {
  943. Target string `json:"target"`
  944. }
  945. /*
  946. Wrapping the functioanlity of the keyring bootstrapper for top level cleanliness
  947. */
  948. func (s SemaphoreConnection) keyBootstrapper() daemon.SockMessage {
  949. reqKeys := s.KeyTagger.GetAnsibleKeys()
  950. for i := range reqKeys {
  951. kn := reqKeys[i]
  952. key, err := s.Keyring.GetKey(kn)
  953. if err != nil {
  954. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  955. }
  956. err = s.AddKey(kn, s.NewKeyRequestBuilder(kn, key))
  957. if err != nil {
  958. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  959. }
  960. }
  961. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, []byte("Daemon keyring successfuly bootstrapped."))
  962. }
  963. /*
  964. Wrapping the functionality of the Project bootstrapper for top level cleanliness
  965. */
  966. func (s SemaphoreConnection) projectBootstrapper() daemon.SockMessage {
  967. err := s.NewProject(YosaiProject)
  968. if err != nil {
  969. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  970. }
  971. err = s.AddRepository(s.Config.Repo(), s.Config.Branch())
  972. if err != nil {
  973. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  974. }
  975. hashiKey, err := s.Keyring.GetKey(s.KeyTagger.HashicorpVaultKeyname())
  976. if err != nil {
  977. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  978. }
  979. err = s.AddEnvironment(EnvironmentVariables{SecretsProviderUrl: s.Config.SecretsBackendUrl(), SecretsProviderApiKey: hashiKey.GetSecret()})
  980. if err != nil {
  981. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  982. }
  983. err = s.AddJobTemplate(s.Config.PlaybookName(), fmt.Sprintf("%s:%s", s.Config.Repo(), s.Config.Branch()))
  984. if err != nil {
  985. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  986. }
  987. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, []byte("Project successfuly bootstrapped."))
  988. }
  989. /*
  990. Wrapping the inventory bootstrap functionality for top level cleanliness
  991. */
  992. func (s SemaphoreConnection) inventoryBootstrapper() daemon.SockMessage {
  993. err := s.AddInventory(YosaiServerInventory, s.Config.VpnServer())
  994. if err != nil {
  995. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  996. }
  997. err = s.AddHostToInv(YosaiServerInventory, s.Config.VpnServer())
  998. if err != nil {
  999. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1000. }
  1001. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, []byte("Inventory successfuly bootstrapped."))
  1002. }
  1003. func (s SemaphoreConnection) BootstrapHandler(msg daemon.SockMessage) daemon.SockMessage {
  1004. var req SemaphoreRequest
  1005. err := json.Unmarshal(msg.Body, &req)
  1006. if err != nil {
  1007. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1008. }
  1009. switch req.Target {
  1010. case "keys":
  1011. return s.keyBootstrapper()
  1012. case "project":
  1013. return s.projectBootstrapper()
  1014. case "inventory":
  1015. return s.inventoryBootstrapper()
  1016. case "all":
  1017. bootstrapFuncs := []func() daemon.SockMessage{
  1018. s.keyBootstrapper,
  1019. s.inventoryBootstrapper,
  1020. s.projectBootstrapper,
  1021. }
  1022. successMsg := ""
  1023. for i := range bootstrapFuncs {
  1024. call := bootstrapFuncs[i]
  1025. resp := call()
  1026. if resp.StatusCode != daemon.REQUEST_OK {
  1027. return resp
  1028. }
  1029. successMsg = successMsg + resp.StatusMsg + "\n"
  1030. }
  1031. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, []byte(successMsg))
  1032. default:
  1033. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_UNRESOLVED, []byte("Unresolved Method."))
  1034. }
  1035. }
  1036. /*
  1037. Router for handling all stuff relating to Projects
  1038. :param msg: a daemon.SockMessage with request info
  1039. */
  1040. func (s SemaphoreConnection) ProjectHandler(msg daemon.SockMessage) daemon.SockMessage {
  1041. switch msg.Method {
  1042. case "bootstrap":
  1043. return s.projectBootstrapper()
  1044. case "add":
  1045. var req SemaphoreRequest
  1046. err := json.Unmarshal(msg.Body, &req)
  1047. if err != nil {
  1048. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1049. }
  1050. err = s.NewProject(req.Target)
  1051. if err != nil {
  1052. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1053. }
  1054. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, []byte("Project: "+req.Target+" successfully added."))
  1055. case "show":
  1056. proj, err := s.GetProjects()
  1057. if err != nil {
  1058. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1059. }
  1060. b, err := json.MarshalIndent(proj, " ", " ")
  1061. if err != nil {
  1062. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1063. }
  1064. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, b)
  1065. default:
  1066. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_UNRESOLVED, []byte("Unresolved Method."))
  1067. }
  1068. }
  1069. /*
  1070. handler to wrap all functions relating to Tasks
  1071. :param msg: a daemon.SockMessage that contains the request information
  1072. */
  1073. func (s SemaphoreConnection) TaskHandler(msg daemon.SockMessage) daemon.SockMessage {
  1074. var req SemaphoreRequest
  1075. err := json.Unmarshal(msg.Body, &req)
  1076. if err != nil {
  1077. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1078. }
  1079. switch msg.Method {
  1080. case "run":
  1081. resp, err := s.StartJob(req.Target)
  1082. if err != nil {
  1083. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1084. }
  1085. b, err := json.MarshalIndent(resp, " ", " ")
  1086. if err != nil {
  1087. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1088. }
  1089. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, b)
  1090. case "show":
  1091. taskid, err := strconv.Atoi(req.Target)
  1092. if err != nil {
  1093. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1094. }
  1095. taskout, err := s.GetTaskOutput(taskid)
  1096. if err != nil {
  1097. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1098. }
  1099. b, err := json.MarshalIndent(taskout, " ", " ")
  1100. if err != nil {
  1101. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1102. }
  1103. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, b)
  1104. case "poll":
  1105. taskId, err := strconv.Atoi(req.Target)
  1106. if err != nil {
  1107. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_TIMEOUT, []byte(err.Error()))
  1108. }
  1109. err = s.PollTask(taskId, 30)
  1110. if err != nil {
  1111. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_TIMEOUT, []byte(err.Error()))
  1112. }
  1113. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_OK, []byte("Task: "+req.Target+" completed."))
  1114. default:
  1115. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_UNRESOLVED, []byte("Unresolved Method."))
  1116. }
  1117. }
  1118. /*
  1119. Handles all of the requests relating to Hosts
  1120. :param msg: a daemon.SockMessage containing all of the request info
  1121. */
  1122. func (s SemaphoreConnection) HostHandler(msg daemon.SockMessage) daemon.SockMessage {
  1123. var req SemaphoreRequest
  1124. err := json.Unmarshal(msg.Body, &req)
  1125. if err != nil {
  1126. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1127. }
  1128. switch msg.Method {
  1129. case "add":
  1130. hosts := strings.Split(strings.Trim(req.Target, ","), ",")
  1131. err := s.AddHostToInv(YosaiServerInventory, hosts...)
  1132. if err != nil {
  1133. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1134. }
  1135. return *daemon.NewSockMessage(daemon.MsgRequest, daemon.REQUEST_OK, []byte(fmt.Sprintf("Host: %v added to the inventory", hosts)))
  1136. case "delete":
  1137. hosts := strings.Split(strings.Trim(req.Target, ","), ",")
  1138. err := s.RemoveHostFromInv(YosaiServerInventory, hosts...)
  1139. if err != nil {
  1140. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_FAILED, []byte(err.Error()))
  1141. }
  1142. return *daemon.NewSockMessage(daemon.MsgRequest, daemon.REQUEST_OK, []byte(fmt.Sprintf("Host: %v removed from the inventory", hosts)))
  1143. default:
  1144. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_UNRESOLVED, []byte("Unresolved Method."))
  1145. }
  1146. }
  1147. /*
  1148. Implementing the router interface
  1149. :param msg: a daemon.SockMessage containing the request data
  1150. */
  1151. func (s SemaphoreConnection) SemaphoreRouter(msg daemon.SockMessage) daemon.SockMessage {
  1152. switch msg.Target {
  1153. case "bootstrap":
  1154. return s.BootstrapHandler(msg)
  1155. case "project":
  1156. return s.ProjectHandler(msg)
  1157. case "task":
  1158. return s.TaskHandler(msg)
  1159. case "hosts":
  1160. return s.HostHandler(msg)
  1161. default:
  1162. return *daemon.NewSockMessage(daemon.MsgResponse, daemon.REQUEST_UNRESOLVED, []byte("Unresolved Method."))
  1163. }
  1164. }
  1165. /*
  1166. ######################################################
  1167. ############# YAML INVENTORY STRUCTS #################
  1168. ######################################################
  1169. */
  1170. type YamlInventory struct {
  1171. All yamlInvAll `yaml:"all"`
  1172. }
  1173. type yamlInvAll struct {
  1174. Hosts map[string]yamlVars `yaml:"hosts"`
  1175. }
  1176. type yamlVars struct {
  1177. AnsibleSshCommonArgs string `yaml:"ansible_ssh_common_args"`
  1178. MachineType string `yaml:"machine_type"`
  1179. MachineSubType string `yaml:"machine_subtype"`
  1180. VpnNetworkAddress string `yaml:"vpn_network_address"`
  1181. VpnServerPort int `yaml:"vpn_server_port"`
  1182. ClientPubkey string `yaml:"client_public_key"`
  1183. ClientVpnAddress string `yaml:"client_vpn_address"`
  1184. SecretsProvider string `yaml:"secrets_provider"`
  1185. }
  1186. /*
  1187. YAML inventory builder function
  1188. :param hosts: a list of host IP addresses to add to the VPN server inventory
  1189. */
  1190. func (s SemaphoreConnection) YamlInventoryBuilder(hosts []string, clientPubkey string) YamlInventory {
  1191. hostmap := map[string]yamlVars{}
  1192. for i := range hosts {
  1193. hostmap[hosts[i]] = yamlVars{
  1194. AnsibleSshCommonArgs: "-o StrictHostKeyChecking=no",
  1195. MachineType: "vpn",
  1196. MachineSubType: "server",
  1197. VpnNetworkAddress: s.Config.VpnServerNetwork(),
  1198. VpnServerPort: s.Config.VpnServerPort(),
  1199. ClientPubkey: clientPubkey,
  1200. ClientVpnAddress: s.Config.VpnClientIpAddr(),
  1201. SecretsProvider: s.Config.SecretsBackend()}
  1202. }
  1203. return YamlInventory{
  1204. All: yamlInvAll{
  1205. Hosts: hostmap,
  1206. },
  1207. }
  1208. }
  1209. /*
  1210. ##########################################
  1211. ################ ERRORS ##################
  1212. ##########################################
  1213. */
  1214. type SemaphoreClientError struct {
  1215. Msg string
  1216. }
  1217. // Implementing error interface
  1218. func (s *SemaphoreClientError) Error() string {
  1219. return fmt.Sprintf("There was an error with the call to the semaphore server: '%s'", s.Msg)
  1220. }
  1221. type KeyNotFound struct{ Keyname string }
  1222. func (k *KeyNotFound) Error() string {
  1223. return fmt.Sprintf("Key '%s' was not found in the Semaphore Keystore", k.Keyname)
  1224. }
  1225. type SemaphoreTimeout struct {
  1226. Tries int
  1227. }
  1228. func (s *SemaphoreTimeout) Error() string {
  1229. return "Semaphore job execution poll timed out after: " + fmt.Sprint(s.Tries) + " calls to the server."
  1230. }