agent.go 26 KB

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