Example #1
0
func RequireDaemon() {
	if c := cmd.ExitCode("docker", "ps"); c != 0 {
		cli.Logf("`docker ps` exited with code %d", c)
		if dockermachine.Installed() {
			vms := dockermachine.RunningVMs()
			if len(vms) != 0 {
				cli.Fatalf(`Tip: eval "$(docker-machine env %s)"`, vms[0])
			}
			vms = dockermachine.VMs()
			switch len(vms) {
			case 0:
				cli.Logf("Tip: you should create a machine using docker-machine")
			case 1:
				start := ""
				if cmd.Stdout("docker-machine", "status", vms[0]) != "Running" {
					start = fmt.Sprintf("docker-machine start %s && ", vms[0])
				}
				cli.Logf(`Tip: %seval "$(docker-machine env %s)"`, start, vms[0])
			default:
				cli.Logf("Tip: start one of your docker machines (%s)",
					strings.Join(vms, ", "))
			}
		}
		cli.Fatal()
	}
}
Example #2
0
func Ls(sous *core.Sous, args []string) {
	//globalFlag := lsFlags.Bool("g", false, "global: list files in all projects sous has built")
	//lsFlags.Parse(args)
	//global := *globalFlag
	args = lsFlags.Args()
	if len(args) != 0 {
		cli.Fatalf("sous ls does not accept any arguments")
	}
	_, context := sous.AssembleTargetContext("app")
	cli.Outf(" ===> Images")
	images := sous.LsImages(context)
	if len(images) == 0 {
		cli.Logf("  no images for this project")
	}
	for _, image := range images {
		cli.Logf("  %s:%s", image.Name, image.Tag)
	}
	cli.Outf(" ===> Containers")
	containers := sous.LsContainers(context)
	if len(containers) == 0 {
		cli.Logf("  no containers for this project")
	}
	for _, container := range containers {
		cli.Logf("  %s (%s)", container.Name(), container.CID())
	}
	cli.Success()
}
Example #3
0
func Contracts(sous *core.Sous, args []string) {
	contractsFlags.Parse(args)
	args = contractsFlags.Args()
	timeout := *timeoutFlag
	targetName := "app"
	if len(args) != 0 {
		targetName = args[0]
	}
	core.RequireGit()
	core.RequireDocker()

	if *dockerImage != "" {
		cli.Fatalf("-image flag not yet implemented")
	}

	target, context := sous.AssembleTargetContext(targetName)

	sous.RunTarget(target, context)

	cli.Logf("=> Running Contracts")
	cli.Logf(`=> **TIP:** Open another terminal in this directory and type **sous logs -f**`)

	taskHost := core.DivineTaskHost()
	port0, err := ports.GetFreePort()
	if err != nil {
		cli.Fatalf("Unable to get free port: %s", err)
	}

	dr := docker.NewRun(context.DockerTag())
	dr.AddEnv("PORT0", strconv.Itoa(port0))
	dr.AddEnv("TASK_HOST", taskHost)
	dr.StdoutFile = context.FilePath("stdout")
	dr.StderrFile = context.FilePath("stderr")
	container, err := dr.Background().Start()
	if err != nil {
		cli.Fatalf("Unable to start container: %s", err)
	}
	cli.AddCleanupTask(func() error {
		return container.KillIfRunning()
	})

	failed := 0
	for _, c := range theContracts {
		cli.Logf(`===> CHECKING CONTRACT: "%s"`, c.Name)
		cli.Logf(`===> Description: %s`, c.Desc(dr))
		if c.Tips != nil {
			cli.Logf("===> **TIPS for this contract:**")
			cli.LogBulletList("     -", c.Tips(dr))
		}
		failed += within(timeout, func() bool {
			return c.Premise(dr)
		})
	}

	if failed != 0 {
		cli.Fatalf("%d contracts failed.", failed)
	}

	cli.Success()
}
Example #4
0
func HostIP(vm string) string {
	var dmi *DMInfo
	cli.Logf("HOSTIP")
	cmd.JSON(&dmi, "docker-machine", "inspect", vm)
	cli.Logf("HOSTIP: %+v", dmi)
	return dmi.Driver.IPAddress
}
Example #5
0
// RunTarget is used to run the top-level target from build commands.
func (s *Sous) RunTarget(t Target, c *Context) (bool, interface{}) {
	if !c.ChangesSinceLastBuild().Any() {
		if !s.Flags.ForceRebuild {
			cli.Logf("No changes since last build.")
			cli.Logf("TIP: use -rebuild to rebuild anyway, or -rebuild-all to rebuild all dependencies")
			return false, nil
		}
	}
	cli.Logf(`** ===> Building top-level target "%s"**`, t.Name())
	return s.runTarget(t, c, false)
}
Example #6
0
func cleanContainers(sous *core.Sous, context *core.Context) bool {
	success := true
	for _, c := range sous.LsContainers(context) {
		if err := c.ForceRemove(); err != nil {
			cli.Logf("Failed to remove container %s (%s)", c.Name(), c.CID())
			success = false
		} else {
			cli.Logf("Removed container %s (%s)", c.Name(), c.CID())
		}
	}
	return success
}
Example #7
0
func cleanImages(sous *core.Sous, context *core.Context) bool {
	success := true
	for _, i := range sous.LsImages(context) {
		if err := i.Remove(); err != nil {
			cli.Logf("Failed to remove image %s:%s", i.Name, i.Tag)
			success = false
		} else {
			cli.Logf("Removed image %s:%s", i.Name, i.Tag)
		}
	}
	return success
}
Example #8
0
func (C *CMD) execute() (code int, err error) {
	c := exec.Command(C.Name, C.Args...)
	c.Stdout = C.Stdout
	c.Stderr = C.Stderr
	c.Env = os.Environ()
	if C.EchoStdout {
		c.Stdout = io.MultiWriter(os.Stdout, c.Stdout)
	}
	if C.EchoStderr {
		c.Stderr = io.MultiWriter(os.Stderr, c.Stderr)
	}
	if C.WriteStdout != nil {
		c.Stdout = io.MultiWriter(C.WriteStdout, c.Stdout)
	}
	if C.WriteStderr != nil {
		c.Stderr = io.MultiWriter(C.WriteStderr, c.Stderr)
	}
	if C.EchoStdout || C.EchoStderr {
		cli.Logf("shell> %s", C)
	}
	if err := c.Start(); err != nil {
		cli.Fatalf("Unable to begin command execution; %s", err)
	}
	err = c.Wait()
	if err != nil {
		if exiterr, ok := err.(*exec.ExitError); ok {
			if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
				return status.ExitStatus(), err
			}
		}
		cli.Fatalf("Command failed, unable to get exit code: %s", C)
	}
	return 0, nil
}
Example #9
0
func (s *Sous) RunContainerTarget(t ContainerTarget, c *Context, imageRebuilt bool) (*docker.Run, bool) {
	stale, reason, container := s.NewContainerNeeded(t, c, imageRebuilt)
	if stale {
		cli.Logf("** ===> Creating new %s container because %s**", t.Name(), reason)
		if container != nil {
			cli.Logf("Force-removing old container %s", container)
			if err := container.ForceRemove(); err != nil {
				cli.Fatalf("Unable to remove outdated container %s; %s", container, err)
			}
		}
		run := t.DockerRun(c)
		run.Name = t.ContainerName(c)
		return run, true
	}
	cli.Logf("** ===> Re-using build container %s**", container)
	return docker.NewReRun(container), false
}
Example #10
0
func (s *Sous) buildImageIfNecessary(t Target, c *Context, asDependency bool, depsRebuilt []string) bool {
	stale, reason := s.needsToBuildNewImage(t, c, asDependency, depsRebuilt)
	if !stale {
		return false
	}
	cli.Logf("** ===> Rebuilding image for %s because %s**", t.Name(), reason)
	s.BuildImage(t, c)
	return true
}
Example #11
0
func (s *MergedState) Diff(dcName string) []Diff {
	dc := s.CompiledDatacentre(dcName)
	c := singularity.NewClient(dc.SingularityURL)
	rs, err := c.Requests()
	if err != nil {
		cli.Fatalf("%s", err)
	}
	cli.Logf("%s: %d", dc.SingularityURL, len(rs))
	return dc.DiffRequests()
}
Example #12
0
func (s *Sous) runTarget(t Target, c *Context, asDependency bool) (bool, interface{}) {
	depsRebuilt := []string{}
	deps := t.DependsOn()
	if len(deps) != 0 {
		for _, d := range deps {
			cli.Logf("** ===> Building dependency \"%s\"**", d.Name())
			dt, dc := s.AssembleTargetContext(d.Name())
			depRebuilt, state := s.runTarget(dt, dc, true)
			if depRebuilt {
				depsRebuilt = append(depsRebuilt, d.Name())
			}
			if ss, ok := t.(SetStater); ok {
				ss.SetState(dt.Name(), state)
			}
		}
		cli.Logf("** ===> All dependencies of %s built**", t.Name())
	}
	// Now we have run all dependencies, run this
	// one if necessary...
	rebuilt := s.buildImageIfNecessary(t, c, asDependency, depsRebuilt)
	// If this is a dep and target specifies a docker container, invoke it.
	if asDependency {
		if ct, ok := t.(ContainerTarget); ok {
			//cli.Logf("** ===> Running target image \"%s\"**", t.Name())
			run, _ := s.RunContainerTarget(ct, c, rebuilt)
			if run.ExitCode() != 0 {
				cli.Fatalf("** =x=> Docker run failed.**")
			}
		}
	}
	// Get any available state...
	var state interface{}
	if s, ok := t.(Stater); ok {
		state = s.State(c)
	}
	return rebuilt, state
}
Example #13
0
func CheckForProblems(pack Pack) (fatal bool) {
	// Now we know that the user was asking for something possible with the detected build pack,
	// let's make sure that build pack is properly compatible with this project
	issues := pack.Problems()
	warnings, errors := issues.Warnings(), issues.Errors()
	if len(warnings) != 0 {
		cli.LogBulletList("WARNING:", issues.Strings())
	}
	if len(errors) != 0 {
		cli.LogBulletList("ERROR:", errors.Strings())
		cli.Logf("ERROR: Your project cannot be built by Sous until the above errors are rectified")
		return true
	}
	return false
}
Example #14
0
func Config(sous *core.Sous, args []string) {
	if len(args) == 0 || len(args) > 2 {
		cli.Fatalf("usage: sous config <key> [<new-value>]")
	}
	if len(args) == 1 {
		if v, ok := config.Properties()[args[0]]; ok {
			cli.Outf(v)
			cli.Success()
		}
		cli.Fatalf("Key %s not found", args[0])
	}
	config.Set(args[0], args[1])
	cli.Logf("Successfully set %s to %s", args[0], args[1])
	cli.Success()
}
Example #15
0
func (p *Pack) baseDockerfile(target string) *docker.Dockerfile {
	np := p.PackageJSON
	nodeVersion := p.bestSupportedNodeVersion()
	from := p.dockerFrom(nodeVersion, target) + ":latest"
	npmVer := defaultNPMVersion
	if np.Engines.NPM != "" {
		npmVer = version.Range(np.Engines.NPM).BestMatchFrom(npmVersions)
		if npmVer == nil {
			cli.Logf("NPM version %s not supported, try using a range instead.", np.Engines.NPM)
			cli.Fatalf("Available NPM version ranges are: '^3' and '^2'")
		}
	}
	df := &docker.Dockerfile{
		From:        from,
		Add:         []docker.Add{docker.Add{Files: []string{"."}, Dest: wd}},
		Workdir:     wd,
		LabelPrefix: "com.opentable",
	}
	df.AddLabel("build.pack.nodejs.version", nodeVersion)
	return df
}
Example #16
0
func Run(sous *core.Sous, args []string) {
	targetName := "app"
	if len(args) != 0 {
		targetName = args[0]
	}
	core.RequireGit()
	core.RequireDocker()

	target, context := sous.AssembleTargetContext(targetName)
	runner, ok := target.(core.ContainerTarget)
	if !ok {
		cli.Fatalf("Target %s does not support running.", target.Name())
	}

	rebuilt, _ := sous.RunTarget(target, context)
	dr, _ := sous.RunContainerTarget(runner, context, rebuilt)
	if exitCode := dr.ExitCode(); exitCode != 0 {
		cli.Logf("Docker container exited with code %d", exitCode)
		cli.Exit(exitCode)
	}
	cli.Success()
}
Example #17
0
func checkForUpdates() {
	cli.Logf("Checking for updates...")
	if err := config.Update(); err != nil {
		cli.Logf("Unable to check: %s", err)
	}
}