cluster_handler.go 12 KB

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