agent.go 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  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. // check if namespace exists
  227. checkNS, err := a.Clientset.CoreV1().Namespaces().Get(
  228. context.TODO(),
  229. name,
  230. metav1.GetOptions{},
  231. )
  232. if err == nil && checkNS != nil {
  233. return checkNS, nil
  234. }
  235. namespace := v1.Namespace{
  236. ObjectMeta: metav1.ObjectMeta{
  237. Name: name,
  238. },
  239. }
  240. return a.Clientset.CoreV1().Namespaces().Create(
  241. context.TODO(),
  242. &namespace,
  243. metav1.CreateOptions{},
  244. )
  245. }
  246. // DeleteNamespace deletes the namespace given the name.
  247. func (a *Agent) DeleteNamespace(name string) error {
  248. return a.Clientset.CoreV1().Namespaces().Delete(
  249. context.TODO(),
  250. name,
  251. metav1.DeleteOptions{},
  252. )
  253. }
  254. func (a *Agent) GetPorterAgent() (*appsv1.Deployment, error) {
  255. depl, err := a.Clientset.AppsV1().Deployments("porter-agent-system").Get(
  256. context.TODO(),
  257. "porter-agent-controller-manager",
  258. metav1.GetOptions{},
  259. )
  260. if err != nil && errors.IsNotFound(err) {
  261. return nil, IsNotFoundError
  262. }
  263. return depl, err
  264. }
  265. // ListJobsByLabel lists jobs in a namespace matching a label
  266. type Label struct {
  267. Key string
  268. Val string
  269. }
  270. func (a *Agent) ListJobsByLabel(namespace string, labels ...Label) ([]batchv1.Job, error) {
  271. selectors := make([]string, 0)
  272. for _, label := range labels {
  273. selectors = append(selectors, fmt.Sprintf("%s=%s", label.Key, label.Val))
  274. }
  275. resp, err := a.Clientset.BatchV1().Jobs(namespace).List(
  276. context.TODO(),
  277. metav1.ListOptions{
  278. LabelSelector: strings.Join(selectors, ","),
  279. },
  280. )
  281. if err != nil {
  282. return nil, err
  283. }
  284. return resp.Items, nil
  285. }
  286. // DeleteJob deletes the job in the given name and namespace.
  287. func (a *Agent) DeleteJob(name, namespace string) error {
  288. return a.Clientset.BatchV1().Jobs(namespace).Delete(
  289. context.TODO(),
  290. name,
  291. metav1.DeleteOptions{},
  292. )
  293. }
  294. // GetJobPods lists all pods belonging to a job in a namespace
  295. func (a *Agent) GetJobPods(namespace, jobName string) ([]v1.Pod, error) {
  296. resp, err := a.Clientset.CoreV1().Pods(namespace).List(
  297. context.TODO(),
  298. metav1.ListOptions{
  299. LabelSelector: fmt.Sprintf("%s=%s", "job-name", jobName),
  300. },
  301. )
  302. if err != nil {
  303. return nil, err
  304. }
  305. return resp.Items, nil
  306. }
  307. // GetIngress gets ingress given the name and namespace
  308. func (a *Agent) GetIngress(namespace string, name string) (*v1beta1.Ingress, error) {
  309. resp, err := a.Clientset.ExtensionsV1beta1().Ingresses(namespace).Get(
  310. context.TODO(),
  311. name,
  312. metav1.GetOptions{},
  313. )
  314. if err != nil && errors.IsNotFound(err) {
  315. return nil, IsNotFoundError
  316. } else if err != nil {
  317. return nil, err
  318. }
  319. return resp, nil
  320. }
  321. var IsNotFoundError = fmt.Errorf("not found")
  322. type BadRequestError struct {
  323. msg string
  324. }
  325. func (e *BadRequestError) Error() string {
  326. return e.msg
  327. }
  328. // GetDeployment gets the deployment given the name and namespace
  329. func (a *Agent) GetDeployment(c grapher.Object) (*appsv1.Deployment, error) {
  330. res, err := a.Clientset.AppsV1().Deployments(c.Namespace).Get(
  331. context.TODO(),
  332. c.Name,
  333. metav1.GetOptions{},
  334. )
  335. if err != nil && errors.IsNotFound(err) {
  336. return nil, IsNotFoundError
  337. } else if err != nil {
  338. return nil, err
  339. }
  340. res.Kind = c.Kind
  341. return res, nil
  342. }
  343. // GetStatefulSet gets the statefulset given the name and namespace
  344. func (a *Agent) GetStatefulSet(c grapher.Object) (*appsv1.StatefulSet, error) {
  345. res, err := a.Clientset.AppsV1().StatefulSets(c.Namespace).Get(
  346. context.TODO(),
  347. c.Name,
  348. metav1.GetOptions{},
  349. )
  350. if err != nil && errors.IsNotFound(err) {
  351. return nil, IsNotFoundError
  352. } else if err != nil {
  353. return nil, err
  354. }
  355. res.Kind = c.Kind
  356. return res, nil
  357. }
  358. // GetReplicaSet gets the replicaset given the name and namespace
  359. func (a *Agent) GetReplicaSet(c grapher.Object) (*appsv1.ReplicaSet, error) {
  360. res, err := a.Clientset.AppsV1().ReplicaSets(c.Namespace).Get(
  361. context.TODO(),
  362. c.Name,
  363. metav1.GetOptions{},
  364. )
  365. if err != nil && errors.IsNotFound(err) {
  366. return nil, IsNotFoundError
  367. } else if err != nil {
  368. return nil, err
  369. }
  370. res.Kind = c.Kind
  371. return res, nil
  372. }
  373. // GetDaemonSet gets the daemonset by name and namespace
  374. func (a *Agent) GetDaemonSet(c grapher.Object) (*appsv1.DaemonSet, error) {
  375. res, err := a.Clientset.AppsV1().DaemonSets(c.Namespace).Get(
  376. context.TODO(),
  377. c.Name,
  378. metav1.GetOptions{},
  379. )
  380. if err != nil && errors.IsNotFound(err) {
  381. return nil, IsNotFoundError
  382. } else if err != nil {
  383. return nil, err
  384. }
  385. res.Kind = c.Kind
  386. return res, nil
  387. }
  388. // GetJob gets the job by name and namespace
  389. func (a *Agent) GetJob(c grapher.Object) (*batchv1.Job, error) {
  390. res, err := a.Clientset.BatchV1().Jobs(c.Namespace).Get(
  391. context.TODO(),
  392. c.Name,
  393. metav1.GetOptions{},
  394. )
  395. if err != nil && errors.IsNotFound(err) {
  396. return nil, IsNotFoundError
  397. } else if err != nil {
  398. return nil, err
  399. }
  400. res.Kind = c.Kind
  401. return res, nil
  402. }
  403. // GetCronJob gets the CronJob by name and namespace
  404. func (a *Agent) GetCronJob(c grapher.Object) (*batchv1beta1.CronJob, error) {
  405. res, err := a.Clientset.BatchV1beta1().CronJobs(c.Namespace).Get(
  406. context.TODO(),
  407. c.Name,
  408. metav1.GetOptions{},
  409. )
  410. if err != nil && errors.IsNotFound(err) {
  411. return nil, IsNotFoundError
  412. } else if err != nil {
  413. return nil, err
  414. }
  415. res.Kind = c.Kind
  416. return res, nil
  417. }
  418. // GetPodsByLabel retrieves pods with matching labels
  419. func (a *Agent) GetPodsByLabel(selector string, namespace string) (*v1.PodList, error) {
  420. // Search in all namespaces for matching pods
  421. return a.Clientset.CoreV1().Pods(namespace).List(
  422. context.TODO(),
  423. metav1.ListOptions{
  424. LabelSelector: selector,
  425. },
  426. )
  427. }
  428. // GetPodByName retrieves a single instance of pod with given name
  429. func (a *Agent) GetPodByName(name string, namespace string) (*v1.Pod, error) {
  430. // Get pod by name
  431. pod, err := a.Clientset.CoreV1().Pods(namespace).Get(
  432. context.TODO(),
  433. name,
  434. metav1.GetOptions{},
  435. )
  436. if err != nil && errors.IsNotFound(err) {
  437. return nil, IsNotFoundError
  438. }
  439. if err != nil {
  440. return nil, err
  441. }
  442. return pod, nil
  443. }
  444. // DeletePod deletes a pod by name and namespace
  445. func (a *Agent) DeletePod(namespace string, name string) error {
  446. err := a.Clientset.CoreV1().Pods(namespace).Delete(
  447. context.TODO(),
  448. name,
  449. metav1.DeleteOptions{},
  450. )
  451. if err != nil && errors.IsNotFound(err) {
  452. return IsNotFoundError
  453. }
  454. return err
  455. }
  456. // GetPodLogs streams real-time logs from a given pod.
  457. func (a *Agent) GetPodLogs(namespace string, name string, rw *websocket.WebsocketSafeReadWriter) error {
  458. // get the pod to read in the list of contains
  459. pod, err := a.Clientset.CoreV1().Pods(namespace).Get(
  460. context.Background(),
  461. name,
  462. metav1.GetOptions{},
  463. )
  464. if err != nil && errors.IsNotFound(err) {
  465. return IsNotFoundError
  466. } else if err != nil {
  467. return fmt.Errorf("Cannot get logs from pod %s: %s", name, err.Error())
  468. }
  469. // see if container is ready and able to open a stream. If not, wait for container
  470. // to be ready.
  471. err, _ = a.waitForPod(pod)
  472. if err != nil && goerrors.Is(err, IsNotFoundError) {
  473. return IsNotFoundError
  474. } else if err != nil {
  475. return fmt.Errorf("Cannot get logs from pod %s: %s", name, err.Error())
  476. }
  477. container := pod.Spec.Containers[0].Name
  478. tails := int64(400)
  479. // follow logs
  480. podLogOpts := v1.PodLogOptions{
  481. Follow: true,
  482. TailLines: &tails,
  483. Container: container,
  484. }
  485. req := a.Clientset.CoreV1().Pods(namespace).GetLogs(name, &podLogOpts)
  486. podLogs, err := req.Stream(context.TODO())
  487. // in the case of bad request errors, such as if the pod is stuck in "ContainerCreating",
  488. // we'd like to pass this through to the client.
  489. if err != nil && errors.IsBadRequest(err) {
  490. return &BadRequestError{err.Error()}
  491. } else if err != nil {
  492. return fmt.Errorf("Cannot open log stream for pod %s: %s", name, err.Error())
  493. }
  494. defer podLogs.Close()
  495. r := bufio.NewReader(podLogs)
  496. errorchan := make(chan error)
  497. go func() {
  498. // listens for websocket closing handshake
  499. for {
  500. if _, _, err := rw.ReadMessage(); err != nil {
  501. errorchan <- nil
  502. return
  503. }
  504. }
  505. }()
  506. go func() {
  507. for {
  508. select {
  509. case <-errorchan:
  510. defer close(errorchan)
  511. return
  512. default:
  513. }
  514. bytes, err := r.ReadBytes('\n')
  515. if _, writeErr := rw.Write(bytes); writeErr != nil {
  516. errorchan <- writeErr
  517. return
  518. }
  519. if err != nil {
  520. if err != io.EOF {
  521. errorchan <- err
  522. return
  523. }
  524. errorchan <- nil
  525. return
  526. }
  527. }
  528. }()
  529. for {
  530. select {
  531. case err = <-errorchan:
  532. return err
  533. }
  534. }
  535. }
  536. // StopJobWithJobSidecar sends a termination signal to a job running with a sidecar
  537. func (a *Agent) StopJobWithJobSidecar(namespace, name string) error {
  538. jobPods, err := a.GetJobPods(namespace, name)
  539. if err != nil {
  540. return err
  541. }
  542. podName := jobPods[0].ObjectMeta.Name
  543. restConf, err := a.RESTClientGetter.ToRESTConfig()
  544. restConf.GroupVersion = &schema.GroupVersion{
  545. Group: "api",
  546. Version: "v1",
  547. }
  548. restConf.NegotiatedSerializer = runtime.NewSimpleNegotiatedSerializer(runtime.SerializerInfo{})
  549. restClient, err := rest.RESTClientFor(restConf)
  550. if err != nil {
  551. return err
  552. }
  553. req := restClient.Post().
  554. Resource("pods").
  555. Name(podName).
  556. Namespace(namespace).
  557. SubResource("exec")
  558. req.Param("command", "./signal.sh")
  559. req.Param("container", "sidecar")
  560. req.Param("stdin", "true")
  561. req.Param("stdout", "false")
  562. req.Param("tty", "false")
  563. exec, err := remotecommand.NewSPDYExecutor(restConf, "POST", req.URL())
  564. if err != nil {
  565. return err
  566. }
  567. return exec.Stream(remotecommand.StreamOptions{
  568. Tty: false,
  569. Stdin: strings.NewReader("./signal.sh"),
  570. })
  571. }
  572. // RunWebsocketTask will run a websocket task. If the websocket returns an anauthorized error, it will restart
  573. // the task some number of times until failing
  574. func (a *Agent) RunWebsocketTask(task func() error) error {
  575. lastTime := int64(0)
  576. for {
  577. if err := a.UpdateClientset(); err != nil {
  578. return err
  579. }
  580. err := task()
  581. if err == nil {
  582. return nil
  583. }
  584. if !errors2.Is(err, &AuthError{}) {
  585. return err
  586. }
  587. if time.Now().Unix()-lastTime < 60 { // don't regenerate connection if too many unauthorized errors
  588. return err
  589. }
  590. lastTime = time.Now().Unix()
  591. }
  592. }
  593. // StreamControllerStatus streams controller status. Supports Deployment, StatefulSet, ReplicaSet, and DaemonSet
  594. // TODO: Support Jobs
  595. func (a *Agent) StreamControllerStatus(kind string, selectors string, rw *websocket.WebsocketSafeReadWriter) error {
  596. run := func() error {
  597. // selectors is an array of max length 1. StreamControllerStatus accepts calls without the selectors argument.
  598. // selectors argument is a single string with comma separated key=value pairs. (e.g. "app=porter,porter=true")
  599. tweakListOptionsFunc := func(options *metav1.ListOptions) {
  600. options.LabelSelector = selectors
  601. }
  602. factory := informers.NewSharedInformerFactoryWithOptions(
  603. a.Clientset,
  604. 0,
  605. informers.WithTweakListOptions(tweakListOptionsFunc),
  606. )
  607. var informer cache.SharedInformer
  608. // Spins up an informer depending on kind. Convert to lowercase for robustness
  609. switch strings.ToLower(kind) {
  610. case "deployment":
  611. informer = factory.Apps().V1().Deployments().Informer()
  612. case "statefulset":
  613. informer = factory.Apps().V1().StatefulSets().Informer()
  614. case "replicaset":
  615. informer = factory.Apps().V1().ReplicaSets().Informer()
  616. case "daemonset":
  617. informer = factory.Apps().V1().DaemonSets().Informer()
  618. case "job":
  619. informer = factory.Batch().V1().Jobs().Informer()
  620. case "cronjob":
  621. informer = factory.Batch().V1beta1().CronJobs().Informer()
  622. case "namespace":
  623. informer = factory.Core().V1().Namespaces().Informer()
  624. case "pod":
  625. informer = factory.Core().V1().Pods().Informer()
  626. }
  627. stopper := make(chan struct{})
  628. errorchan := make(chan error)
  629. defer close(stopper)
  630. informer.SetWatchErrorHandler(func(r *cache.Reflector, err error) {
  631. if strings.HasSuffix(err.Error(), ": Unauthorized") {
  632. errorchan <- &AuthError{}
  633. }
  634. })
  635. informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  636. UpdateFunc: func(oldObj, newObj interface{}) {
  637. msg := Message{
  638. EventType: "UPDATE",
  639. Object: newObj,
  640. Kind: strings.ToLower(kind),
  641. }
  642. rw.WriteJSONWithChannel(msg, errorchan)
  643. },
  644. AddFunc: func(obj interface{}) {
  645. msg := Message{
  646. EventType: "ADD",
  647. Object: obj,
  648. Kind: strings.ToLower(kind),
  649. }
  650. rw.WriteJSONWithChannel(msg, errorchan)
  651. },
  652. DeleteFunc: func(obj interface{}) {
  653. msg := Message{
  654. EventType: "DELETE",
  655. Object: obj,
  656. Kind: strings.ToLower(kind),
  657. }
  658. rw.WriteJSONWithChannel(msg, errorchan)
  659. },
  660. })
  661. go func() {
  662. // listens for websocket closing handshake
  663. for {
  664. if _, _, err := rw.ReadMessage(); err != nil {
  665. errorchan <- nil
  666. return
  667. }
  668. }
  669. }()
  670. go informer.Run(stopper)
  671. for {
  672. select {
  673. case err := <-errorchan:
  674. return err
  675. }
  676. }
  677. }
  678. return a.RunWebsocketTask(run)
  679. }
  680. var b64 = base64.StdEncoding
  681. var magicGzip = []byte{0x1f, 0x8b, 0x08}
  682. func decodeRelease(data string) (*rspb.Release, error) {
  683. // base64 decode string
  684. b, err := b64.DecodeString(data)
  685. if err != nil {
  686. return nil, err
  687. }
  688. // For backwards compatibility with releases that were stored before
  689. // compression was introduced we skip decompression if the
  690. // gzip magic header is not found
  691. if bytes.Equal(b[0:3], magicGzip) {
  692. r, err := gzip.NewReader(bytes.NewReader(b))
  693. if err != nil {
  694. return nil, err
  695. }
  696. defer r.Close()
  697. b2, err := ioutil.ReadAll(r)
  698. if err != nil {
  699. return nil, err
  700. }
  701. b = b2
  702. }
  703. var rls rspb.Release
  704. // unmarshal release object bytes
  705. if err := json.Unmarshal(b, &rls); err != nil {
  706. return nil, err
  707. }
  708. return &rls, nil
  709. }
  710. func contains(s []string, str string) bool {
  711. for _, v := range s {
  712. if v == str {
  713. return true
  714. }
  715. }
  716. return false
  717. }
  718. func parseSecretToHelmRelease(secret v1.Secret, chartList []string) (*rspb.Release, bool, error) {
  719. if secret.Type != "helm.sh/release.v1" {
  720. return nil, true, nil
  721. }
  722. releaseData, ok := secret.Data["release"]
  723. if !ok {
  724. return nil, true, fmt.Errorf("release field not found")
  725. }
  726. helm_object, err := decodeRelease(string(releaseData))
  727. if err != nil {
  728. return nil, true, err
  729. }
  730. if len(chartList) > 0 && !contains(chartList, helm_object.Name) {
  731. return nil, true, nil
  732. }
  733. return helm_object, false, nil
  734. }
  735. func (a *Agent) StreamHelmReleases(namespace string, chartList []string, selectors string, rw *websocket.WebsocketSafeReadWriter) error {
  736. run := func() error {
  737. tweakListOptionsFunc := func(options *metav1.ListOptions) {
  738. options.LabelSelector = selectors
  739. }
  740. factory := informers.NewSharedInformerFactoryWithOptions(
  741. a.Clientset,
  742. 0,
  743. informers.WithTweakListOptions(tweakListOptionsFunc),
  744. informers.WithNamespace(namespace),
  745. )
  746. informer := factory.Core().V1().Secrets().Informer()
  747. stopper := make(chan struct{})
  748. errorchan := make(chan error)
  749. defer close(stopper)
  750. informer.SetWatchErrorHandler(func(r *cache.Reflector, err error) {
  751. if strings.HasSuffix(err.Error(), ": Unauthorized") {
  752. errorchan <- &AuthError{}
  753. }
  754. })
  755. informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  756. UpdateFunc: func(oldObj, newObj interface{}) {
  757. secretObj, ok := newObj.(*v1.Secret)
  758. if !ok {
  759. errorchan <- fmt.Errorf("could not cast to secret")
  760. return
  761. }
  762. helm_object, isNotHelmRelease, err := parseSecretToHelmRelease(*secretObj, chartList)
  763. if isNotHelmRelease && err == nil {
  764. return
  765. }
  766. if err != nil {
  767. errorchan <- err
  768. return
  769. }
  770. msg := Message{
  771. EventType: "UPDATE",
  772. Object: helm_object,
  773. }
  774. rw.WriteJSONWithChannel(msg, errorchan)
  775. },
  776. AddFunc: func(obj interface{}) {
  777. secretObj, ok := obj.(*v1.Secret)
  778. if !ok {
  779. errorchan <- fmt.Errorf("could not cast to secret")
  780. return
  781. }
  782. helm_object, isNotHelmRelease, err := parseSecretToHelmRelease(*secretObj, chartList)
  783. if isNotHelmRelease && err == nil {
  784. return
  785. }
  786. if err != nil {
  787. errorchan <- err
  788. return
  789. }
  790. msg := Message{
  791. EventType: "ADD",
  792. Object: helm_object,
  793. }
  794. rw.WriteJSONWithChannel(msg, errorchan)
  795. },
  796. DeleteFunc: func(obj interface{}) {
  797. secretObj, ok := obj.(*v1.Secret)
  798. if !ok {
  799. errorchan <- fmt.Errorf("could not cast to secret")
  800. return
  801. }
  802. helm_object, isNotHelmRelease, err := parseSecretToHelmRelease(*secretObj, chartList)
  803. if isNotHelmRelease && err == nil {
  804. return
  805. }
  806. if err != nil {
  807. errorchan <- err
  808. return
  809. }
  810. msg := Message{
  811. EventType: "DELETE",
  812. Object: helm_object,
  813. }
  814. rw.WriteJSONWithChannel(msg, errorchan)
  815. },
  816. })
  817. go func() {
  818. // listens for websocket closing handshake
  819. for {
  820. if _, _, err := rw.ReadMessage(); err != nil {
  821. errorchan <- nil
  822. return
  823. }
  824. }
  825. }()
  826. go informer.Run(stopper)
  827. for {
  828. select {
  829. case err := <-errorchan:
  830. return err
  831. }
  832. }
  833. }
  834. return a.RunWebsocketTask(run)
  835. }
  836. func (a *Agent) Provision(
  837. opts *provisioner.ProvisionOpts,
  838. ) error {
  839. // get the provisioner job template
  840. job, err := provisioner.GetProvisionerJobTemplate(opts)
  841. if err != nil {
  842. return err
  843. }
  844. // apply the provisioner job template
  845. _, err = a.Clientset.BatchV1().Jobs(opts.ProvJobNamespace).Create(
  846. context.TODO(),
  847. job,
  848. metav1.CreateOptions{},
  849. )
  850. return err
  851. }
  852. // CreateImagePullSecrets will create the required image pull secrets and
  853. // return a map from the registry name to the name of the secret.
  854. func (a *Agent) CreateImagePullSecrets(
  855. repo repository.Repository,
  856. namespace string,
  857. linkedRegs map[string]*models.Registry,
  858. doAuth *oauth2.Config,
  859. ) (map[string]string, error) {
  860. res := make(map[string]string)
  861. for key, val := range linkedRegs {
  862. _reg := registry.Registry(*val)
  863. data, err := _reg.GetDockerConfigJSON(repo, doAuth)
  864. if err != nil {
  865. return nil, err
  866. }
  867. secretName := fmt.Sprintf("porter-%s-%d", val.ToRegistryType().Service, val.ID)
  868. secret, err := a.Clientset.CoreV1().Secrets(namespace).Get(
  869. context.TODO(),
  870. secretName,
  871. metav1.GetOptions{},
  872. )
  873. // if not found, create the secret
  874. if err != nil && errors.IsNotFound(err) {
  875. _, err = a.Clientset.CoreV1().Secrets(namespace).Create(
  876. context.TODO(),
  877. &v1.Secret{
  878. ObjectMeta: metav1.ObjectMeta{
  879. Name: secretName,
  880. },
  881. Data: map[string][]byte{
  882. string(v1.DockerConfigJsonKey): data,
  883. },
  884. Type: v1.SecretTypeDockerConfigJson,
  885. },
  886. metav1.CreateOptions{},
  887. )
  888. if err != nil {
  889. return nil, err
  890. }
  891. // add secret name to the map
  892. res[key] = secretName
  893. continue
  894. } else if err != nil {
  895. return nil, err
  896. }
  897. // otherwise, check that the secret contains the correct data: if
  898. // if doesn't, update it
  899. if !bytes.Equal(secret.Data[v1.DockerConfigJsonKey], data) {
  900. _, err := a.Clientset.CoreV1().Secrets(namespace).Update(
  901. context.TODO(),
  902. &v1.Secret{
  903. ObjectMeta: metav1.ObjectMeta{
  904. Name: secretName,
  905. },
  906. Data: map[string][]byte{
  907. string(v1.DockerConfigJsonKey): data,
  908. },
  909. Type: v1.SecretTypeDockerConfigJson,
  910. },
  911. metav1.UpdateOptions{},
  912. )
  913. if err != nil {
  914. return nil, err
  915. }
  916. }
  917. // add secret name to the map
  918. res[key] = secretName
  919. }
  920. return res, nil
  921. }
  922. // helper that waits for pod to be ready
  923. func (a *Agent) waitForPod(pod *v1.Pod) (error, bool) {
  924. var (
  925. w watch.Interface
  926. err error
  927. ok bool
  928. )
  929. // immediately after creating a pod, the API may return a 404. heuristically 1
  930. // second seems to be plenty.
  931. watchRetries := 3
  932. for i := 0; i < watchRetries; i++ {
  933. selector := fields.OneTermEqualSelector("metadata.name", pod.Name).String()
  934. w, err = a.Clientset.CoreV1().
  935. Pods(pod.Namespace).
  936. Watch(context.Background(), metav1.ListOptions{FieldSelector: selector})
  937. if err == nil {
  938. break
  939. }
  940. time.Sleep(time.Second)
  941. }
  942. if err != nil {
  943. return err, false
  944. }
  945. defer w.Stop()
  946. for {
  947. select {
  948. case <-time.After(time.Second * 30):
  949. return goerrors.New("timed out waiting for pod"), false
  950. case <-time.Tick(time.Second):
  951. // poll every second in case we already missed the ready event while
  952. // creating the listener.
  953. pod, err = a.Clientset.CoreV1().
  954. Pods(pod.Namespace).
  955. Get(context.Background(), pod.Name, metav1.GetOptions{})
  956. if err != nil && errors.IsNotFound(err) {
  957. return IsNotFoundError, false
  958. } else if err != nil {
  959. return err, false
  960. }
  961. if isExited := isPodExited(pod); isExited || isPodReady(pod) {
  962. return nil, isExited
  963. }
  964. case evt := <-w.ResultChan():
  965. pod, ok = evt.Object.(*v1.Pod)
  966. if !ok {
  967. return fmt.Errorf("unexpected object type: %T", evt.Object), false
  968. }
  969. if isExited := isPodExited(pod); isExited || isPodReady(pod) {
  970. return nil, isExited
  971. }
  972. }
  973. }
  974. }
  975. func isPodReady(pod *v1.Pod) bool {
  976. ready := false
  977. conditions := pod.Status.Conditions
  978. for i := range conditions {
  979. if conditions[i].Type == v1.PodReady {
  980. ready = pod.Status.Conditions[i].Status == v1.ConditionTrue
  981. }
  982. }
  983. return ready
  984. }
  985. func isPodExited(pod *v1.Pod) bool {
  986. return pod.Status.Phase == v1.PodSucceeded || pod.Status.Phase == v1.PodFailed
  987. }