Example #1
0
func TestInspectData(t *testing.T) {
	testCreateDataByImport(t, dataName)
	defer testKillDataCont(t, dataName)

	do := definitions.NowDo()
	do.Name = dataName
	do.Operations.Args = []string{"name"}
	do.Operations.ContainerNumber = 1
	log.WithFields(log.Fields{
		"data container": do.Name,
		"args":           do.Operations.Args,
	}).Info("Inspecting data (from tests)")
	if err := InspectData(do); err != nil {
		log.Error(err)
		t.FailNow()
	}

	do = definitions.NowDo()
	do.Name = dataName
	do.Operations.Args = []string{"config.network_disabled"}
	do.Operations.ContainerNumber = 1
	log.WithFields(log.Fields{
		"data container": do.Name,
		"args":           do.Operations.Args,
	}).Info("Inspecting data (from tests)")
	if err := InspectData(do); err != nil {
		log.Error(err)
		t.Fail()
	}
}
Example #2
0
//[zr] TODO move to testings package
func testNumbersExistAndRun(t *testing.T, servName string, containerExist, containerRun int) {
	log.WithFields(log.Fields{
		"=>":        servName,
		"existing#": containerExist,
		"running#":  containerRun,
	}).Info("Checking number of containers for")

	log.WithField("=>", servName).Debug("Checking existing containers for")
	exist := util.HowManyContainersExisting(servName, "service")

	log.WithField("=>", servName).Debug("Checking running containers for")
	run := util.HowManyContainersRunning(servName, "service")

	if exist != containerExist {
		log.WithFields(log.Fields{
			"name":     servName,
			"expected": containerExist,
			"got":      exist,
		}).Error("Wrong number of existing containers")
		fatal(t, nil)
	}

	if run != containerRun {
		log.WithFields(log.Fields{
			"name":     servName,
			"expected": containerExist,
			"got":      run,
		}).Error("Wrong number of running containers")
		fatal(t, nil)
	}

	log.Info("All good")
}
Example #3
0
func TestRenameChain(t *testing.T) {
	aChain := "hichain"
	rename1 := "niahctset"
	rename2 := chainName
	testNewChain(aChain)
	defer testKillChain(t, rename2)

	do := def.NowDo()
	do.Name = aChain
	do.NewName = rename1
	log.WithFields(log.Fields{
		"from": do.Name,
		"to":   do.NewName,
	}).Info("Renaming chain (from tests)")

	if e := RenameChain(do); e != nil {
		tests.IfExit(e)
	}

	testExistAndRun(t, rename1, true, true)

	do = def.NowDo()
	do.Name = rename1
	do.NewName = rename2
	log.WithFields(log.Fields{
		"from": do.Name,
		"to":   do.NewName,
	}).Info("Renaming chain (from tests)")
	if e := RenameChain(do); e != nil {
		tests.IfExit(e)
	}

	testExistAndRun(t, chainName, true, true)
}
Example #4
0
func TestRenameAction(t *testing.T) {
	testExist(t, newName, false)
	testExist(t, oldName, true)

	do := definitions.NowDo()
	do.Name = oldName
	do.NewName = newName
	log.WithFields(log.Fields{
		"from": do.Name,
		"to":   do.NewName,
	}).Info("Renaming action (from tests)")
	if err := RenameAction(do); err != nil {
		log.Error(err)
		t.Fail()
	}
	testExist(t, newName, true)
	testExist(t, oldName, false)

	do = definitions.NowDo()
	do.Name = newName
	do.NewName = oldName
	log.WithFields(log.Fields{
		"from": do.Name,
		"to":   do.NewName,
	}).Info("Renaming action (from tests)")
	if err := RenameAction(do); err != nil {
		log.Error(err)
		t.Fail()
	}
	testExist(t, newName, false)
	testExist(t, oldName, true)
}
Example #5
0
func MoveOutOfDirAndRmDir(src, dest string) error {
	log.WithFields(log.Fields{
		"from": src,
		"to":   dest,
	}).Info("Move all files/dirs out of a dir and `rm -fr` that dir")
	toMove, err := filepath.Glob(filepath.Join(src, "*"))
	if err != nil {
		return err
	}

	if len(toMove) == 0 {
		log.Debug("No files to move")
	}

	for _, f := range toMove {
		t := filepath.Join(dest, filepath.Base(f))
		log.WithFields(log.Fields{
			"from": f,
			"to":   t,
		}).Debug("Moving")

		// using a copy (read+write) strategy to get around swap partitions and other
		//   problems that cause a simple rename strategy to fail. it is more io overhead
		//   to do this, but for now that is preferable to alternative solutions.
		Copy(f, t)
	}

	log.WithField("=>", src).Info("Removing directory")
	err = os.RemoveAll(src)
	if err != nil {
		return err
	}

	return nil
}
Example #6
0
func TestExistAndRun(name, t string, contNum int, toExist, toRun bool) error {
	log.WithFields(log.Fields{
		"=>":       name,
		"running":  toRun,
		"existing": toExist,
	}).Info("Checking container")

	if existing := FindContainer(name, t, contNum, false); existing != toExist {
		log.WithFields(log.Fields{
			"=>":       name,
			"expected": toExist,
			"got":      existing,
		}).Info("Checking container existing")

		return ErrContainerExistMismatch
	}

	if running := FindContainer(name, t, contNum, true); running != toRun {
		log.WithFields(log.Fields{
			"=>":       name,
			"expected": toExist,
			"got":      running,
		}).Info("Checking container running")

		return ErrContainerRunMismatch
	}

	return nil
}
Example #7
0
func TestInspectService(t *testing.T) {
	testStartService(t, servName, false)
	defer testKillService(t, servName, true)

	do := def.NowDo()
	do.Name = servName
	do.Operations.Args = []string{"name"}
	do.Operations.ContainerNumber = 1
	log.WithFields(log.Fields{
		"=>":   fmt.Sprintf("%s:%d", servName, do.Operations.ContainerNumber),
		"args": do.Operations.Args,
	}).Debug("Inspect service (from tests)")

	e := InspectService(do)
	if e != nil {
		log.Infof("Error inspecting service: %v", e)
		tests.IfExit(e)
	}

	do = def.NowDo()
	do.Name = servName
	do.Operations.Args = []string{"config.user"}
	do.Operations.ContainerNumber = 1
	log.WithFields(log.Fields{
		"=>":   servName,
		"args": do.Operations.Args,
	}).Debug("Inspect service (from tests)")
	e = InspectService(do)
	if e != nil {
		log.Infof("Error inspecting service: %v", e)
		tests.IfExit(e)
	}
}
Example #8
0
func TestNewService(t *testing.T) {
	do := def.NowDo()
	servName := "keys"
	do.Name = servName
	do.Operations.Args = []string{"quay.io/eris/keys"}

	log.WithFields(log.Fields{
		"=>":   do.Name,
		"args": do.Operations.Args,
	}).Debug("Creating a new service (from tests)")
	e := NewService(do)
	if e != nil {
		log.Error(e)
		tests.IfExit(e)
	}

	do = def.NowDo()
	do.Operations.Args = []string{servName}
	log.WithFields(log.Fields{
		"container number": do.Operations.ContainerNumber,
		"args":             do.Operations.Args,
	}).Debug("Starting service (from tests)")
	e = StartService(do)
	if e != nil {
		log.Error(e)
		tests.IfExit(e)
	}

	testExistAndRun(t, servName, 1, true, true)
	testNumbersExistAndRun(t, servName, 1, 1)
	testKillService(t, servName, true)
	testExistAndRun(t, servName, 1, false, false)
}
Example #9
0
func TestLoadServiceDefinition(t *testing.T) {
	var e error
	srv, e = loaders.LoadServiceDefinition(servName, true, 1)
	if e != nil {
		log.Error(e)
		tests.IfExit(e)
	}

	if srv.Name != servName {
		log.WithFields(log.Fields{
			"expected": servName,
			"got":      srv.Name,
		}).Error("Improper name on load")
	}

	if srv.Service.Name != servName {
		log.WithFields(log.Fields{
			"expected": servName,
			"got":      srv.Service.Name,
		}).Error("Improper service name on load")

		tests.IfExit(e)
	}

	if !srv.Service.AutoData {
		log.Error("data_container not properly read on load")
		tests.IfExit(e)
	}

	if srv.Operations.DataContainerName == "" {
		log.Error("data_container_name not set")
		tests.IfExit(e)
	}
}
Example #10
0
func RenameAction(do *definitions.Do) error {
	if do.Name == do.NewName {
		return fmt.Errorf("Cannot rename to same name")
	}

	do.Name = strings.Replace(do.Name, " ", "_", -1)
	do.NewName = strings.Replace(do.NewName, " ", "_", -1)
	act, _, err := LoadActionDefinition(do.Name)
	if err != nil {
		log.WithFields(log.Fields{
			"from": do.Name,
			"to":   do.NewName,
		}).Debug("Failed renaming action")
		return err
	}

	do.Name = strings.Replace(do.Name, " ", "_", -1)
	log.WithField("file", do.Name).Debug("Finding action definition file")
	oldFile := util.GetFileByNameAndType("actions", do.Name)
	if oldFile == "" {
		return fmt.Errorf("Could not find that action definition file.")
	}
	log.WithField("file", oldFile).Debug("Found action definition file")

	// if !strings.Contains(oldFile, ActionsPath) {
	// 	oldFile = filepath.Join(ActionsPath, oldFile) + ".toml"
	// }

	var newFile string
	newNameBase := strings.Replace(strings.Replace(do.NewName, " ", "_", -1), filepath.Ext(do.NewName), "", 1)

	if newNameBase == do.Name {
		newFile = strings.Replace(oldFile, filepath.Ext(oldFile), filepath.Ext(do.NewName), 1)
	} else {
		newFile = strings.Replace(oldFile, do.Name, do.NewName, 1)
		newFile = strings.Replace(newFile, " ", "_", -1)
	}

	if newFile == oldFile {
		log.Info("Not renaming the same file")
		return nil
	}

	act.Name = strings.Replace(newNameBase, "_", " ", -1)

	log.WithFields(log.Fields{
		"old": act.Name,
		"new": newFile,
	}).Debug("Writing new action definition file")
	err = WriteActionDefinitionFile(act, newFile)
	if err != nil {
		return err
	}

	log.WithField("file", oldFile).Debug("Removing old file")
	os.Remove(oldFile)

	return nil
}
Example #11
0
func StartService(do *definitions.Do) (err error) {
	var services []*definitions.ServiceDefinition

	do.Operations.Args = append(do.Operations.Args, do.ServicesSlice...)
	log.WithField("args", do.Operations.Args).Info("Building services group")
	for _, srv := range do.Operations.Args {
		s, e := BuildServicesGroup(srv, do.Operations.ContainerNumber)
		if e != nil {
			return e
		}
		services = append(services, s...)
	}

	// [csk]: controls for ops reconciliation, overwrite will, e.g., merge the maps and stuff
	for _, s := range services {
		util.Merge(s.Operations, do.Operations)
	}

	log.Debug("Preparing to build chain")
	for _, s := range services {
		log.WithFields(log.Fields{
			"name":         s.Name,
			"dependencies": s.Dependencies,
			"links":        s.Service.Links,
			"volumes from": s.Service.VolumesFrom,
		}).Debug()

		// Spacer.
		log.Debug()
	}
	services, err = BuildChainGroup(do.ChainName, services)
	if err != nil {
		return err
	}
	log.Debug("Checking services after build chain")
	for _, s := range services {
		log.WithFields(log.Fields{
			"name":         s.Name,
			"dependencies": s.Dependencies,
			"links":        s.Service.Links,
			"volumes from": s.Service.VolumesFrom,
		}).Debug()

		// Spacer.
		log.Debug()
	}

	// NOTE: the top level service should be at the end of the list
	topService := services[len(services)-1]
	topService.Service.Environment = append(topService.Service.Environment, do.Env...)
	topService.Service.Links = append(topService.Service.Links, do.Links...)
	services[len(services)-1] = topService

	return StartGroup(services)
}
Example #12
0
func RegisterChain(do *definitions.Do) error {
	// do.Name is mandatory
	if do.Name == "" {
		return fmt.Errorf("RegisterChain requires a chainame")
	}
	etcbChain := do.ChainID
	do.ChainID = do.Name

	// NOTE: registration expects you to have the data container
	if !util.IsDataContainer(do.Name, do.Operations.ContainerNumber) {
		return fmt.Errorf("Registration requires you to have a data container for the chain. Could not find data for %s", do.Name)
	}

	chain, err := loaders.LoadChainDefinition(do.Name, false, do.Operations.ContainerNumber)
	if err != nil {
		return err
	}
	log.WithField("image", chain.Service.Image).Debug("Chain loaded")

	// set chainid and other vars
	envVars := []string{
		fmt.Sprintf("CHAIN_ID=%s", do.ChainID),                 // of the etcb chain
		fmt.Sprintf("PUBKEY=%s", do.Pubkey),                    // pubkey to register chain with
		fmt.Sprintf("ETCB_CHAIN_ID=%s", etcbChain),             // chain id of the etcb chain
		fmt.Sprintf("NODE_ADDR=%s", do.Gateway),                // etcb node to send the register tx to
		fmt.Sprintf("NEW_P2P_SEEDS=%s", do.Operations.Args[0]), // seeds to register for the chain // TODO: deal with multi seed (needs support in tendermint)
	}
	envVars = append(envVars, do.Env...)

	log.WithFields(log.Fields{
		"environment": envVars,
		"links":       do.Links,
	}).Debug("Registering chain with")
	chain.Service.Environment = append(chain.Service.Environment, envVars...)
	chain.Service.Links = append(chain.Service.Links, do.Links...)

	if err := bootDependencies(chain, do); err != nil {
		return err
	}

	log.WithFields(log.Fields{
		"=>":    chain.Service.Name,
		"image": chain.Service.Image,
	}).Debug("Performing chain container start")
	chain.Operations = loaders.LoadDataDefinition(chain.Service.Name, do.Operations.ContainerNumber)
	chain.Operations.Args = []string{loaders.ErisChainRegister}

	_, err = perform.DockerRunData(chain.Operations, chain.Service)

	return err
}
Example #13
0
func readActionDefinition(actionName []string, dropped map[string]string, varNum int) (*viper.Viper, map[string]string, error) {
	if len(actionName) == 0 {
		log.WithFields(log.Fields{
			"action": actionName,
			"drop":   dropped,
			"var#":   varNum,
		}).Debug("Failed to load action definition file")
		return nil, dropped, fmt.Errorf("The marmots could not find the action definition file.\nPlease check your actions with [eris actions ls]")
	}

	log.WithField("file", strings.Join(actionName, "_")).Debug("Preparing to read action definition file")
	log.WithField("drop", dropped).Debug()

	var actionConf = viper.New()

	actionConf.AddConfigPath(dir.ActionsPath)
	actionConf.SetConfigName(strings.Join(actionName, "_"))
	err := actionConf.ReadInConfig()

	if err != nil {
		log.WithField("action", actionName[len(actionName)-1]).Debug("Dropping and retrying")
		dropped[fmt.Sprintf("$%d", varNum)] = actionName[len(actionName)-1]
		actionName = actionName[:len(actionName)-1]
		varNum++
		return readActionDefinition(actionName, dropped, varNum)
	} else {
		log.Debug("Successfully read action definition file")
	}

	return actionConf, dropped, nil
}
Example #14
0
func setAppType(app *definitions.Contracts, name, command, typ string) error {
	var t string

	log.WithFields(log.Fields{
		"task": command,
		"type": typ,
		"app":  name,
	}).Debug("Setting app type")

	if typ != "" {
		t = typ
	} else {
		switch command {
		case "test":
			t = app.TestType
		case "deploy":
			t = app.DeployType
		}
	}

	switch t {
	case "embark":
		app.AppType = definitions.EmbarkApp()
	case "sunit":
		app.AppType = definitions.SUnitApp()
	case "manual":
		app.AppType = definitions.GulpApp()
	default:
		app.AppType = definitions.EPMApp()
	}

	log.WithField("app type", app.AppType.Name).Debug()

	return nil
}
Example #15
0
func Migrate(dirsToMigrate map[string]string) error {
	for depDir, newDir := range dirsToMigrate {
		if !DoesDirExist(depDir) && !DoesDirExist(newDir) {
			return fmt.Errorf("neither deprecated (%s) or new (%s) exists. please run `init` prior to `update`\n", depDir, newDir)
		} else if DoesDirExist(depDir) && !DoesDirExist(newDir) { //never updated, just rename dirs
			if err := os.Rename(depDir, newDir); err != nil {
				return err
			}
			log.WithFields(log.Fields{
				"from": depDir,
				"to":   newDir,
			}).Warn("Directory migration successful")
		} else if DoesDirExist(depDir) && DoesDirExist(newDir) { //both exist, better check what's in them
			if err := checkFileNamesAndMigrate(depDir, newDir); err != nil {
				return err
			}
			// [csk] once the files are migrated we need to remove the dir or
			// the DoesDirExist function will return.
			if err := os.Remove(depDir); err != nil {
				return err
			}
		} else { //should never throw
			return fmt.Errorf("unknown and unresolveable conflict between directory to deprecate (%s) and new directory (%s)\n", depDir, newDir)
		}
		if DoesDirExist(depDir) {
			return fmt.Errorf("deprecated directory (%s) still exists, something went wrong", depDir)
		}
	}

	return nil
}
Example #16
0
// DockerExecData runs a data container with volumes-from field set interactively.
//
//  ops.Args         - command line parameters
//  ops.Interactive  - if true, set Entrypoint to ops.Args,
//                     if false, set Cmd to ops.Args
//
// See parameter description for DockerRunData.
func DockerExecData(ops *def.Operation, service *def.Service) (err error) {
	log.WithFields(log.Fields{
		"=>":   ops.DataContainerName,
		"args": ops.Args,
	}).Info("Executing data container")

	opts := configureVolumesFromContainer(ops, service)
	log.WithField("image", opts.Config.Image).Info("Data container configured")

	_, err = createContainer(opts)
	if err != nil {
		return err
	}

	// Clean up the container.
	defer func() {
		log.WithField("=>", opts.Name).Info("Removing data container")
		if err2 := removeContainer(opts.Name, true, false); err2 != nil {
			if os.Getenv("CIRCLE_BRANCH") == "" {
				err = fmt.Errorf("Tragic! Error removing data container after executing (%v): %v", err, err2)
			}
		}
		log.WithField("=>", opts.Name).Info("Data container removed")
	}()

	// Start the container.
	log.WithField("=>", opts.Name).Info("Executing interactive data container")
	if err = startInteractiveContainer(opts); err != nil {
		return err
	}

	return nil
}
Example #17
0
// DockerStop stops a running ops.SrvContainerName container unforcedly.
// timeout is a number of seconds to wait before killing the container process
// ungracefully.
// It returns Docker errors on exit if not successful. DockerStop doesn't return
// an error if the container isn't running.
func DockerStop(srv *def.Service, ops *def.Operation, timeout uint) error {
	// don't limit this to verbose because it takes a few seconds
	// [zr] unless force sets timeout to 0 (for, eg. stdout)
	if timeout != 0 {
		log.WithField("=>", srv.Name).Warn("Stopping (may take a few seconds)")
	}

	log.WithFields(log.Fields{
		"=>":      ops.SrvContainerName,
		"timeout": timeout,
	}).Info("Stopping container")

	_, running := ContainerExists(ops)
	if running {
		log.WithField("=>", ops.SrvContainerName).Debug("Container found running")

		err := stopContainer(ops.SrvContainerName, timeout)
		if err != nil {
			return err
		}
	} else {
		log.WithField("=>", ops.SrvContainerName).Debug("Container found not running")
	}

	log.WithField("=>", ops.SrvContainerName).Info("Container stopped")

	return nil
}
Example #18
0
func TestSetGlobalObjectDefaultConfig(t *testing.T) {
	ChangeErisDir(configErisDir)

	cli, err := SetGlobalObject(os.Stderr, os.Stdout)
	if err != nil {
		t.Fatalf("expected success, got error %v", err)
	}

	defaults, err := SetDefaults()
	if err != nil {
		t.Fatalf("expected defaults loaded, got error %v", err)
	}

	if def, returned := defaults.Get("IpfsHost"), cli.Config.IpfsHost; reflect.DeepEqual(returned, def) != true {
		t.Fatalf("expected default %q, got %q", returned, def)
	}

	if def, returned := defaults.Get("CompilersHost"), cli.Config.CompilersHost; reflect.DeepEqual(returned, def) != true {
		t.Fatalf("expected default %q, got %q", returned, def)
	}

	log.WithFields(log.Fields{
		"ipfshost":       cli.Config.IpfsHost,
		"compilers host": cli.Config.CompilersHost,
		"host":           cli.Config.DockerHost,
		"cert path":      cli.Config.DockerCertPath,
		"verbose":        cli.Config.Verbose,
	}).Info("Checking defaults")
}
Example #19
0
func TestStartKillServiceWithDependencies(t *testing.T) {
	do := def.NowDo()
	do.Operations.Args = []string{"do_not_use"}
	log.WithFields(log.Fields{
		"service":    servName,
		"dependency": "keys",
	}).Debug("Starting service with dependency (from tests)")
	if e := StartService(do); e != nil {
		log.Infof("Error starting service: %v", e)
		tests.IfExit(e)
	}

	defer func() {
		testKillService(t, "do_not_use", true)

		testExistAndRun(t, servName, 1, false, false)
		testNumbersExistAndRun(t, servName, 0, 0)

		testKillService(t, "keys", true)
	}()

	testExistAndRun(t, servName, 1, true, true)
	testExistAndRun(t, "keys", 1, true, true)

	testNumbersExistAndRun(t, "keys", 1, 1)
	testNumbersExistAndRun(t, servName, 1, 1)
}
Example #20
0
// links and mounts for service dependencies
func connectToAService(srv *definitions.Service, ops *definitions.Operation, typ, name, internalName string, link, mount bool) {
	log.WithFields(log.Fields{
		"=>":            srv.Name,
		"type":          typ,
		"name":          name,
		"internal name": internalName,
		"link":          link,
		"volumes from":  mount,
	}).Debug("Connecting to service")
	containerName := util.ContainersName(typ, name, ops.ContainerNumber)

	if link {
		newLink := containerName + ":" + internalName
		srv.Links = append(srv.Links, newLink)
	}

	if mount {
		// Automagically mount VolumesFrom for serviceDeps so they can
		// easily pass files back and forth. note that this is opinionated
		// and will mount as read-write. we can revisit this if read-only
		// mounting required for specific use cases
		newVol := containerName + ":rw"
		srv.VolumesFrom = append(srv.VolumesFrom, newVol)
	}
}
Example #21
0
func Do(do *definitions.Do) error {
	log.WithFields(log.Fields{
		"chain":    do.ChainName,
		"services": do.ServicesSlice,
	}).Info("Performing action")

	var err error
	var actionVars []string
	do.Action, actionVars, err = LoadActionDefinition(strings.Join(do.Operations.Args, "_"))
	if err != nil {
		return err
	}

	resolveServices(do)
	resolveChain(do)
	fixChain(do.Action, do.ChainName)

	if err := StartServicesAndChains(do); err != nil {
		return err
	}

	if err := PerformCommand(do.Action, actionVars, do.Quiet); err != nil {
		return err
	}

	return nil
}
Example #22
0
func NewService(do *definitions.Do) error {
	srv := definitions.BlankServiceDefinition()
	srv.Name = do.Name
	srv.Service.Name = do.Name
	srv.Service.Image = do.Operations.Args[0]
	srv.Service.AutoData = true

	var err error
	//get maintainer info
	srv.Maintainer.Name, srv.Maintainer.Email, err = config.GitConfigUser()
	if err != nil {
		log.Debug(err.Error())
	}

	log.WithFields(log.Fields{
		"service": srv.Service.Name,
		"image":   srv.Service.Image,
	}).Debug("Creating a new service definition file")
	err = WriteServiceDefinitionFile(srv, filepath.Join(ServicesPath, do.Name+".toml"))
	if err != nil {
		return err
	}
	do.Result = "success"
	return nil
}
Example #23
0
// ImportData does what it says. It imports from a host's Source to a Dest
// in a data container. It returns an error.
//
//  do.Name                       - name of the data container to use (required)
//  do.Operations.ContainerNumber - container number (optional)
//  do.Source                     - directory which should be imported (required)
//  do.Destination                - directory to _unload_ the payload into (required)
//
func ImportData(do *definitions.Do) error {
	log.WithFields(log.Fields{
		"from": do.Source,
		"to":   do.Destination,
	}).Debug("Importing")
	if util.IsDataContainer(do.Name, do.Operations.ContainerNumber) {

		srv := PretendToBeAService(do.Name, do.Operations.ContainerNumber)
		service, exists := perform.ContainerExists(srv.Operations)

		if !exists {
			return fmt.Errorf("There is no data container for that service.")
		}
		if err := checkErisContainerRoot(do, "import"); err != nil {
			return err
		}

		containerName := util.DataContainersName(do.Name, do.Operations.ContainerNumber)
		os.Chdir(do.Source)

		reader, err := util.Tar(do.Source, 0)
		if err != nil {
			return err
		}
		defer reader.Close()

		opts := docker.UploadToContainerOptions{
			InputStream:          reader,
			Path:                 do.Destination,
			NoOverwriteDirNonDir: true,
		}

		log.WithField("=>", containerName).Info("Copying into container")
		log.WithField("path", do.Source).Debug()
		if err := util.DockerClient.UploadToContainer(service.ID, opts); err != nil {
			return err
		}

		doChown := definitions.NowDo()
		doChown.Operations.DataContainerName = containerName
		doChown.Operations.ContainerType = "data"
		doChown.Operations.ContainerNumber = do.Operations.ContainerNumber
		//required b/c `docker cp` (UploadToContainer) goes in as root
		doChown.Operations.Args = []string{"chown", "--recursive", "eris", do.Destination}
		_, err = perform.DockerRunData(doChown.Operations, nil)
		if err != nil {
			return fmt.Errorf("Error changing owner: %v\n", err)
		}
	} else {
		log.WithField("name", do.Name).Info("Data container does not exist.")
		ops := loaders.LoadDataDefinition(do.Name, do.Operations.ContainerNumber)
		if err := perform.DockerCreateData(ops); err != nil {
			return fmt.Errorf("Error creating data container %v.", err)
		}
		return ImportData(do)
	}
	do.Result = "success"
	return nil
}
Example #24
0
func giveMeAllTheNames(name string, srv *def.ServiceDefinition) {
	log.WithField("=>", name).Debug("Giving myself all the names")
	srv.Name = name
	srv.Service.Name = name
	srv.Operations.SrvContainerName = util.DataContainersName(srv.Name, srv.Operations.ContainerNumber)
	srv.Operations.DataContainerName = util.DataContainersName(srv.Name, srv.Operations.ContainerNumber)
	log.WithFields(log.Fields{
		"data container":    srv.Operations.DataContainerName,
		"service container": srv.Operations.SrvContainerName,
	}).Debug("Using names")
}
Example #25
0
func PerformAppActionService(do *definitions.Do, app *definitions.Contracts) error {
	log.Warn("Performing action. This can sometimes take a wee while")
	log.WithFields(log.Fields{
		"service": do.Service.Name,
		"image":   do.Service.Image,
	}).Info()
	log.WithFields(log.Fields{
		"workdir":    do.Service.WorkDir,
		"entrypoint": do.Service.EntryPoint,
	}).Debug()

	do.Operations.ContainerType = definitions.TypeService
	if err := perform.DockerExecService(do.Service, do.Operations); err != nil {
		do.Result = "could not perform app action"
		return err
	}

	log.Info("Finished performing app action")
	return nil
}
Example #26
0
func TestRenameService(t *testing.T) {
	testStartService(t, "keys", false)
	testExistAndRun(t, "keys", 1, true, true)
	testNumbersExistAndRun(t, "keys", 1, 1)

	do := def.NowDo()
	do.Name = "keys"
	do.NewName = "syek"
	log.WithFields(log.Fields{
		"from": do.Name,
		"to":   do.NewName,
	}).Debug("Renaming service (from tests)")
	if e := RenameService(do); e != nil {
		tests.IfExit(fmt.Errorf("Error (tests fail) =>\t\t%v\n", e))
	}

	testExistAndRun(t, "syek", 1, true, true)
	testExistAndRun(t, "keys", 1, false, false)
	testNumbersExistAndRun(t, "syek", 1, 1)
	testNumbersExistAndRun(t, "keys", 0, 0)

	do = def.NowDo()
	do.Name = "syek"
	do.NewName = "keys"
	log.WithFields(log.Fields{
		"from": do.Name,
		"to":   do.NewName,
	}).Debug("Renaming service (from tests)")
	if e := RenameService(do); e != nil {
		log.Errorf("Error (tests fail): %v", e)
		tests.IfExit(e)
	}

	testExistAndRun(t, "keys", 1, true, true)
	testExistAndRun(t, "syek", 1, false, false)
	testNumbersExistAndRun(t, "keys", 1, 1)
	testNumbersExistAndRun(t, "syek", 0, 0)

	testKillService(t, "keys", true)
	testExistAndRun(t, "keys", 1, false, false)
}
Example #27
0
func removeErisImages(prompt bool) error {
	opts := docker.ListImagesOptions{
		All:     true,
		Filters: nil,
		Digests: false,
	}
	allTheImages, err := DockerClient.ListImages(opts)
	if err != nil {
		return err
	}

	//get all repo tags & IDs
	// [zr] this could probably be cleaner
	repoTags := make(map[int][]string)
	imageIDs := make(map[int]string)
	for i, image := range allTheImages {
		repoTags[i] = image.RepoTags
		imageIDs[i] = image.ID
	}

	erisImages := []string{}
	erisImageIDs := []string{}

	//searches through repo tags for eris images & "maps" to ID
	for i, repoTag := range repoTags {
		for _, rt := range repoTag {
			r, err := regexp.Compile(`eris`)
			if err != nil {
				log.Errorf("Regexp error: %v", err)
			}

			if r.MatchString(rt) == true {
				erisImages = append(erisImages, rt)
				erisImageIDs = append(erisImageIDs, imageIDs[i])
			}
		}
	}

	if !prompt || canWeRemove(erisImages, "images") {
		for i, imageID := range erisImageIDs {
			log.WithFields(log.Fields{
				"=>": erisImages[i],
				"id": imageID,
			}).Debug("Removing image")
			if err := DockerClient.RemoveImage(imageID); err != nil {
				return err
			}
		}
	} else {
		log.Warn("Permission to remove images not given, continuing with clean")
	}
	return nil
}
Example #28
0
func ListFiles(do *definitions.Do) error {
	ensureRunning()
	log.WithFields(log.Fields{
		"file": do.Name,
		"path": do.Path,
	}).Debug("Listing an object")
	hash, err := listFile(do.Name)
	if err != nil {
		return err
	}
	do.Result = hash
	return nil
}
Example #29
0
func CatFiles(do *definitions.Do) error {
	ensureRunning()
	log.WithFields(log.Fields{
		"file": do.Name,
		"path": do.Path,
	}).Debug("Dumping the contents of a file")
	hash, err := catFile(do.Name)
	if err != nil {
		return err
	}
	do.Result = hash
	return nil
}
Example #30
0
func TestRenameData(t *testing.T) {
	testCreateDataByImport(t, dataName)
	defer testKillDataCont(t, dataName)

	testExist(t, dataName, true)
	testExist(t, newName, false)

	do := definitions.NowDo()
	do.Name = dataName
	do.NewName = newName
	do.Operations.ContainerNumber = 1
	log.WithFields(log.Fields{
		"from": do.Name,
		"to":   do.NewName,
	}).Info("Renaming data (from tests)")
	if err := RenameData(do); err != nil {
		log.Error(err)
		t.FailNow()
	}

	testExist(t, dataName, false)
	testExist(t, newName, true)

	do = definitions.NowDo()
	do.Name = newName
	do.NewName = dataName
	do.Operations.ContainerNumber = 1
	log.WithFields(log.Fields{
		"from": do.Name,
		"to":   do.NewName,
	}).Info("Renaming data (from tests)")
	if err := RenameData(do); err != nil {
		log.Error(err)
		t.FailNow()
	}

	testExist(t, dataName, true)
	testExist(t, newName, false)
}