Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft: Adds services capabilities #638

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions pkg/container/docker_network.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package container

import (
"context"

"github.com/docker/docker/api/types"
"github.com/nektos/act/pkg/common"
)

func NewDockerNetworkCreateExecutor(name string) common.Executor {
return func(ctx context.Context) error {
cli, err := GetDockerClient(ctx)
if err != nil {
return err
}

_, err = cli.NetworkCreate(ctx, name, types.NetworkCreate{})
if err != nil {
return err
}

return nil
}
}

func NewDockerNetworkRemoveExecutor(name string) common.Executor {
return func(ctx context.Context) error {
cli, err := GetDockerClient(ctx)
if err != nil {
return err
}

cli.NetworkRemove(ctx, name)
return nil
}
}
26 changes: 24 additions & 2 deletions pkg/container/docker_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ type FileEntry struct {
// Container for managing docker run containers
type Container interface {
Create() common.Executor
ConnectToNetwork(name string) common.Executor
Copy(destPath string, files ...*FileEntry) common.Executor
CopyDir(destPath string, srcPath string, useGitIgnore bool) common.Executor
Pull(forcePull bool) common.Executor
Expand Down Expand Up @@ -97,6 +98,17 @@ func supportsContainerImagePlatform(cli *client.Client) bool {
return constraint.Check(sv)
}

func (cr *containerReference) ConnectToNetwork(name string) common.Executor {
return common.
NewDebugExecutor("%sdocker network connect %s %s", logPrefix, name, cr.input.Name).
Then(
common.NewPipelineExecutor(
cr.connect(),
cr.connectToNetwork(name),
).IfNot(common.Dryrun),
)
}

func (cr *containerReference) Create() common.Executor {
return common.
NewDebugExecutor("%sdocker create image=%s platform=%s entrypoint=%+q cmd=%+q", logPrefix, cr.input.Image, cr.input.Platform, cr.input.Entrypoint, cr.input.Cmd).
Expand Down Expand Up @@ -203,6 +215,12 @@ func GetDockerClient(ctx context.Context) (*client.Client, error) {
return cli, err
}

func (cr *containerReference) connectToNetwork(name string) common.Executor {
return func(ctx context.Context) error {
return cr.cli.NetworkConnect(ctx, name, cr.input.Name, nil)
}
}

func (cr *containerReference) connect() common.Executor {
return func(ctx context.Context) error {
if cr.cli != nil {
Expand Down Expand Up @@ -275,12 +293,16 @@ func (cr *containerReference) create() common.Executor {
input := cr.input
config := &container.Config{
Image: input.Image,
Cmd: input.Cmd,
Entrypoint: input.Entrypoint,
WorkingDir: input.WorkingDir,
Env: input.Env,
Tty: isTerminal,
}
if len(input.Cmd) > 0 {
config.Cmd = input.Cmd
}
if len(input.Entrypoint) > 0 {
config.Entrypoint = input.Entrypoint
}

mounts := make([]mount.Mount, 0)
for mountSource, mountTarget := range input.Mounts {
Expand Down
112 changes: 93 additions & 19 deletions pkg/runner/run_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,19 @@ import (

// RunContext contains info about current job
type RunContext struct {
Name string
Config *Config
Matrix map[string]interface{}
Run *model.Run
EventJSON string
Env map[string]string
ExtraPath []string
CurrentStep string
StepResults map[string]*stepResult
ExprEval ExpressionEvaluator
JobContainer container.Container
OutputMappings map[MappableOutput]MappableOutput
Name string
Config *Config
Matrix map[string]interface{}
Run *model.Run
EventJSON string
Env map[string]string
ExtraPath []string
CurrentStep string
StepResults map[string]*stepResult
ExprEval ExpressionEvaluator
JobContainer container.Container
ServiceContainers []container.Container
OutputMappings map[MappableOutput]MappableOutput
}

type MappableOutput struct {
Expand Down Expand Up @@ -96,6 +97,36 @@ func (rc *RunContext) startJobContainer() common.Executor {
binds = append(binds, fmt.Sprintf("%s:%s%s", rc.Config.Workdir, rc.Config.Workdir, bindModifiers))
}

if rc.Config.ContainerArchitecture == "" {
rc.Config.ContainerArchitecture = fmt.Sprintf("%s/%s", "linux", runtime.GOARCH)
}
Markcial marked this conversation as resolved.
Show resolved Hide resolved
// add service containers
for name, spec := range rc.Run.Job().Services {
mergedEnv := envList
for k, v := range spec.Env {
mergedEnv = append(mergedEnv, fmt.Sprintf("%s=%s", k, v))
}
c := container.NewContainer(&container.NewContainerInput{
Name: name,
WorkingDir: rc.Config.Workdir,
Image: spec.Image,
Env: mergedEnv,
Mounts: map[string]string{
// TODO merge volumes
name: filepath.Dir(rc.Config.Workdir),
"act-toolcache": "/toolcache",
"act-actions": "/actions",
},
Binds: binds,
Stdout: logWriter,
Stderr: logWriter,
Privileged: rc.Config.Privileged,
UsernsMode: rc.Config.UsernsMode,
Platform: rc.Config.ContainerArchitecture,
})
rc.ServiceContainers = append(rc.ServiceContainers, c)
}

rc.JobContainer = container.NewContainer(&container.NewContainerInput{
Cmd: nil,
Entrypoint: []string{"/usr/bin/tail", "-f", "/dev/null"},
Expand All @@ -108,13 +139,12 @@ func (rc *RunContext) startJobContainer() common.Executor {
"act-toolcache": "/toolcache",
"act-actions": "/actions",
},
NetworkMode: "host",
Binds: binds,
Stdout: logWriter,
Stderr: logWriter,
Privileged: rc.Config.Privileged,
UsernsMode: rc.Config.UsernsMode,
Platform: rc.Config.ContainerArchitecture,
Binds: binds,
Stdout: logWriter,
Stderr: logWriter,
Privileged: rc.Config.Privileged,
UsernsMode: rc.Config.UsernsMode,
Platform: rc.Config.ContainerArchitecture,
})

var copyWorkspace bool
Expand All @@ -124,11 +154,17 @@ func (rc *RunContext) startJobContainer() common.Executor {
copyToPath = filepath.Join(rc.Config.Workdir, copyToPath)
}

networkName := fmt.Sprintf("act-%s-network", rc.Run.JobID)
return common.NewPipelineExecutor(
rc.JobContainer.Pull(rc.Config.ForcePull),
rc.stopServiceContainers(),
rc.stopJobContainer(),
rc.removeNetwork(networkName),
rc.createNetwork(networkName),
rc.startServiceContainers(networkName),
rc.JobContainer.Create(),
rc.JobContainer.Start(false),
rc.JobContainer.ConnectToNetwork(networkName),
rc.JobContainer.CopyDir(copyToPath, rc.Config.Workdir+string(filepath.Separator)+".", rc.Config.UseGitIgnore).IfBool(copyWorkspace),
rc.JobContainer.Copy(filepath.Dir(rc.Config.Workdir), &container.FileEntry{
Name: "workflow/event.json",
Expand All @@ -146,6 +182,19 @@ func (rc *RunContext) startJobContainer() common.Executor {
)(ctx)
}
}

func (rc *RunContext) createNetwork(name string) common.Executor {
return func(ctx context.Context) error {
return container.NewDockerNetworkCreateExecutor(name)(ctx)
}
}

func (rc *RunContext) removeNetwork(name string) common.Executor {
return func(ctx context.Context) error {
return container.NewDockerNetworkRemoveExecutor(name)(ctx)
}
}

func (rc *RunContext) execJobContainer(cmd []string, env map[string]string) common.Executor {
return func(ctx context.Context) error {
return rc.JobContainer.Exec(cmd, env)(ctx)
Expand All @@ -163,6 +212,31 @@ func (rc *RunContext) stopJobContainer() common.Executor {
}
}

func (rc *RunContext) startServiceContainers(networkName string) common.Executor {
return func(ctx context.Context) error {
execs := []common.Executor{}
for _, c := range rc.ServiceContainers {
execs = append(execs, common.NewPipelineExecutor(
c.Pull(false),
c.Create(),
c.Start(false),
c.ConnectToNetwork(networkName),
))
}
return common.NewParallelExecutor(execs...)(ctx)
}
}

func (rc *RunContext) stopServiceContainers() common.Executor {
return func(ctx context.Context) error {
execs := []common.Executor{}
for _, c := range rc.ServiceContainers {
execs = append(execs, c.Remove())
}
return common.NewParallelExecutor(execs...)(ctx)
}
}

// ActionCacheDir is for rc
func (rc *RunContext) ActionCacheDir() string {
var xdgCache string
Expand Down
36 changes: 36 additions & 0 deletions pkg/runner/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,42 @@ func TestRunEventSecrets(t *testing.T) {
assert.NilError(t, err, workflowPath)
}

func TestRunWithService(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}

log.SetLevel(log.DebugLevel)
ctx := context.Background()

platforms := map[string]string{
"ubuntu-latest": "node:12.20.1-buster-slim",
}

workflowPath := "services"
eventName := "push"

workdir, err := filepath.Abs("testdata")
assert.NilError(t, err, workflowPath)

runnerConfig := &Config{
Workdir: workdir,
EventName: eventName,
Platforms: platforms,
ReuseContainers: false,
}
runner, err := New(runnerConfig)
assert.NilError(t, err, workflowPath)

planner, err := model.NewWorkflowPlanner(fmt.Sprintf("testdata/%s", workflowPath))
Markcial marked this conversation as resolved.
Show resolved Hide resolved
assert.NilError(t, err, workflowPath)

plan := planner.PlanEvent(eventName)

err = runner.NewPlanExecutor(plan)(ctx)
assert.NilError(t, err, workflowPath)
}

func TestRunEventPullRequest(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
Expand Down
26 changes: 26 additions & 0 deletions pkg/runner/testdata/services/push.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: services
on: push
jobs:
services:
name: Reproduction of failing Services interpolation
runs-on: ubuntu-latest
services:
postgres:
image: postgres:12
env:
POSTGRES_USER: runner
POSTGRES_PASSWORD: mysecretdbpass
POSTGRES_DB: mydb
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432
steps:
- name: Echo the Postgres service ID / Network / Ports
run: |
echo "id: ${{ job.services.postgres.id }}"
echo "network: ${{ job.services.postgres.network }}"
echo "ports: ${{ job.services.postgres.ports }}"