porter.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. package docker
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "strings"
  6. "time"
  7. "github.com/docker/docker/api/types"
  8. "github.com/docker/docker/api/types/container"
  9. "github.com/docker/docker/api/types/mount"
  10. "github.com/docker/go-connections/nat"
  11. "k8s.io/client-go/util/homedir"
  12. )
  13. // PorterDB is used for enumerating DB types
  14. type PorterDB int
  15. // The supported DB types
  16. const (
  17. Postgres PorterDB = iota
  18. SQLite
  19. )
  20. // PorterStartOpts are the options for starting the Porter stack
  21. type PorterStartOpts struct {
  22. ProcessID string
  23. ServerImageTag string
  24. ServerPort int
  25. DB PorterDB
  26. KubeconfigPath string
  27. SkipKubeconfig bool
  28. Env []string
  29. }
  30. // StartPorter creates a new Docker agent using the host environment, and creates a
  31. // new Porter instance
  32. func StartPorter(opts *PorterStartOpts) (agent *Agent, id string, err error) {
  33. home := homedir.HomeDir()
  34. outputConfPath := filepath.Join(home, ".porter", "porter.kubeconfig")
  35. containerConfPath := "/porter/porter.kubeconfig"
  36. agent, err = NewAgentFromEnv()
  37. if err != nil {
  38. return nil, "", err
  39. }
  40. // the volume mounts to use
  41. mounts := make([]mount.Mount, 0)
  42. // the volumes passed to the Porter container
  43. volumesMap := make(map[string]struct{})
  44. if !opts.SkipKubeconfig {
  45. // add a bind mount with the kubeconfig
  46. mount := mount.Mount{
  47. Type: mount.TypeBind,
  48. Source: outputConfPath,
  49. Target: containerConfPath,
  50. ReadOnly: true,
  51. Consistency: mount.ConsistencyFull,
  52. }
  53. mounts = append(mounts, mount)
  54. }
  55. netID, err := agent.CreateBridgeNetworkIfNotExist("porter_network_" + opts.ProcessID)
  56. if err != nil {
  57. return nil, "", err
  58. }
  59. switch opts.DB {
  60. case SQLite:
  61. // check if sqlite volume exists, create it if not
  62. vol, err := agent.CreateLocalVolumeIfNotExist("porter_sqlite_" + opts.ProcessID)
  63. if err != nil {
  64. return nil, "", err
  65. }
  66. // create mount
  67. mount := mount.Mount{
  68. Type: mount.TypeVolume,
  69. Source: vol.Name,
  70. Target: "/sqlite",
  71. ReadOnly: false,
  72. Consistency: mount.ConsistencyFull,
  73. }
  74. mounts = append(mounts, mount)
  75. volumesMap[vol.Name] = struct{}{}
  76. opts.Env = append(opts.Env, []string{
  77. "SQL_LITE=true",
  78. "SQL_LITE_PATH=/sqlite/porter.db",
  79. }...)
  80. case Postgres:
  81. // check if postgres volume exists, create it if not
  82. vol, err := agent.CreateLocalVolumeIfNotExist("porter_postgres_" + opts.ProcessID)
  83. if err != nil {
  84. return nil, "", err
  85. }
  86. // pgMount is mount for postgres container
  87. pgMount := []mount.Mount{
  88. mount.Mount{
  89. Type: mount.TypeVolume,
  90. Source: vol.Name,
  91. Target: "/var/lib/postgresql/data",
  92. ReadOnly: false,
  93. Consistency: mount.ConsistencyFull,
  94. },
  95. }
  96. // create postgres container with mount
  97. startOpts := PostgresOpts{
  98. Name: "porter_postgres_" + opts.ProcessID,
  99. Image: "postgres:latest",
  100. Mounts: pgMount,
  101. VolumeMap: map[string]struct{}{
  102. "porter_postgres": struct{}{},
  103. },
  104. NetworkID: netID,
  105. Env: []string{
  106. "POSTGRES_USER=porter",
  107. "POSTGRES_PASSWORD=porter",
  108. "POSTGRES_DB=porter",
  109. },
  110. }
  111. pgID, err := agent.StartPostgresContainer(startOpts)
  112. fmt.Println("Waiting for postgres:latest to be healthy...")
  113. agent.WaitForContainerHealthy(pgID, 10)
  114. if err != nil {
  115. return nil, "", err
  116. }
  117. opts.Env = append(opts.Env, []string{
  118. "SQL_LITE=false",
  119. "DB_USER=porter",
  120. "DB_PASS=porter",
  121. "DB_NAME=porter",
  122. "DB_HOST=porter_postgres_" + opts.ProcessID,
  123. "DB_PORT=5432",
  124. }...)
  125. defer agent.WaitForContainerStop(pgID)
  126. }
  127. // create Porter container
  128. startOpts := PorterServerStartOpts{
  129. Name: "porter_server_" + opts.ProcessID,
  130. Image: "porter1/porter:" + opts.ServerImageTag,
  131. HostPort: uint(opts.ServerPort),
  132. ContainerPort: 8080,
  133. Mounts: mounts,
  134. VolumeMap: volumesMap,
  135. NetworkID: netID,
  136. Env: opts.Env,
  137. }
  138. id, err = agent.StartPorterContainer(startOpts)
  139. if err != nil {
  140. return nil, "", err
  141. }
  142. return agent, id, nil
  143. }
  144. // PorterServerStartOpts are the options for starting the Porter server
  145. type PorterServerStartOpts struct {
  146. Name string
  147. Image string
  148. StartCmd []string
  149. HostPort uint
  150. ContainerPort uint
  151. Mounts []mount.Mount
  152. VolumeMap map[string]struct{}
  153. Env []string
  154. NetworkID string
  155. }
  156. // StartPorterContainer pulls a specific Porter image and starts a container
  157. // using the Docker engine. It returns the container ID
  158. func (a *Agent) StartPorterContainer(opts PorterServerStartOpts) (string, error) {
  159. id, err := a.upsertPorterContainer(opts)
  160. if err != nil {
  161. return "", err
  162. }
  163. err = a.startPorterContainer(id)
  164. if err != nil {
  165. return "", err
  166. }
  167. // attach container to network
  168. err = a.ConnectContainerToNetwork(opts.NetworkID, id, opts.Name)
  169. if err != nil {
  170. return "", err
  171. }
  172. return id, nil
  173. }
  174. // detect if container exists and is running, and stop
  175. // if spec has changed, remove and recreate container
  176. // if container does not exist, create the container
  177. // otherwise, return stopped container
  178. func (a *Agent) upsertPorterContainer(opts PorterServerStartOpts) (id string, err error) {
  179. containers, err := a.getContainersCreatedByStart()
  180. // remove the matching container
  181. for _, container := range containers {
  182. if len(container.Names) > 0 && container.Names[0] == "/"+opts.Name {
  183. timeout, _ := time.ParseDuration("15s")
  184. err := a.client.ContainerStop(a.ctx, container.ID, &timeout)
  185. if err != nil {
  186. return "", a.handleDockerClientErr(err, "Could not stop container "+container.ID)
  187. }
  188. err = a.client.ContainerRemove(a.ctx, container.ID, types.ContainerRemoveOptions{})
  189. if err != nil {
  190. return "", a.handleDockerClientErr(err, "Could not remove container "+container.ID)
  191. }
  192. }
  193. }
  194. return a.pullAndCreatePorterContainer(opts)
  195. }
  196. // create the container and return its id
  197. func (a *Agent) pullAndCreatePorterContainer(opts PorterServerStartOpts) (id string, err error) {
  198. a.PullImage(opts.Image)
  199. // format the port array for binding to host machine
  200. ports := []string{fmt.Sprintf("127.0.0.1:%d:%d/tcp", opts.HostPort, opts.ContainerPort)}
  201. _, portBindings, err := nat.ParsePortSpecs(ports)
  202. if err != nil {
  203. return "", fmt.Errorf("Unable to parse port specification %s", ports)
  204. }
  205. labels := make(map[string]string)
  206. labels[a.label] = "true"
  207. // create the container with a label specifying this was created via the CLI
  208. resp, err := a.client.ContainerCreate(a.ctx, &container.Config{
  209. Image: opts.Image,
  210. Cmd: opts.StartCmd,
  211. Tty: false,
  212. Labels: labels,
  213. Volumes: opts.VolumeMap,
  214. Env: opts.Env,
  215. }, &container.HostConfig{
  216. PortBindings: portBindings,
  217. Mounts: opts.Mounts,
  218. }, nil, opts.Name)
  219. if err != nil {
  220. return "", a.handleDockerClientErr(err, "Could not create Porter container")
  221. }
  222. return resp.ID, nil
  223. }
  224. // start the container
  225. func (a *Agent) startPorterContainer(id string) error {
  226. if err := a.client.ContainerStart(a.ctx, id, types.ContainerStartOptions{}); err != nil {
  227. return a.handleDockerClientErr(err, "Could not start Porter container")
  228. }
  229. return nil
  230. }
  231. // PostgresOpts are the options for starting the Postgres DB
  232. type PostgresOpts struct {
  233. Name string
  234. Image string
  235. Env []string
  236. VolumeMap map[string]struct{}
  237. Mounts []mount.Mount
  238. NetworkID string
  239. }
  240. // StartPostgresContainer pulls a specific Porter image and starts a container
  241. // using the Docker engine
  242. func (a *Agent) StartPostgresContainer(opts PostgresOpts) (string, error) {
  243. id, err := a.upsertPostgresContainer(opts)
  244. if err != nil {
  245. return "", err
  246. }
  247. err = a.startPostgresContainer(id)
  248. if err != nil {
  249. return "", err
  250. }
  251. // attach container to network
  252. err = a.ConnectContainerToNetwork(opts.NetworkID, id, opts.Name)
  253. if err != nil {
  254. return "", err
  255. }
  256. return id, nil
  257. }
  258. // detect if container exists and is running, and stop
  259. // if it is running, stop it
  260. // if it is stopped, return id
  261. // if it does not exist, create it and return it
  262. func (a *Agent) upsertPostgresContainer(opts PostgresOpts) (id string, err error) {
  263. containers, err := a.getContainersCreatedByStart()
  264. // stop the matching container and return it
  265. for _, container := range containers {
  266. if len(container.Names) > 0 && container.Names[0] == "/"+opts.Name {
  267. timeout, _ := time.ParseDuration("15s")
  268. err := a.client.ContainerStop(a.ctx, container.ID, &timeout)
  269. if err != nil {
  270. return "", a.handleDockerClientErr(err, "Could not stop postgres container "+container.ID)
  271. }
  272. return container.ID, nil
  273. }
  274. }
  275. return a.pullAndCreatePostgresContainer(opts)
  276. }
  277. // create the container and return it
  278. func (a *Agent) pullAndCreatePostgresContainer(opts PostgresOpts) (id string, err error) {
  279. a.PullImage(opts.Image)
  280. labels := make(map[string]string)
  281. labels[a.label] = "true"
  282. // create the container with a label specifying this was created via the CLI
  283. resp, err := a.client.ContainerCreate(a.ctx, &container.Config{
  284. Image: opts.Image,
  285. Tty: false,
  286. Labels: labels,
  287. Volumes: opts.VolumeMap,
  288. Env: opts.Env,
  289. ExposedPorts: nat.PortSet{
  290. "5432": struct{}{},
  291. },
  292. Healthcheck: &container.HealthConfig{
  293. Test: []string{"CMD-SHELL", "pg_isready"},
  294. Interval: 10 * time.Second,
  295. Timeout: 5 * time.Second,
  296. Retries: 3,
  297. },
  298. }, &container.HostConfig{
  299. Mounts: opts.Mounts,
  300. }, nil, opts.Name)
  301. if err != nil {
  302. return "", a.handleDockerClientErr(err, "Could not create Porter container")
  303. }
  304. return resp.ID, nil
  305. }
  306. // start the container in the background
  307. func (a *Agent) startPostgresContainer(id string) error {
  308. if err := a.client.ContainerStart(a.ctx, id, types.ContainerStartOptions{}); err != nil {
  309. return a.handleDockerClientErr(err, "Could not start Postgres container")
  310. }
  311. return nil
  312. }
  313. // StopPorterContainers finds all containers that were started via the CLI and stops them
  314. // -- removes the container if remove is set to true
  315. func (a *Agent) StopPorterContainers(remove bool) error {
  316. fmt.Println("Stopping containers...")
  317. containers, err := a.getContainersCreatedByStart()
  318. if err != nil {
  319. return err
  320. }
  321. // remove all Porter containers
  322. for _, container := range containers {
  323. timeout, _ := time.ParseDuration("15s")
  324. err := a.client.ContainerStop(a.ctx, container.ID, &timeout)
  325. if err != nil {
  326. return a.handleDockerClientErr(err, "Could not stop container "+container.ID)
  327. }
  328. if remove {
  329. err = a.client.ContainerRemove(a.ctx, container.ID, types.ContainerRemoveOptions{})
  330. if err != nil {
  331. return a.handleDockerClientErr(err, "Could not remove container "+container.ID)
  332. }
  333. }
  334. }
  335. return nil
  336. }
  337. // StopPorterContainersWithProcessID finds all containers that were started via the CLI
  338. // and have a given process id and stops them -- removes the container if remove is set
  339. // to true
  340. func (a *Agent) StopPorterContainersWithProcessID(processID string, remove bool) error {
  341. fmt.Println("Stopping containers...")
  342. containers, err := a.getContainersCreatedByStart()
  343. if err != nil {
  344. return err
  345. }
  346. // remove all Porter containers
  347. for _, container := range containers {
  348. if strings.Contains(container.Names[0], "_"+processID) {
  349. timeout, _ := time.ParseDuration("15s")
  350. err := a.client.ContainerStop(a.ctx, container.ID, &timeout)
  351. if err != nil {
  352. return a.handleDockerClientErr(err, "Could not stop container "+container.ID)
  353. }
  354. if remove {
  355. err = a.client.ContainerRemove(a.ctx, container.ID, types.ContainerRemoveOptions{})
  356. if err != nil {
  357. return a.handleDockerClientErr(err, "Could not remove container "+container.ID)
  358. }
  359. }
  360. }
  361. }
  362. return nil
  363. }
  364. // getContainersCreatedByStart gets all containers that were created by the "porter start"
  365. // command by looking for the label "CreatedByPorterCLI" (or .label of the agent)
  366. func (a *Agent) getContainersCreatedByStart() ([]types.Container, error) {
  367. containers, err := a.client.ContainerList(a.ctx, types.ContainerListOptions{
  368. All: true,
  369. })
  370. if err != nil {
  371. return nil, a.handleDockerClientErr(err, "Could not list containers")
  372. }
  373. res := make([]types.Container, 0)
  374. for _, container := range containers {
  375. if contains, ok := container.Labels[a.label]; ok && contains == "true" {
  376. res = append(res, container)
  377. }
  378. }
  379. return res, nil
  380. }