cluster_handler.go 11 KB

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