agent.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  1. package kubernetes
  2. import (
  3. "bufio"
  4. "bytes"
  5. "compress/gzip"
  6. "context"
  7. "encoding/base64"
  8. "encoding/json"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "strings"
  13. "github.com/porter-dev/porter/internal/kubernetes/provisioner"
  14. "github.com/porter-dev/porter/internal/kubernetes/provisioner/aws"
  15. "github.com/porter-dev/porter/internal/kubernetes/provisioner/aws/ecr"
  16. "github.com/porter-dev/porter/internal/kubernetes/provisioner/aws/eks"
  17. "github.com/porter-dev/porter/internal/kubernetes/provisioner/do"
  18. "github.com/porter-dev/porter/internal/kubernetes/provisioner/do/docr"
  19. "github.com/porter-dev/porter/internal/kubernetes/provisioner/do/doks"
  20. "github.com/porter-dev/porter/internal/kubernetes/provisioner/gcp"
  21. "github.com/porter-dev/porter/internal/kubernetes/provisioner/gcp/gke"
  22. "github.com/porter-dev/porter/internal/models"
  23. "github.com/porter-dev/porter/internal/models/integrations"
  24. "github.com/porter-dev/porter/internal/oauth"
  25. "github.com/porter-dev/porter/internal/registry"
  26. "github.com/porter-dev/porter/internal/repository"
  27. "golang.org/x/oauth2"
  28. "github.com/gorilla/websocket"
  29. "github.com/porter-dev/porter/internal/helm/grapher"
  30. appsv1 "k8s.io/api/apps/v1"
  31. batchv1 "k8s.io/api/batch/v1"
  32. batchv1beta1 "k8s.io/api/batch/v1beta1"
  33. v1 "k8s.io/api/core/v1"
  34. v1beta1 "k8s.io/api/extensions/v1beta1"
  35. "k8s.io/apimachinery/pkg/api/errors"
  36. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  37. "k8s.io/apimachinery/pkg/runtime"
  38. "k8s.io/apimachinery/pkg/runtime/schema"
  39. "k8s.io/apimachinery/pkg/types"
  40. "k8s.io/cli-runtime/pkg/genericclioptions"
  41. "k8s.io/client-go/informers"
  42. "k8s.io/client-go/kubernetes"
  43. "k8s.io/client-go/rest"
  44. "k8s.io/client-go/tools/cache"
  45. "k8s.io/client-go/tools/remotecommand"
  46. "github.com/porter-dev/porter/internal/config"
  47. rspb "helm.sh/helm/v3/pkg/release"
  48. )
  49. // Agent is a Kubernetes agent for performing operations that interact with the
  50. // api server
  51. type Agent struct {
  52. RESTClientGetter genericclioptions.RESTClientGetter
  53. Clientset kubernetes.Interface
  54. }
  55. type Message struct {
  56. EventType string `json:"event_type"`
  57. Object interface{}
  58. Kind string
  59. }
  60. type ListOptions struct {
  61. FieldSelector string
  62. }
  63. // CreateConfigMap creates the configmap given the key-value pairs and namespace
  64. func (a *Agent) CreateConfigMap(name string, namespace string, configMap map[string]string) (*v1.ConfigMap, error) {
  65. return a.Clientset.CoreV1().ConfigMaps(namespace).Create(
  66. context.TODO(),
  67. &v1.ConfigMap{
  68. ObjectMeta: metav1.ObjectMeta{
  69. Name: name,
  70. Namespace: namespace,
  71. Labels: map[string]string{
  72. "porter": "true",
  73. },
  74. },
  75. Data: configMap,
  76. },
  77. metav1.CreateOptions{},
  78. )
  79. }
  80. // CreateLinkedSecret creates a secret given the key-value pairs and namespace. Values are
  81. // base64 encoded
  82. func (a *Agent) CreateLinkedSecret(name, namespace, cmName string, data map[string][]byte) (*v1.Secret, error) {
  83. return a.Clientset.CoreV1().Secrets(namespace).Create(
  84. context.TODO(),
  85. &v1.Secret{
  86. ObjectMeta: metav1.ObjectMeta{
  87. Name: name,
  88. Namespace: namespace,
  89. Labels: map[string]string{
  90. "porter": "true",
  91. "configmap": cmName,
  92. },
  93. },
  94. Data: data,
  95. },
  96. metav1.CreateOptions{},
  97. )
  98. }
  99. type mergeConfigMapData struct {
  100. Data map[string]*string `json:"data"`
  101. }
  102. // UpdateConfigMap updates the configmap given its name and namespace
  103. func (a *Agent) UpdateConfigMap(name string, namespace string, configMap map[string]string) error {
  104. cmData := make(map[string]*string)
  105. for key, val := range configMap {
  106. valCopy := val
  107. cmData[key] = &valCopy
  108. if len(val) == 0 {
  109. cmData[key] = nil
  110. }
  111. }
  112. mergeCM := &mergeConfigMapData{
  113. Data: cmData,
  114. }
  115. patchBytes, err := json.Marshal(mergeCM)
  116. if err != nil {
  117. return err
  118. }
  119. _, err = a.Clientset.CoreV1().ConfigMaps(namespace).Patch(
  120. context.Background(),
  121. name,
  122. types.MergePatchType,
  123. patchBytes,
  124. metav1.PatchOptions{},
  125. )
  126. return err
  127. }
  128. type mergeLinkedSecretData struct {
  129. Data map[string]*[]byte `json:"data"`
  130. }
  131. // UpdateLinkedSecret updates the secret given its name and namespace
  132. func (a *Agent) UpdateLinkedSecret(name, namespace, cmName string, data map[string][]byte) error {
  133. secretData := make(map[string]*[]byte)
  134. for key, val := range data {
  135. valCopy := val
  136. secretData[key] = &valCopy
  137. if len(val) == 0 {
  138. secretData[key] = nil
  139. }
  140. }
  141. mergeSecret := &mergeLinkedSecretData{
  142. Data: secretData,
  143. }
  144. patchBytes, err := json.Marshal(mergeSecret)
  145. if err != nil {
  146. return err
  147. }
  148. _, err = a.Clientset.CoreV1().Secrets(namespace).Patch(
  149. context.TODO(),
  150. name,
  151. types.MergePatchType,
  152. patchBytes,
  153. metav1.PatchOptions{},
  154. )
  155. return err
  156. }
  157. // DeleteConfigMap deletes the configmap given its name and namespace
  158. func (a *Agent) DeleteConfigMap(name string, namespace string) error {
  159. return a.Clientset.CoreV1().ConfigMaps(namespace).Delete(
  160. context.TODO(),
  161. name,
  162. metav1.DeleteOptions{},
  163. )
  164. }
  165. // DeleteLinkedSecret deletes the secret given its name and namespace
  166. func (a *Agent) DeleteLinkedSecret(name, namespace string) error {
  167. return a.Clientset.CoreV1().Secrets(namespace).Delete(
  168. context.TODO(),
  169. name,
  170. metav1.DeleteOptions{},
  171. )
  172. }
  173. // GetConfigMap retrieves the configmap given its name and namespace
  174. func (a *Agent) GetConfigMap(name string, namespace string) (*v1.ConfigMap, error) {
  175. return a.Clientset.CoreV1().ConfigMaps(namespace).Get(
  176. context.TODO(),
  177. name,
  178. metav1.GetOptions{},
  179. )
  180. }
  181. // GetSecret retrieves the secret given its name and namespace
  182. func (a *Agent) GetSecret(name string, namespace string) (*v1.Secret, error) {
  183. return a.Clientset.CoreV1().Secrets(namespace).Get(
  184. context.TODO(),
  185. name,
  186. metav1.GetOptions{},
  187. )
  188. }
  189. // ListConfigMaps simply lists namespaces
  190. func (a *Agent) ListConfigMaps(namespace string) (*v1.ConfigMapList, error) {
  191. return a.Clientset.CoreV1().ConfigMaps(namespace).List(
  192. context.TODO(),
  193. metav1.ListOptions{
  194. LabelSelector: "porter=true",
  195. },
  196. )
  197. }
  198. // ListEvents lists the events of a given object.
  199. func (a *Agent) ListEvents(name string, namespace string) (*v1.EventList, error) {
  200. return a.Clientset.CoreV1().Events(namespace).List(
  201. context.TODO(),
  202. metav1.ListOptions{
  203. FieldSelector: fmt.Sprintf("involvedObject.name=%s,involvedObject.namespace=%s", name, namespace),
  204. },
  205. )
  206. }
  207. // ListNamespaces simply lists namespaces
  208. func (a *Agent) ListNamespaces() (*v1.NamespaceList, error) {
  209. return a.Clientset.CoreV1().Namespaces().List(
  210. context.TODO(),
  211. metav1.ListOptions{},
  212. )
  213. }
  214. // CreateNamespace creates a namespace with the given name.
  215. func (a *Agent) CreateNamespace(name string) (*v1.Namespace, error) {
  216. // check if namespace exists
  217. checkNS, err := a.Clientset.CoreV1().Namespaces().Get(
  218. context.TODO(),
  219. name,
  220. metav1.GetOptions{},
  221. )
  222. if err == nil && checkNS != nil {
  223. return checkNS, nil
  224. }
  225. namespace := v1.Namespace{
  226. ObjectMeta: metav1.ObjectMeta{
  227. Name: name,
  228. },
  229. }
  230. return a.Clientset.CoreV1().Namespaces().Create(
  231. context.TODO(),
  232. &namespace,
  233. metav1.CreateOptions{},
  234. )
  235. }
  236. func (a *Agent) GetPorterAgent() (*appsv1.Deployment, error) {
  237. return a.Clientset.AppsV1().Deployments("porter-agent-system").Get(
  238. context.TODO(),
  239. "porter-agent-controller-manager",
  240. metav1.GetOptions{},
  241. )
  242. }
  243. // DeleteNamespace deletes the namespace given the name.
  244. func (a *Agent) DeleteNamespace(name string) error {
  245. return a.Clientset.CoreV1().Namespaces().Delete(
  246. context.TODO(),
  247. name,
  248. metav1.DeleteOptions{},
  249. )
  250. }
  251. // ListJobsByLabel lists jobs in a namespace matching a label
  252. type Label struct {
  253. Key string
  254. Val string
  255. }
  256. func (a *Agent) ListJobsByLabel(namespace string, labels ...Label) ([]batchv1.Job, error) {
  257. selectors := make([]string, 0)
  258. for _, label := range labels {
  259. selectors = append(selectors, fmt.Sprintf("%s=%s", label.Key, label.Val))
  260. }
  261. resp, err := a.Clientset.BatchV1().Jobs(namespace).List(
  262. context.TODO(),
  263. metav1.ListOptions{
  264. LabelSelector: strings.Join(selectors, ","),
  265. },
  266. )
  267. if err != nil {
  268. return nil, err
  269. }
  270. return resp.Items, nil
  271. }
  272. // DeleteJob deletes the job in the given name and namespace.
  273. func (a *Agent) DeleteJob(name, namespace string) error {
  274. return a.Clientset.BatchV1().Jobs(namespace).Delete(
  275. context.TODO(),
  276. name,
  277. metav1.DeleteOptions{},
  278. )
  279. }
  280. // GetJobPods lists all pods belonging to a job in a namespace
  281. func (a *Agent) GetJobPods(namespace, jobName string) ([]v1.Pod, error) {
  282. resp, err := a.Clientset.CoreV1().Pods(namespace).List(
  283. context.TODO(),
  284. metav1.ListOptions{
  285. LabelSelector: fmt.Sprintf("%s=%s", "job-name", jobName),
  286. },
  287. )
  288. if err != nil {
  289. return nil, err
  290. }
  291. return resp.Items, nil
  292. }
  293. // GetIngress gets ingress given the name and namespace
  294. func (a *Agent) GetIngress(namespace string, name string) (*v1beta1.Ingress, error) {
  295. return a.Clientset.ExtensionsV1beta1().Ingresses(namespace).Get(
  296. context.TODO(),
  297. name,
  298. metav1.GetOptions{},
  299. )
  300. }
  301. // GetDeployment gets the deployment given the name and namespace
  302. func (a *Agent) GetDeployment(c grapher.Object) (*appsv1.Deployment, error) {
  303. return a.Clientset.AppsV1().Deployments(c.Namespace).Get(
  304. context.TODO(),
  305. c.Name,
  306. metav1.GetOptions{},
  307. )
  308. }
  309. // GetStatefulSet gets the statefulset given the name and namespace
  310. func (a *Agent) GetStatefulSet(c grapher.Object) (*appsv1.StatefulSet, error) {
  311. return a.Clientset.AppsV1().StatefulSets(c.Namespace).Get(
  312. context.TODO(),
  313. c.Name,
  314. metav1.GetOptions{},
  315. )
  316. }
  317. // GetReplicaSet gets the replicaset given the name and namespace
  318. func (a *Agent) GetReplicaSet(c grapher.Object) (*appsv1.ReplicaSet, error) {
  319. return a.Clientset.AppsV1().ReplicaSets(c.Namespace).Get(
  320. context.TODO(),
  321. c.Name,
  322. metav1.GetOptions{},
  323. )
  324. }
  325. // GetDaemonSet gets the daemonset by name and namespace
  326. func (a *Agent) GetDaemonSet(c grapher.Object) (*appsv1.DaemonSet, error) {
  327. return a.Clientset.AppsV1().DaemonSets(c.Namespace).Get(
  328. context.TODO(),
  329. c.Name,
  330. metav1.GetOptions{},
  331. )
  332. }
  333. // GetJob gets the job by name and namespace
  334. func (a *Agent) GetJob(c grapher.Object) (*batchv1.Job, error) {
  335. return a.Clientset.BatchV1().Jobs(c.Namespace).Get(
  336. context.TODO(),
  337. c.Name,
  338. metav1.GetOptions{},
  339. )
  340. }
  341. // GetCronJob gets the CronJob by name and namespace
  342. func (a *Agent) GetCronJob(c grapher.Object) (*batchv1beta1.CronJob, error) {
  343. return a.Clientset.BatchV1beta1().CronJobs(c.Namespace).Get(
  344. context.TODO(),
  345. c.Name,
  346. metav1.GetOptions{},
  347. )
  348. }
  349. // GetPodsByLabel retrieves pods with matching labels
  350. func (a *Agent) GetPodsByLabel(selector string, namespace string) (*v1.PodList, error) {
  351. // Search in all namespaces for matching pods
  352. return a.Clientset.CoreV1().Pods(namespace).List(
  353. context.TODO(),
  354. metav1.ListOptions{
  355. LabelSelector: selector,
  356. },
  357. )
  358. }
  359. // DeletePod deletes a pod by name and namespace
  360. func (a *Agent) DeletePod(namespace string, name string) error {
  361. return a.Clientset.CoreV1().Pods(namespace).Delete(
  362. context.TODO(),
  363. name,
  364. metav1.DeleteOptions{},
  365. )
  366. }
  367. // GetPodLogs streams real-time logs from a given pod.
  368. func (a *Agent) GetPodLogs(namespace string, name string, conn *websocket.Conn) error {
  369. // get the pod to read in the list of contains
  370. pod, err := a.Clientset.CoreV1().Pods(namespace).Get(
  371. context.Background(),
  372. name,
  373. metav1.GetOptions{},
  374. )
  375. if err != nil {
  376. return fmt.Errorf("Cannot get pod %s: %s", name, err.Error())
  377. }
  378. container := pod.Spec.Containers[0].Name
  379. tails := int64(400)
  380. // follow logs
  381. podLogOpts := v1.PodLogOptions{
  382. Follow: true,
  383. TailLines: &tails,
  384. Container: container,
  385. }
  386. req := a.Clientset.CoreV1().Pods(namespace).GetLogs(name, &podLogOpts)
  387. podLogs, err := req.Stream(context.TODO())
  388. if err != nil {
  389. return fmt.Errorf("Cannot open log stream for pod %s: %s", name, err.Error())
  390. }
  391. defer podLogs.Close()
  392. r := bufio.NewReader(podLogs)
  393. errorchan := make(chan error)
  394. go func() {
  395. // listens for websocket closing handshake
  396. for {
  397. if _, _, err := conn.ReadMessage(); err != nil {
  398. defer conn.Close()
  399. errorchan <- nil
  400. return
  401. }
  402. }
  403. }()
  404. go func() {
  405. for {
  406. select {
  407. case <-errorchan:
  408. defer close(errorchan)
  409. return
  410. default:
  411. }
  412. bytes, err := r.ReadBytes('\n')
  413. if writeErr := conn.WriteMessage(websocket.TextMessage, bytes); writeErr != nil {
  414. errorchan <- writeErr
  415. return
  416. }
  417. if err != nil {
  418. if err != io.EOF {
  419. errorchan <- err
  420. return
  421. }
  422. errorchan <- nil
  423. return
  424. }
  425. }
  426. }()
  427. for {
  428. select {
  429. case err = <-errorchan:
  430. return err
  431. }
  432. }
  433. }
  434. // StopJobWithJobSidecar sends a termination signal to a job running with a sidecar
  435. func (a *Agent) StopJobWithJobSidecar(namespace, name string) error {
  436. jobPods, err := a.GetJobPods(namespace, name)
  437. if err != nil {
  438. return err
  439. }
  440. podName := jobPods[0].ObjectMeta.Name
  441. restConf, err := a.RESTClientGetter.ToRESTConfig()
  442. restConf.GroupVersion = &schema.GroupVersion{
  443. Group: "api",
  444. Version: "v1",
  445. }
  446. restConf.NegotiatedSerializer = runtime.NewSimpleNegotiatedSerializer(runtime.SerializerInfo{})
  447. restClient, err := rest.RESTClientFor(restConf)
  448. if err != nil {
  449. return err
  450. }
  451. req := restClient.Post().
  452. Resource("pods").
  453. Name(podName).
  454. Namespace(namespace).
  455. SubResource("exec")
  456. req.Param("command", "./signal.sh")
  457. req.Param("container", "sidecar")
  458. req.Param("stdin", "true")
  459. req.Param("stdout", "false")
  460. req.Param("tty", "false")
  461. exec, err := remotecommand.NewSPDYExecutor(restConf, "POST", req.URL())
  462. if err != nil {
  463. return err
  464. }
  465. return exec.Stream(remotecommand.StreamOptions{
  466. Tty: false,
  467. Stdin: strings.NewReader("./signal.sh"),
  468. })
  469. }
  470. // StreamControllerStatus streams controller status. Supports Deployment, StatefulSet, ReplicaSet, and DaemonSet
  471. // TODO: Support Jobs
  472. func (a *Agent) StreamControllerStatus(conn *websocket.Conn, kind string, selectors string) error {
  473. // selectors is an array of max length 1. StreamControllerStatus accepts calls without the selectors argument.
  474. // selectors argument is a single string with comma separated key=value pairs. (e.g. "app=porter,porter=true")
  475. tweakListOptionsFunc := func(options *metav1.ListOptions) {
  476. options.LabelSelector = selectors
  477. }
  478. factory := informers.NewSharedInformerFactoryWithOptions(
  479. a.Clientset,
  480. 0,
  481. informers.WithTweakListOptions(tweakListOptionsFunc),
  482. )
  483. var informer cache.SharedInformer
  484. // Spins up an informer depending on kind. Convert to lowercase for robustness
  485. switch strings.ToLower(kind) {
  486. case "deployment":
  487. informer = factory.Apps().V1().Deployments().Informer()
  488. case "statefulset":
  489. informer = factory.Apps().V1().StatefulSets().Informer()
  490. case "replicaset":
  491. informer = factory.Apps().V1().ReplicaSets().Informer()
  492. case "daemonset":
  493. informer = factory.Apps().V1().DaemonSets().Informer()
  494. case "job":
  495. informer = factory.Batch().V1().Jobs().Informer()
  496. case "cronjob":
  497. informer = factory.Batch().V1beta1().CronJobs().Informer()
  498. case "namespace":
  499. informer = factory.Core().V1().Namespaces().Informer()
  500. case "pod":
  501. informer = factory.Core().V1().Pods().Informer()
  502. }
  503. stopper := make(chan struct{})
  504. errorchan := make(chan error)
  505. defer close(stopper)
  506. informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  507. UpdateFunc: func(oldObj, newObj interface{}) {
  508. msg := Message{
  509. EventType: "UPDATE",
  510. Object: newObj,
  511. Kind: strings.ToLower(kind),
  512. }
  513. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  514. errorchan <- writeErr
  515. return
  516. }
  517. },
  518. AddFunc: func(obj interface{}) {
  519. msg := Message{
  520. EventType: "ADD",
  521. Object: obj,
  522. Kind: strings.ToLower(kind),
  523. }
  524. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  525. errorchan <- writeErr
  526. return
  527. }
  528. },
  529. DeleteFunc: func(obj interface{}) {
  530. msg := Message{
  531. EventType: "DELETE",
  532. Object: obj,
  533. Kind: strings.ToLower(kind),
  534. }
  535. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  536. errorchan <- writeErr
  537. return
  538. }
  539. },
  540. })
  541. go func() {
  542. // listens for websocket closing handshake
  543. for {
  544. if _, _, err := conn.ReadMessage(); err != nil {
  545. conn.Close()
  546. errorchan <- nil
  547. return
  548. }
  549. }
  550. }()
  551. go informer.Run(stopper)
  552. for {
  553. select {
  554. case err := <-errorchan:
  555. return err
  556. }
  557. }
  558. }
  559. var b64 = base64.StdEncoding
  560. var magicGzip = []byte{0x1f, 0x8b, 0x08}
  561. func decodeRelease(data string) (*rspb.Release, error) {
  562. // base64 decode string
  563. b, err := b64.DecodeString(data)
  564. if err != nil {
  565. return nil, err
  566. }
  567. // For backwards compatibility with releases that were stored before
  568. // compression was introduced we skip decompression if the
  569. // gzip magic header is not found
  570. if bytes.Equal(b[0:3], magicGzip) {
  571. r, err := gzip.NewReader(bytes.NewReader(b))
  572. if err != nil {
  573. return nil, err
  574. }
  575. defer r.Close()
  576. b2, err := ioutil.ReadAll(r)
  577. if err != nil {
  578. return nil, err
  579. }
  580. b = b2
  581. }
  582. var rls rspb.Release
  583. // unmarshal release object bytes
  584. if err := json.Unmarshal(b, &rls); err != nil {
  585. return nil, err
  586. }
  587. return &rls, nil
  588. }
  589. func contains(s []string, str string) bool {
  590. for _, v := range s {
  591. if v == str {
  592. return true
  593. }
  594. }
  595. return false
  596. }
  597. func parseSecretToHelmRelease(secret v1.Secret, chartList []string) (*rspb.Release, bool, error) {
  598. if secret.Type != "helm.sh/release.v1" {
  599. return nil, true, nil
  600. }
  601. releaseData, ok := secret.Data["release"]
  602. if !ok {
  603. return nil, true, fmt.Errorf("release field not found")
  604. }
  605. helm_object, err := decodeRelease(string(releaseData))
  606. if err != nil {
  607. return nil, true, err
  608. }
  609. if len(chartList) > 0 && !contains(chartList, helm_object.Name) {
  610. return nil, true, nil
  611. }
  612. return helm_object, false, nil
  613. }
  614. func (a *Agent) StreamHelmReleases(conn *websocket.Conn, chartList []string, selectors string) error {
  615. tweakListOptionsFunc := func(options *metav1.ListOptions) {
  616. options.LabelSelector = selectors
  617. }
  618. factory := informers.NewSharedInformerFactoryWithOptions(
  619. a.Clientset,
  620. 0,
  621. informers.WithTweakListOptions(tweakListOptionsFunc),
  622. )
  623. informer := factory.Core().V1().Secrets().Informer()
  624. stopper := make(chan struct{})
  625. errorchan := make(chan error)
  626. defer close(stopper)
  627. informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  628. UpdateFunc: func(oldObj, newObj interface{}) {
  629. secretObj, ok := newObj.(*v1.Secret)
  630. if !ok {
  631. errorchan <- fmt.Errorf("could not cast to secret")
  632. return
  633. }
  634. helm_object, isNotHelmRelease, err := parseSecretToHelmRelease(*secretObj, chartList)
  635. if isNotHelmRelease && err == nil {
  636. return
  637. }
  638. if err != nil {
  639. errorchan <- err
  640. return
  641. }
  642. msg := Message{
  643. EventType: "UPDATE",
  644. Object: helm_object,
  645. }
  646. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  647. errorchan <- writeErr
  648. return
  649. }
  650. },
  651. AddFunc: func(obj interface{}) {
  652. secretObj, ok := obj.(*v1.Secret)
  653. if !ok {
  654. errorchan <- fmt.Errorf("could not cast to secret")
  655. return
  656. }
  657. helm_object, isNotHelmRelease, err := parseSecretToHelmRelease(*secretObj, chartList)
  658. if isNotHelmRelease && err == nil {
  659. return
  660. }
  661. if err != nil {
  662. errorchan <- err
  663. return
  664. }
  665. msg := Message{
  666. EventType: "ADD",
  667. Object: helm_object,
  668. }
  669. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  670. errorchan <- writeErr
  671. return
  672. }
  673. },
  674. DeleteFunc: func(obj interface{}) {
  675. secretObj, ok := obj.(*v1.Secret)
  676. if !ok {
  677. errorchan <- fmt.Errorf("could not cast to secret")
  678. return
  679. }
  680. helm_object, isNotHelmRelease, err := parseSecretToHelmRelease(*secretObj, chartList)
  681. if isNotHelmRelease && err == nil {
  682. return
  683. }
  684. if err != nil {
  685. errorchan <- err
  686. return
  687. }
  688. msg := Message{
  689. EventType: "DELETE",
  690. Object: helm_object,
  691. }
  692. if writeErr := conn.WriteJSON(msg); writeErr != nil {
  693. errorchan <- writeErr
  694. return
  695. }
  696. },
  697. })
  698. go func() {
  699. // listens for websocket closing handshake
  700. for {
  701. if _, _, err := conn.ReadMessage(); err != nil {
  702. conn.Close()
  703. errorchan <- nil
  704. return
  705. }
  706. }
  707. }()
  708. go informer.Run(stopper)
  709. for {
  710. select {
  711. case err := <-errorchan:
  712. return err
  713. }
  714. }
  715. }
  716. // ProvisionECR spawns a new provisioning pod that creates an ECR instance
  717. func (a *Agent) ProvisionECR(
  718. projectID uint,
  719. awsConf *integrations.AWSIntegration,
  720. ecrName string,
  721. repo repository.Repository,
  722. infra *models.Infra,
  723. operation provisioner.ProvisionerOperation,
  724. pgConf *config.DBConf,
  725. redisConf *config.RedisConf,
  726. provImageTag string,
  727. provImagePullSecret string,
  728. ) (*batchv1.Job, error) {
  729. id := infra.GetUniqueName()
  730. prov := &provisioner.Conf{
  731. ID: id,
  732. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  733. Kind: provisioner.ECR,
  734. Operation: operation,
  735. Redis: redisConf,
  736. Postgres: pgConf,
  737. ProvisionerImageTag: provImageTag,
  738. ImagePullSecret: provImagePullSecret,
  739. LastApplied: infra.LastApplied,
  740. AWS: &aws.Conf{
  741. AWSRegion: awsConf.AWSRegion,
  742. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  743. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  744. },
  745. ECR: &ecr.Conf{
  746. ECRName: ecrName,
  747. },
  748. }
  749. return a.provision(prov, infra, repo)
  750. }
  751. // ProvisionEKS spawns a new provisioning pod that creates an EKS instance
  752. func (a *Agent) ProvisionEKS(
  753. projectID uint,
  754. awsConf *integrations.AWSIntegration,
  755. eksName, machineType string,
  756. repo repository.Repository,
  757. infra *models.Infra,
  758. operation provisioner.ProvisionerOperation,
  759. pgConf *config.DBConf,
  760. redisConf *config.RedisConf,
  761. provImageTag string,
  762. provImagePullSecret string,
  763. ) (*batchv1.Job, error) {
  764. id := infra.GetUniqueName()
  765. prov := &provisioner.Conf{
  766. ID: id,
  767. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  768. Kind: provisioner.EKS,
  769. Operation: operation,
  770. Redis: redisConf,
  771. Postgres: pgConf,
  772. ProvisionerImageTag: provImageTag,
  773. ImagePullSecret: provImagePullSecret,
  774. LastApplied: infra.LastApplied,
  775. AWS: &aws.Conf{
  776. AWSRegion: awsConf.AWSRegion,
  777. AWSAccessKeyID: string(awsConf.AWSAccessKeyID),
  778. AWSSecretAccessKey: string(awsConf.AWSSecretAccessKey),
  779. },
  780. EKS: &eks.Conf{
  781. ClusterName: eksName,
  782. MachineType: machineType,
  783. },
  784. }
  785. return a.provision(prov, infra, repo)
  786. }
  787. // ProvisionGCR spawns a new provisioning pod that creates a GCR instance
  788. func (a *Agent) ProvisionGCR(
  789. projectID uint,
  790. gcpConf *integrations.GCPIntegration,
  791. repo repository.Repository,
  792. infra *models.Infra,
  793. operation provisioner.ProvisionerOperation,
  794. pgConf *config.DBConf,
  795. redisConf *config.RedisConf,
  796. provImageTag string,
  797. provImagePullSecret string,
  798. ) (*batchv1.Job, error) {
  799. id := infra.GetUniqueName()
  800. prov := &provisioner.Conf{
  801. ID: id,
  802. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  803. Kind: provisioner.GCR,
  804. Operation: operation,
  805. Redis: redisConf,
  806. Postgres: pgConf,
  807. ProvisionerImageTag: provImageTag,
  808. ImagePullSecret: provImagePullSecret,
  809. LastApplied: infra.LastApplied,
  810. GCP: &gcp.Conf{
  811. GCPRegion: gcpConf.GCPRegion,
  812. GCPProjectID: gcpConf.GCPProjectID,
  813. GCPKeyData: string(gcpConf.GCPKeyData),
  814. },
  815. }
  816. return a.provision(prov, infra, repo)
  817. }
  818. // ProvisionGKE spawns a new provisioning pod that creates a GKE instance
  819. func (a *Agent) ProvisionGKE(
  820. projectID uint,
  821. gcpConf *integrations.GCPIntegration,
  822. gkeName string,
  823. repo repository.Repository,
  824. infra *models.Infra,
  825. operation provisioner.ProvisionerOperation,
  826. pgConf *config.DBConf,
  827. redisConf *config.RedisConf,
  828. provImageTag string,
  829. provImagePullSecret string,
  830. ) (*batchv1.Job, error) {
  831. id := infra.GetUniqueName()
  832. prov := &provisioner.Conf{
  833. ID: id,
  834. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  835. Kind: provisioner.GKE,
  836. Operation: operation,
  837. Redis: redisConf,
  838. Postgres: pgConf,
  839. ProvisionerImageTag: provImageTag,
  840. ImagePullSecret: provImagePullSecret,
  841. LastApplied: infra.LastApplied,
  842. GCP: &gcp.Conf{
  843. GCPRegion: gcpConf.GCPRegion,
  844. GCPProjectID: gcpConf.GCPProjectID,
  845. GCPKeyData: string(gcpConf.GCPKeyData),
  846. },
  847. GKE: &gke.Conf{
  848. ClusterName: gkeName,
  849. },
  850. }
  851. return a.provision(prov, infra, repo)
  852. }
  853. // ProvisionDOCR spawns a new provisioning pod that creates a DOCR instance
  854. func (a *Agent) ProvisionDOCR(
  855. projectID uint,
  856. doConf *integrations.OAuthIntegration,
  857. doAuth *oauth2.Config,
  858. repo repository.Repository,
  859. docrName, docrSubscriptionTier string,
  860. infra *models.Infra,
  861. operation provisioner.ProvisionerOperation,
  862. pgConf *config.DBConf,
  863. redisConf *config.RedisConf,
  864. provImageTag string,
  865. provImagePullSecret string,
  866. ) (*batchv1.Job, error) {
  867. // get the token
  868. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  869. infra.DOIntegrationID,
  870. )
  871. if err != nil {
  872. return nil, err
  873. }
  874. tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
  875. if err != nil {
  876. return nil, err
  877. }
  878. id := infra.GetUniqueName()
  879. prov := &provisioner.Conf{
  880. ID: id,
  881. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  882. Kind: provisioner.DOCR,
  883. Operation: operation,
  884. Redis: redisConf,
  885. Postgres: pgConf,
  886. ProvisionerImageTag: provImageTag,
  887. ImagePullSecret: provImagePullSecret,
  888. LastApplied: infra.LastApplied,
  889. DO: &do.Conf{
  890. DOToken: tok,
  891. },
  892. DOCR: &docr.Conf{
  893. DOCRName: docrName,
  894. DOCRSubscriptionTier: docrSubscriptionTier,
  895. },
  896. }
  897. return a.provision(prov, infra, repo)
  898. }
  899. // ProvisionDOKS spawns a new provisioning pod that creates a DOKS instance
  900. func (a *Agent) ProvisionDOKS(
  901. projectID uint,
  902. doConf *integrations.OAuthIntegration,
  903. doAuth *oauth2.Config,
  904. repo repository.Repository,
  905. doRegion, doksClusterName string,
  906. infra *models.Infra,
  907. operation provisioner.ProvisionerOperation,
  908. pgConf *config.DBConf,
  909. redisConf *config.RedisConf,
  910. provImageTag string,
  911. provImagePullSecret string,
  912. ) (*batchv1.Job, error) {
  913. // get the token
  914. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  915. infra.DOIntegrationID,
  916. )
  917. if err != nil {
  918. return nil, err
  919. }
  920. tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
  921. if err != nil {
  922. return nil, err
  923. }
  924. id := infra.GetUniqueName()
  925. prov := &provisioner.Conf{
  926. ID: id,
  927. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  928. Kind: provisioner.DOKS,
  929. Operation: operation,
  930. Redis: redisConf,
  931. Postgres: pgConf,
  932. LastApplied: infra.LastApplied,
  933. ProvisionerImageTag: provImageTag,
  934. ImagePullSecret: provImagePullSecret,
  935. DO: &do.Conf{
  936. DOToken: tok,
  937. },
  938. DOKS: &doks.Conf{
  939. DORegion: doRegion,
  940. DOKSClusterName: doksClusterName,
  941. },
  942. }
  943. return a.provision(prov, infra, repo)
  944. }
  945. // ProvisionTest spawns a new provisioning pod that tests provisioning
  946. func (a *Agent) ProvisionTest(
  947. projectID uint,
  948. infra *models.Infra,
  949. repo repository.Repository,
  950. operation provisioner.ProvisionerOperation,
  951. pgConf *config.DBConf,
  952. redisConf *config.RedisConf,
  953. provImageTag string,
  954. provImagePullSecret string,
  955. ) (*batchv1.Job, error) {
  956. id := infra.GetUniqueName()
  957. prov := &provisioner.Conf{
  958. ID: id,
  959. Name: fmt.Sprintf("prov-%s-%s", id, string(operation)),
  960. Operation: operation,
  961. Kind: provisioner.Test,
  962. Redis: redisConf,
  963. Postgres: pgConf,
  964. ProvisionerImageTag: provImageTag,
  965. ImagePullSecret: provImagePullSecret,
  966. }
  967. return a.provision(prov, infra, repo)
  968. }
  969. func (a *Agent) provision(
  970. prov *provisioner.Conf,
  971. infra *models.Infra,
  972. repo repository.Repository,
  973. ) (*batchv1.Job, error) {
  974. prov.Namespace = "default"
  975. job, err := prov.GetProvisionerJobTemplate()
  976. if err != nil {
  977. return nil, err
  978. }
  979. job, err = a.Clientset.BatchV1().Jobs(prov.Namespace).Create(
  980. context.TODO(),
  981. job,
  982. metav1.CreateOptions{},
  983. )
  984. if err != nil {
  985. return nil, err
  986. }
  987. infra.LastApplied = prov.LastApplied
  988. infra, err = repo.Infra.UpdateInfra(infra)
  989. if err != nil {
  990. return nil, err
  991. }
  992. return job, nil
  993. }
  994. // CreateImagePullSecrets will create the required image pull secrets and
  995. // return a map from the registry name to the name of the secret.
  996. func (a *Agent) CreateImagePullSecrets(
  997. repo repository.Repository,
  998. namespace string,
  999. linkedRegs map[string]*models.Registry,
  1000. doAuth *oauth2.Config,
  1001. ) (map[string]string, error) {
  1002. res := make(map[string]string)
  1003. for key, val := range linkedRegs {
  1004. _reg := registry.Registry(*val)
  1005. data, err := _reg.GetDockerConfigJSON(repo, doAuth)
  1006. if err != nil {
  1007. return nil, err
  1008. }
  1009. secretName := fmt.Sprintf("porter-%s-%d", val.Externalize().Service, val.ID)
  1010. secret, err := a.Clientset.CoreV1().Secrets(namespace).Get(
  1011. context.TODO(),
  1012. secretName,
  1013. metav1.GetOptions{},
  1014. )
  1015. // if not found, create the secret
  1016. if err != nil && errors.IsNotFound(err) {
  1017. _, err = a.Clientset.CoreV1().Secrets(namespace).Create(
  1018. context.TODO(),
  1019. &v1.Secret{
  1020. ObjectMeta: metav1.ObjectMeta{
  1021. Name: secretName,
  1022. },
  1023. Data: map[string][]byte{
  1024. string(v1.DockerConfigJsonKey): data,
  1025. },
  1026. Type: v1.SecretTypeDockerConfigJson,
  1027. },
  1028. metav1.CreateOptions{},
  1029. )
  1030. if err != nil {
  1031. return nil, err
  1032. }
  1033. // add secret name to the map
  1034. res[key] = secretName
  1035. continue
  1036. } else if err != nil {
  1037. return nil, err
  1038. }
  1039. // otherwise, check that the secret contains the correct data: if
  1040. // if doesn't, update it
  1041. if !bytes.Equal(secret.Data[v1.DockerConfigJsonKey], data) {
  1042. _, err := a.Clientset.CoreV1().Secrets(namespace).Update(
  1043. context.TODO(),
  1044. &v1.Secret{
  1045. ObjectMeta: metav1.ObjectMeta{
  1046. Name: secretName,
  1047. },
  1048. Data: map[string][]byte{
  1049. string(v1.DockerConfigJsonKey): data,
  1050. },
  1051. Type: v1.SecretTypeDockerConfigJson,
  1052. },
  1053. metav1.UpdateOptions{},
  1054. )
  1055. if err != nil {
  1056. return nil, err
  1057. }
  1058. }
  1059. // add secret name to the map
  1060. res[key] = secretName
  1061. }
  1062. return res, nil
  1063. }