porter.go 12 KB

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