porter.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. specs "github.com/opencontainers/image-spec/specs-go/v1"
  11. )
  12. // PorterDB is used for enumerating DB types
  13. type PorterDB int
  14. // The supported DB types
  15. const (
  16. Postgres PorterDB = iota
  17. SQLite
  18. )
  19. // PorterStartOpts are the options for starting the Porter stack
  20. type PorterStartOpts struct {
  21. ProcessID string
  22. ServerImageTag string
  23. ServerPort int
  24. DB PorterDB
  25. Env []string
  26. }
  27. // StartPorter creates a new Docker agent using the host environment, and creates a
  28. // new Porter instance
  29. func StartPorter(opts *PorterStartOpts) (agent *Agent, id string, err error) {
  30. agent, err = NewAgentFromEnv()
  31. if err != nil {
  32. return nil, "", err
  33. }
  34. // the volume mounts to use
  35. mounts := make([]mount.Mount, 0)
  36. // the volumes passed to the Porter container
  37. volumesMap := make(map[string]struct{})
  38. netID, err := agent.CreateBridgeNetworkIfNotExist("porter_network_" + opts.ProcessID)
  39. if err != nil {
  40. return nil, "", err
  41. }
  42. switch opts.DB {
  43. case SQLite:
  44. // check if sqlite volume exists, create it if not
  45. vol, err := agent.CreateLocalVolumeIfNotExist("porter_sqlite_" + opts.ProcessID)
  46. if err != nil {
  47. return nil, "", err
  48. }
  49. // create mount
  50. mount := mount.Mount{
  51. Type: mount.TypeVolume,
  52. Source: vol.Name,
  53. Target: "/sqlite",
  54. ReadOnly: false,
  55. Consistency: mount.ConsistencyFull,
  56. }
  57. mounts = append(mounts, mount)
  58. volumesMap[vol.Name] = struct{}{}
  59. opts.Env = append(opts.Env, []string{
  60. "SQL_LITE=true",
  61. "SQL_LITE_PATH=/sqlite/porter.db",
  62. }...)
  63. case Postgres:
  64. // check if postgres volume exists, create it if not
  65. vol, err := agent.CreateLocalVolumeIfNotExist("porter_postgres_" + opts.ProcessID)
  66. if err != nil {
  67. return nil, "", err
  68. }
  69. // pgMount is mount for postgres container
  70. pgMount := []mount.Mount{
  71. {
  72. Type: mount.TypeVolume,
  73. Source: vol.Name,
  74. Target: "/var/lib/postgresql/data",
  75. ReadOnly: false,
  76. Consistency: mount.ConsistencyFull,
  77. },
  78. }
  79. // create postgres container with mount
  80. startOpts := PostgresOpts{
  81. Name: "porter_postgres_" + opts.ProcessID,
  82. Image: "postgres:latest",
  83. Mounts: pgMount,
  84. VolumeMap: map[string]struct{}{
  85. "porter_postgres": {},
  86. },
  87. NetworkID: netID,
  88. Env: []string{
  89. "POSTGRES_USER=porter",
  90. "POSTGRES_PASSWORD=porter",
  91. "POSTGRES_DB=porter",
  92. },
  93. }
  94. pgID, err := agent.StartPostgresContainer(startOpts)
  95. if err != nil {
  96. return nil, "", err
  97. }
  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. opts.Env = append(opts.Env, "REDIS_ENABLED=false")
  112. // create Porter container
  113. startOpts := PorterServerStartOpts{
  114. Name: "porter_server_" + opts.ProcessID,
  115. Image: "porter1/porter:" + opts.ServerImageTag,
  116. HostPort: uint(opts.ServerPort),
  117. ContainerPort: 8080,
  118. Mounts: mounts,
  119. VolumeMap: volumesMap,
  120. NetworkID: netID,
  121. Env: opts.Env,
  122. }
  123. id, err = agent.StartPorterContainer(startOpts)
  124. if err != nil {
  125. return nil, "", err
  126. }
  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.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.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.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, &specs.Platform{}, 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.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.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.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, &specs.Platform{}, 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.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. containers, err := a.getContainersCreatedByStart()
  312. if err != nil {
  313. return err
  314. }
  315. // remove all Porter containers
  316. for _, container := range containers {
  317. timeout, _ := time.ParseDuration("15s")
  318. err := a.ContainerStop(a.ctx, container.ID, &timeout)
  319. if err != nil {
  320. return a.handleDockerClientErr(err, "Could not stop container "+container.ID)
  321. }
  322. if remove {
  323. err = a.ContainerRemove(a.ctx, container.ID, types.ContainerRemoveOptions{})
  324. if err != nil {
  325. return a.handleDockerClientErr(err, "Could not remove container "+container.ID)
  326. }
  327. }
  328. }
  329. return nil
  330. }
  331. // StopPorterContainersWithProcessID finds all containers that were started via the CLI
  332. // and have a given process id and stops them -- removes the container if remove is set
  333. // to true
  334. func (a *Agent) StopPorterContainersWithProcessID(processID string, remove bool) error {
  335. containers, err := a.getContainersCreatedByStart()
  336. if err != nil {
  337. return err
  338. }
  339. // remove all Porter containers
  340. for _, container := range containers {
  341. if strings.Contains(container.Names[0], "_"+processID) {
  342. timeout, _ := time.ParseDuration("15s")
  343. err := a.ContainerStop(a.ctx, container.ID, &timeout)
  344. if err != nil {
  345. return a.handleDockerClientErr(err, "Could not stop container "+container.ID)
  346. }
  347. if remove {
  348. err = a.ContainerRemove(a.ctx, container.ID, types.ContainerRemoveOptions{})
  349. if err != nil {
  350. return a.handleDockerClientErr(err, "Could not remove container "+container.ID)
  351. }
  352. }
  353. }
  354. }
  355. return nil
  356. }
  357. // getContainersCreatedByStart gets all containers that were created by the "porter start"
  358. // command by looking for the label "CreatedByPorterCLI" (or .label of the agent)
  359. func (a *Agent) getContainersCreatedByStart() ([]types.Container, error) {
  360. containers, err := a.ContainerList(a.ctx, types.ContainerListOptions{
  361. All: true,
  362. })
  363. if err != nil {
  364. return nil, a.handleDockerClientErr(err, "Could not list containers")
  365. }
  366. res := make([]types.Container, 0)
  367. for _, container := range containers {
  368. if contains, ok := container.Labels[a.label]; ok && contains == "true" {
  369. res = append(res, container)
  370. }
  371. }
  372. return res, nil
  373. }