porter.go 12 KB

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