cluster_handler.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "github.com/go-chi/chi"
  8. "github.com/porter-dev/porter/internal/analytics"
  9. "github.com/porter-dev/porter/internal/forms"
  10. "github.com/porter-dev/porter/internal/kubernetes"
  11. "github.com/porter-dev/porter/internal/kubernetes/domain"
  12. "github.com/porter-dev/porter/internal/models"
  13. )
  14. // HandleCreateProjectCluster creates a new cluster
  15. func (app *App) HandleCreateProjectCluster(w http.ResponseWriter, r *http.Request) {
  16. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  17. userID, err := app.getUserIDFromRequest(r)
  18. if err != nil || projID == 0 {
  19. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  20. return
  21. }
  22. form := &forms.CreateClusterForm{
  23. ProjectID: uint(projID),
  24. }
  25. // decode from JSON to form value
  26. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  27. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  28. return
  29. }
  30. // validate the form
  31. if err := app.validator.Struct(form); err != nil {
  32. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  33. return
  34. }
  35. // convert the form to a registry
  36. cluster, err := form.ToCluster()
  37. if err != nil {
  38. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  39. return
  40. }
  41. // handle write to the database
  42. cluster, err = app.Repo.Cluster().CreateCluster(cluster)
  43. if err != nil {
  44. app.handleErrorDataWrite(err, w)
  45. return
  46. }
  47. app.Logger.Info().Msgf("New cluster created: %d", cluster.ID)
  48. app.analyticsClient.Track(analytics.CreateSegmentNewClusterEvent(
  49. &analytics.NewClusterEventOpts{
  50. UserId: fmt.Sprintf("%d", userID),
  51. ProjId: fmt.Sprintf("%d", projID),
  52. ClusterName: cluster.Name,
  53. ClusterType: "EKS",
  54. EventType: "connected",
  55. },
  56. ))
  57. w.WriteHeader(http.StatusCreated)
  58. clusterExt := cluster.Externalize()
  59. if err := json.NewEncoder(w).Encode(clusterExt); err != nil {
  60. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  61. return
  62. }
  63. }
  64. // HandleReadProjectCluster reads a cluster by id
  65. func (app *App) HandleReadProjectCluster(w http.ResponseWriter, r *http.Request) {
  66. id, err := strconv.ParseUint(chi.URLParam(r, "cluster_id"), 0, 64)
  67. if err != nil || id == 0 {
  68. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  69. return
  70. }
  71. cluster, err := app.Repo.Cluster().ReadCluster(uint(id))
  72. if err != nil {
  73. app.handleErrorRead(err, ErrProjectDataRead, w)
  74. return
  75. }
  76. clusterExt := cluster.DetailedExternalize()
  77. form := &forms.K8sForm{
  78. OutOfClusterConfig: &kubernetes.OutOfClusterConfig{
  79. Repo: app.Repo,
  80. DigitalOceanOAuth: app.DOConf,
  81. Cluster: cluster,
  82. },
  83. }
  84. var agent *kubernetes.Agent
  85. if app.ServerConf.IsTesting {
  86. agent = app.TestAgents.K8sAgent
  87. } else {
  88. agent, _ = kubernetes.GetAgentOutOfClusterConfig(form.OutOfClusterConfig)
  89. }
  90. endpoint, found, ingressErr := domain.GetNGINXIngressServiceIP(agent.Clientset)
  91. if found {
  92. clusterExt.IngressIP = endpoint
  93. }
  94. if !found && ingressErr != nil {
  95. clusterExt.IngressError = kubernetes.CatchK8sConnectionError(ingressErr).Externalize()
  96. }
  97. w.WriteHeader(http.StatusOK)
  98. if err := json.NewEncoder(w).Encode(clusterExt); err != nil {
  99. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  100. return
  101. }
  102. }
  103. // HandleListProjectClusters returns a list of clusters that have linked Integrations.
  104. func (app *App) HandleListProjectClusters(w http.ResponseWriter, r *http.Request) {
  105. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  106. if err != nil || projID == 0 {
  107. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  108. return
  109. }
  110. clusters, err := app.Repo.Cluster().ListClustersByProjectID(uint(projID))
  111. if err != nil {
  112. app.handleErrorRead(err, ErrProjectDataRead, w)
  113. return
  114. }
  115. extClusters := make([]*models.ClusterExternal, 0)
  116. for _, cluster := range clusters {
  117. extClusters = append(extClusters, cluster.Externalize())
  118. }
  119. w.WriteHeader(http.StatusOK)
  120. if err := json.NewEncoder(w).Encode(extClusters); err != nil {
  121. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  122. return
  123. }
  124. }
  125. // HandleUpdateProjectCluster updates a project's cluster
  126. func (app *App) HandleUpdateProjectCluster(w http.ResponseWriter, r *http.Request) {
  127. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  128. if err != nil || projID == 0 {
  129. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  130. return
  131. }
  132. clusterID, err := strconv.ParseUint(chi.URLParam(r, "cluster_id"), 0, 64)
  133. if err != nil || clusterID == 0 {
  134. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  135. return
  136. }
  137. form := &forms.UpdateClusterForm{
  138. ID: uint(clusterID),
  139. }
  140. // decode from JSON to form value
  141. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  142. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  143. return
  144. }
  145. // validate the form
  146. if err := app.validator.Struct(form); err != nil {
  147. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  148. return
  149. }
  150. // convert the form to a registry
  151. cluster, err := form.ToCluster(app.Repo.Cluster())
  152. if err != nil {
  153. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  154. return
  155. }
  156. // handle write to the database
  157. cluster, err = app.Repo.Cluster().UpdateCluster(cluster)
  158. if err != nil {
  159. app.handleErrorDataWrite(err, w)
  160. return
  161. }
  162. w.WriteHeader(http.StatusOK)
  163. clusterExt := cluster.Externalize()
  164. if err := json.NewEncoder(w).Encode(clusterExt); err != nil {
  165. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  166. return
  167. }
  168. }
  169. // HandleDeleteProjectCluster handles the deletion of a Cluster via the cluster ID
  170. func (app *App) HandleDeleteProjectCluster(w http.ResponseWriter, r *http.Request) {
  171. id, err := strconv.ParseUint(chi.URLParam(r, "cluster_id"), 0, 64)
  172. if err != nil || id == 0 {
  173. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  174. return
  175. }
  176. cluster, err := app.Repo.Cluster().ReadCluster(uint(id))
  177. if err != nil {
  178. app.handleErrorRead(err, ErrProjectDataRead, w)
  179. return
  180. }
  181. err = app.Repo.Cluster().DeleteCluster(cluster)
  182. if err != nil {
  183. app.handleErrorRead(err, ErrProjectDataRead, w)
  184. return
  185. }
  186. w.WriteHeader(http.StatusOK)
  187. }
  188. // HandleCreateProjectClusterCandidates handles the creation of ClusterCandidates using
  189. // a kubeconfig and a project id
  190. func (app *App) HandleCreateProjectClusterCandidates(w http.ResponseWriter, r *http.Request) {
  191. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  192. if err != nil || projID == 0 {
  193. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  194. return
  195. }
  196. form := &forms.CreateClusterCandidatesForm{
  197. ProjectID: uint(projID),
  198. }
  199. // decode from JSON to form value
  200. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  201. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  202. return
  203. }
  204. // validate the form
  205. if err := app.validator.Struct(form); err != nil {
  206. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  207. return
  208. }
  209. // convert the form to a ClusterCandidate
  210. ccs, err := form.ToClusterCandidates(app.ServerConf.IsLocal)
  211. if err != nil {
  212. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  213. return
  214. }
  215. extClusters := make([]*models.ClusterCandidateExternal, 0)
  216. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  217. if err != nil {
  218. http.Error(w, err.Error(), http.StatusInternalServerError)
  219. return
  220. }
  221. userID, _ := session.Values["user_id"].(uint)
  222. for _, cc := range ccs {
  223. // handle write to the database
  224. cc, err = app.Repo.Cluster().CreateClusterCandidate(cc)
  225. if err != nil {
  226. app.handleErrorDataWrite(err, w)
  227. return
  228. }
  229. app.Logger.Info().Msgf("New cluster candidate created: %d", cc.ID)
  230. // if the ClusterCandidate does not have any actions to perform, create the Cluster
  231. // automatically
  232. if len(cc.Resolvers) == 0 {
  233. // we query the repo again to get the decrypted version of the cluster candidate
  234. cc, err = app.Repo.Cluster().ReadClusterCandidate(cc.ID)
  235. if err != nil {
  236. app.handleErrorDataRead(err, w)
  237. return
  238. }
  239. clusterForm := &forms.ResolveClusterForm{
  240. Resolver: &models.ClusterResolverAll{},
  241. ClusterCandidateID: cc.ID,
  242. ProjectID: uint(projID),
  243. UserID: userID,
  244. }
  245. err := clusterForm.ResolveIntegration(app.Repo)
  246. if err != nil {
  247. app.handleErrorDataWrite(err, w)
  248. return
  249. }
  250. cluster, err := clusterForm.ResolveCluster(app.Repo)
  251. if err != nil {
  252. app.handleErrorDataWrite(err, w)
  253. return
  254. }
  255. cc, err = app.Repo.Cluster().UpdateClusterCandidateCreatedClusterID(cc.ID, cluster.ID)
  256. if err != nil {
  257. app.handleErrorDataWrite(err, w)
  258. return
  259. }
  260. app.Logger.Info().Msgf("New cluster created: %d", cluster.ID)
  261. }
  262. extClusters = append(extClusters, cc.Externalize())
  263. }
  264. w.WriteHeader(http.StatusCreated)
  265. if err := json.NewEncoder(w).Encode(extClusters); err != nil {
  266. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  267. return
  268. }
  269. }
  270. // HandleListProjectClusterCandidates returns a list of externalized ClusterCandidates
  271. // ([]models.ClusterCandidateExternal) based on a project ID
  272. func (app *App) HandleListProjectClusterCandidates(w http.ResponseWriter, r *http.Request) {
  273. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  274. if err != nil || projID == 0 {
  275. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  276. return
  277. }
  278. ccs, err := app.Repo.Cluster().ListClusterCandidatesByProjectID(uint(projID))
  279. if err != nil {
  280. app.handleErrorRead(err, ErrProjectDataRead, w)
  281. return
  282. }
  283. extCCs := make([]*models.ClusterCandidateExternal, 0)
  284. for _, cc := range ccs {
  285. extCCs = append(extCCs, cc.Externalize())
  286. }
  287. w.WriteHeader(http.StatusOK)
  288. if err := json.NewEncoder(w).Encode(extCCs); err != nil {
  289. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  290. return
  291. }
  292. }
  293. // HandleResolveClusterCandidate accepts a list of resolving objects (ClusterResolver)
  294. // for a given ClusterCandidate, which "resolves" that ClusterCandidate and creates a
  295. // Cluster for a specific project
  296. func (app *App) HandleResolveClusterCandidate(w http.ResponseWriter, r *http.Request) {
  297. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  298. if err != nil || projID == 0 {
  299. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  300. return
  301. }
  302. candID, err := strconv.ParseUint(chi.URLParam(r, "candidate_id"), 0, 64)
  303. if err != nil || projID == 0 {
  304. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  305. return
  306. }
  307. session, err := app.Store.Get(r, app.ServerConf.CookieName)
  308. if err != nil {
  309. http.Error(w, err.Error(), http.StatusInternalServerError)
  310. return
  311. }
  312. userID, _ := session.Values["user_id"].(uint)
  313. // decode actions from request
  314. resolver := &models.ClusterResolverAll{}
  315. if err := json.NewDecoder(r.Body).Decode(resolver); err != nil {
  316. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  317. return
  318. }
  319. clusterResolver := &forms.ResolveClusterForm{
  320. Resolver: resolver,
  321. ClusterCandidateID: uint(candID),
  322. ProjectID: uint(projID),
  323. UserID: userID,
  324. }
  325. err = clusterResolver.ResolveIntegration(app.Repo)
  326. if err != nil {
  327. app.handleErrorDataWrite(err, w)
  328. return
  329. }
  330. cluster, err := clusterResolver.ResolveCluster(app.Repo)
  331. if err != nil {
  332. app.handleErrorDataWrite(err, w)
  333. return
  334. }
  335. _, err = app.Repo.Cluster().UpdateClusterCandidateCreatedClusterID(uint(candID), cluster.ID)
  336. if err != nil {
  337. app.handleErrorDataWrite(err, w)
  338. return
  339. }
  340. app.Logger.Info().Msgf("New cluster created: %d", cluster.ID)
  341. app.analyticsClient.Track(analytics.CreateSegmentNewClusterEvent(
  342. &analytics.NewClusterEventOpts{
  343. UserId: fmt.Sprintf("%d", userID),
  344. ProjId: fmt.Sprintf("%d", projID),
  345. ClusterName: cluster.Name,
  346. ClusterType: "",
  347. EventType: "connected",
  348. },
  349. ))
  350. clusterExt := cluster.Externalize()
  351. w.WriteHeader(http.StatusCreated)
  352. if err := json.NewEncoder(w).Encode(clusterExt); err != nil {
  353. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  354. return
  355. }
  356. }