porter.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. err = agent.WaitForContainerHealthy(pgID, 10)
  98. if err != nil {
  99. return nil, "", err
  100. }
  101. opts.Env = append(opts.Env, []string{
  102. "SQL_LITE=false",
  103. "DB_USER=porter",
  104. "DB_PASS=porter",
  105. "DB_NAME=porter",
  106. "DB_HOST=porter_postgres_" + opts.ProcessID,
  107. "DB_PORT=5432",
  108. }...)
  109. }
  110. // create Porter container
  111. startOpts := PorterServerStartOpts{
  112. Name: "porter_server_" + opts.ProcessID,
  113. Image: "porter1/porter:" + opts.ServerImageTag,
  114. HostPort: uint(opts.ServerPort),
  115. ContainerPort: 8080,
  116. Mounts: mounts,
  117. VolumeMap: volumesMap,
  118. NetworkID: netID,
  119. Env: opts.Env,
  120. }
  121. id, err = agent.StartPorterContainer(startOpts)
  122. if err != nil {
  123. return nil, "", err
  124. }
  125. err = agent.WaitForContainerHealthy(id, 10)
  126. if err != nil {
  127. return nil, "", err
  128. }
  129. return agent, id, nil
  130. }
  131. // PorterServerStartOpts are the options for starting the Porter server
  132. type PorterServerStartOpts struct {
  133. Name string
  134. Image string
  135. StartCmd []string
  136. HostPort uint
  137. ContainerPort uint
  138. Mounts []mount.Mount
  139. VolumeMap map[string]struct{}
  140. Env []string
  141. NetworkID string
  142. }
  143. // StartPorterContainer pulls a specific Porter image and starts a container
  144. // using the Docker engine. It returns the container ID
  145. func (a *Agent) StartPorterContainer(opts PorterServerStartOpts) (string, error) {
  146. id, err := a.upsertPorterContainer(opts)
  147. if err != nil {
  148. return "", err
  149. }
  150. err = a.startPorterContainer(id)
  151. if err != nil {
  152. return "", err
  153. }
  154. // attach container to network
  155. err = a.ConnectContainerToNetwork(opts.NetworkID, id, opts.Name)
  156. if err != nil {
  157. return "", err
  158. }
  159. return id, nil
  160. }
  161. // detect if container exists and is running, and stop
  162. // if spec has changed, remove and recreate container
  163. // if container does not exist, create the container
  164. // otherwise, return stopped container
  165. func (a *Agent) upsertPorterContainer(opts PorterServerStartOpts) (id string, err error) {
  166. containers, err := a.getContainersCreatedByStart()
  167. // remove the matching container
  168. for _, container := range containers {
  169. if len(container.Names) > 0 && container.Names[0] == "/"+opts.Name {
  170. timeout, _ := time.ParseDuration("15s")
  171. err := a.client.ContainerStop(a.ctx, container.ID, &timeout)
  172. if err != nil {
  173. return "", a.handleDockerClientErr(err, "Could not stop container "+container.ID)
  174. }
  175. err = a.client.ContainerRemove(a.ctx, container.ID, types.ContainerRemoveOptions{})
  176. if err != nil {
  177. return "", a.handleDockerClientErr(err, "Could not remove container "+container.ID)
  178. }
  179. }
  180. }
  181. return a.pullAndCreatePorterContainer(opts)
  182. }
  183. // create the container and return its id
  184. func (a *Agent) pullAndCreatePorterContainer(opts PorterServerStartOpts) (id string, err error) {
  185. a.PullImage(opts.Image)
  186. // format the port array for binding to host machine
  187. ports := []string{fmt.Sprintf("127.0.0.1:%d:%d/tcp", opts.HostPort, opts.ContainerPort)}
  188. _, portBindings, err := nat.ParsePortSpecs(ports)
  189. if err != nil {
  190. return "", fmt.Errorf("Unable to parse port specification %s", ports)
  191. }
  192. labels := make(map[string]string)
  193. labels[a.label] = "true"
  194. // create the container with a label specifying this was created via the CLI
  195. resp, err := a.client.ContainerCreate(a.ctx, &container.Config{
  196. Image: opts.Image,
  197. Cmd: opts.StartCmd,
  198. Tty: false,
  199. Labels: labels,
  200. Volumes: opts.VolumeMap,
  201. Env: opts.Env,
  202. Healthcheck: &container.HealthConfig{
  203. Test: []string{"CMD-SHELL", "/porter/ready"},
  204. Interval: 10 * time.Second,
  205. Timeout: 5 * time.Second,
  206. Retries: 3,
  207. },
  208. }, &container.HostConfig{
  209. PortBindings: portBindings,
  210. Mounts: opts.Mounts,
  211. }, nil, opts.Name)
  212. if err != nil {
  213. return "", a.handleDockerClientErr(err, "Could not create Porter container")
  214. }
  215. return resp.ID, nil
  216. }
  217. // start the container
  218. func (a *Agent) startPorterContainer(id string) error {
  219. if err := a.client.ContainerStart(a.ctx, id, types.ContainerStartOptions{}); err != nil {
  220. return a.handleDockerClientErr(err, "Could not start Porter container")
  221. }
  222. return nil
  223. }
  224. // PostgresOpts are the options for starting the Postgres DB
  225. type PostgresOpts struct {
  226. Name string
  227. Image string
  228. Env []string
  229. VolumeMap map[string]struct{}
  230. Mounts []mount.Mount
  231. NetworkID string
  232. }
  233. // StartPostgresContainer pulls a specific Porter image and starts a container
  234. // using the Docker engine
  235. func (a *Agent) StartPostgresContainer(opts PostgresOpts) (string, error) {
  236. id, err := a.upsertPostgresContainer(opts)
  237. if err != nil {
  238. return "", err
  239. }
  240. err = a.startPostgresContainer(id)
  241. if err != nil {
  242. return "", err
  243. }
  244. // attach container to network
  245. err = a.ConnectContainerToNetwork(opts.NetworkID, id, opts.Name)
  246. if err != nil {
  247. return "", err
  248. }
  249. return id, nil
  250. }
  251. // detect if container exists and is running, and stop
  252. // if it is running, stop it
  253. // if it is stopped, return id
  254. // if it does not exist, create it and return it
  255. func (a *Agent) upsertPostgresContainer(opts PostgresOpts) (id string, err error) {
  256. containers, err := a.getContainersCreatedByStart()
  257. // stop the matching container and return it
  258. for _, container := range containers {
  259. if len(container.Names) > 0 && container.Names[0] == "/"+opts.Name {
  260. timeout, _ := time.ParseDuration("15s")
  261. err := a.client.ContainerStop(a.ctx, container.ID, &timeout)
  262. if err != nil {
  263. return "", a.handleDockerClientErr(err, "Could not stop postgres container "+container.ID)
  264. }
  265. return container.ID, nil
  266. }
  267. }
  268. return a.pullAndCreatePostgresContainer(opts)
  269. }
  270. // create the container and return it
  271. func (a *Agent) pullAndCreatePostgresContainer(opts PostgresOpts) (id string, err error) {
  272. a.PullImage(opts.Image)
  273. labels := make(map[string]string)
  274. labels[a.label] = "true"
  275. // create the container with a label specifying this was created via the CLI
  276. resp, err := a.client.ContainerCreate(a.ctx, &container.Config{
  277. Image: opts.Image,
  278. Tty: false,
  279. Labels: labels,
  280. Volumes: opts.VolumeMap,
  281. Env: opts.Env,
  282. ExposedPorts: nat.PortSet{
  283. "5432": struct{}{},
  284. },
  285. Healthcheck: &container.HealthConfig{
  286. Test: []string{"CMD-SHELL", "pg_isready"},
  287. Interval: 10 * time.Second,
  288. Timeout: 5 * time.Second,
  289. Retries: 3,
  290. },
  291. }, &container.HostConfig{
  292. Mounts: opts.Mounts,
  293. }, nil, opts.Name)
  294. if err != nil {
  295. return "", a.handleDockerClientErr(err, "Could not create Porter container")
  296. }
  297. return resp.ID, nil
  298. }
  299. // start the container in the background
  300. func (a *Agent) startPostgresContainer(id string) error {
  301. if err := a.client.ContainerStart(a.ctx, id, types.ContainerStartOptions{}); err != nil {
  302. return a.handleDockerClientErr(err, "Could not start Postgres container")
  303. }
  304. return nil
  305. }
  306. // StopPorterContainers finds all containers that were started via the CLI and stops them
  307. // -- removes the container if remove is set to true
  308. func (a *Agent) StopPorterContainers(remove bool) error {
  309. containers, err := a.getContainersCreatedByStart()
  310. if err != nil {
  311. return err
  312. }
  313. // remove all Porter containers
  314. for _, container := range containers {
  315. timeout, _ := time.ParseDuration("15s")
  316. err := a.client.ContainerStop(a.ctx, container.ID, &timeout)
  317. if err != nil {
  318. return a.handleDockerClientErr(err, "Could not stop container "+container.ID)
  319. }
  320. if remove {
  321. err = a.client.ContainerRemove(a.ctx, container.ID, types.ContainerRemoveOptions{})
  322. if err != nil {
  323. return a.handleDockerClientErr(err, "Could not remove container "+container.ID)
  324. }
  325. }
  326. }
  327. return nil
  328. }
  329. // StopPorterContainersWithProcessID finds all containers that were started via the CLI
  330. // and have a given process id and stops them -- removes the container if remove is set
  331. // to true
  332. func (a *Agent) StopPorterContainersWithProcessID(processID string, remove bool) error {
  333. containers, err := a.getContainersCreatedByStart()
  334. if err != nil {
  335. return err
  336. }
  337. // remove all Porter containers
  338. for _, container := range containers {
  339. if strings.Contains(container.Names[0], "_"+processID) {
  340. timeout, _ := time.ParseDuration("15s")
  341. err := a.client.ContainerStop(a.ctx, container.ID, &timeout)
  342. if err != nil {
  343. return a.handleDockerClientErr(err, "Could not stop container "+container.ID)
  344. }
  345. if remove {
  346. err = a.client.ContainerRemove(a.ctx, container.ID, types.ContainerRemoveOptions{})
  347. if err != nil {
  348. return a.handleDockerClientErr(err, "Could not remove container "+container.ID)
  349. }
  350. }
  351. }
  352. }
  353. return nil
  354. }
  355. // getContainersCreatedByStart gets all containers that were created by the "porter start"
  356. // command by looking for the label "CreatedByPorterCLI" (or .label of the agent)
  357. func (a *Agent) getContainersCreatedByStart() ([]types.Container, error) {
  358. containers, err := a.client.ContainerList(a.ctx, types.ContainerListOptions{
  359. All: true,
  360. })
  361. if err != nil {
  362. return nil, a.handleDockerClientErr(err, "Could not list containers")
  363. }
  364. res := make([]types.Container, 0)
  365. for _, container := range containers {
  366. if contains, ok := container.Labels[a.label]; ok && contains == "true" {
  367. res = append(res, container)
  368. }
  369. }
  370. return res, nil
  371. }