Esempio n. 1
0
// Try to Tooligure a project by parsing yaml from a byte stream
func (tools *Tools) from_ToolYamlBytes(logger log.Log, project *conf.Project, yamlBytes []byte) bool {
	if project != nil {
		// token replace
		tokens := &project.Tokens
		yamlBytes = []byte(tokens.TokenReplace(string(yamlBytes)))
	}

	var yaml_tools map[string]map[string]interface{}
	err := yaml.Unmarshal(yamlBytes, &yaml_tools)
	if err != nil {
		logger.Warning("Could not parse tool yaml:" + err.Error())
		return false
	}

	for name, tool_struct := range yaml_tools {
		switch tool_struct["Type"] {
		case "script":
			json_tool, _ := json.Marshal(tool_struct)
			var scriptTool Tool_Script
			err := json.Unmarshal(json_tool, &scriptTool)
			if err != nil {
				logger.Warning("Couldn't process tool [" + name + "] :" + err.Error())
				continue
			}

			tool := Tool(&scriptTool)
			tool.Init(logger.MakeChild("SCRIPT:"+name), project)

			tools.SetTool(name, tool)
		}

	}
	return true
}
Esempio n. 2
0
func (operation *BuildOperation) Run(logger log.Log) bool {
	logger.Info("Running operation: build")
	logger.Debug(log.VERBOSITY_DEBUG, "Run:Targets", operation.targets.TargetOrder())

	for _, targetID := range operation.targets.TargetOrder() {
		target, targetExists := operation.targets.Target(targetID)
		if !targetExists {
			// this is strange
			logger.Warning("Internal target error, was told to use a target that doesn't exist")
			continue
		}

		node, hasNode := target.Node()
		nodeLogger := logger.MakeChild(targetID)

		if !hasNode {
			nodeLogger.Info("No node [" + node.MachineName() + "]")
		} else if !node.Can("build") {
			nodeLogger.Info("Node doesn't build [" + node.MachineName() + "]")
		} else {
			nodeLogger.Message("Building node")
			node.Client().Build(nodeLogger, operation.force)
		}
	}

	return true
}
// Try to configure factories by parsing yaml from a byte stream
func (clientFactories *ClientFactories) from_ClientFactoriesYamlBytes(logger log.Log, project *conf.Project, yamlBytes []byte) bool {
	if project != nil {
		// token replace
		tokens := &project.Tokens
		yamlBytes = []byte(tokens.TokenReplace(string(yamlBytes)))
	}

	var yaml_clients map[string]map[string]interface{}
	err := yaml.Unmarshal(yamlBytes, &yaml_clients)
	if err != nil {
		logger.Warning("YAML parsing error : " + err.Error())
		return false
	}
	logger.Debug(log.VERBOSITY_DEBUG_STAAAP, "YAML source:", yaml_clients)

	for name, client_struct := range yaml_clients {
		clientType := ""
		client_json, _ := json.Marshal(client_struct)
		logger.Debug(log.VERBOSITY_DEBUG_STAAAP, "Single client JSON:", string(client_json))

		if clientType_struct, ok := client_struct["Type"]; ok {
			clientType, _ = clientType_struct.(string)
		} else {
			clientType = name
		}

		switch strings.ToLower(clientType) {
		case "docker":
			fallthrough
		case "fsouza":

			clientFactorySettings := &FSouza_ClientFactorySettings{}
			err := json.Unmarshal(client_json, clientFactorySettings)

			if err != nil {
				logger.Warning("Factory definition failed to configure client factory :" + err.Error())
				logger.Debug(log.VERBOSITY_DEBUG, "Factory configuration json: ", string(client_json), clientFactorySettings)
				continue
			}

			factory := FSouza_ClientFactory{}
			if !factory.Init(logger.MakeChild(clientType), project, ClientFactorySettings(clientFactorySettings)) {
				logger.Error("Failed to initialize FSouza factory from client factory configuration: " + err.Error())
				continue
			}

			// Add this factory to the factory list
			logger.Debug(log.VERBOSITY_DEBUG_LOTS, "Client Factory Created [Client_DockerFSouzaFactory]", factory)
			clientFactories.AddClientFactory(clientType, ClientFactory(&factory))

		case "":
			logger.Warning("Client registration failure, client has a bad value for 'Type'")
		default:
			logger.Warning("Client registration failure, client has an unknown value for 'Type' :" + clientType)
		}

	}

	return true
}
func (operation *InitGenerateOperation) Run(logger log.Log) bool {
	logger.Info("running init operation:" + operation.output)

	var writer io.Writer
	switch operation.output {
	case "logger":
		fallthrough
	case "":
		writer = logger
	default:
		if strings.HasSuffix(operation.output, ".") {
			operation.output = operation.output + operation.handler
		}
		if fileWriter, err := os.Create(operation.output); err == nil {
			operation.skip = append(operation.skip, operation.output)
			writer = io.Writer(fileWriter)
			defer fileWriter.Close()
			logger.Message("Opening file for init generation output: " + operation.output)
		} else {
			logger.Error("Could not open output file to write init to:" + operation.output)
		}
	}

	initialize.Init_Generate(logger.MakeChild("init-generate"), operation.handler, operation.root, operation.skip, operation.sizeLimit, writer)

	return true
}
Esempio n. 5
0
func (operation *StatusOperation) Run(logger log.Log) bool {
	logger.Message("RUNNING Status OPERATION")

	logger.Debug(log.VERBOSITY_DEBUG, "Run:Targets", operation.targets.TargetOrder())
	for _, targetID := range operation.targets.TargetOrder() {
		target, targetExists := operation.targets.Target(targetID)
		node, hasNode := target.Node()
		instances, hasInstances := target.Instances()

		if !targetExists {
			// this is strange
			logger.Warning("Internal target error, was told to use a target that doesn't exist")
			continue
		}

		nodeLogger := logger.MakeChild(targetID)
		status := []string{}

		if hasNode {
			status = append(status, operation.NodeStatus(nodeLogger, node)...)
		} else {
			status = append(status, "No node for target")
		}
		if hasInstances {
			status = append(status, operation.InstancesStatus(nodeLogger, instances)...)
		} else {
			status = append(status, "No instances for target")
		}

		nodeLogger.Message("[" + strings.Join(status, "][") + "]")
	}

	return true
}
Esempio n. 6
0
func (clientFactory *FSouza_ClientFactory) Init(logger log.Log, project *conf.Project, settings ClientFactorySettings) bool {
	clientFactory.log = logger
	clientFactory.conf = project

	// make sure that the settings that were given, where the proper "FSouza_ClientFactory" type
	typedSettings := settings.Settings()
	switch asserted := typedSettings.(type) {
	case *FSouza_ClientFactorySettings:
		clientFactory.settings = *asserted
	default:
		logger.Error("Invalid settings type passed to Fsouza Factory")
		logger.Debug(log.VERBOSITY_DEBUG, "Settings passed:", asserted)
	}

	// if we haven't made an actual fsouza docker client, then do it now
	if clientFactory.client == nil {
		if client, pk := clientFactory.makeFsouzaClientWrapper(logger.MakeChild("fsouza")); pk {
			clientFactory.client = client
			return true
		} else {
			logger.Error("Failed to create actual FSouza Docker client from client factory configuration")
			return false
		}
	}
	return true
}
Esempio n. 7
0
func (operation *InfoOperation) Run(logger log.Log) bool {
	logger.Message("RUNNING INFO OPERATION")

	logger.Debug(log.VERBOSITY_DEBUG, "Run:Targets", operation.targets.TargetOrder())
	for _, targetID := range operation.targets.TargetOrder() {
		target, targetExists := operation.targets.Target(targetID)
		node, hasNode := target.Node()
		_, hasInstances := target.Instances()

		if !targetExists {
			// this is strange
			logger.Warning("Internal target error, was told to use a target that doesn't exist")
			continue
		}

		nodeLogger := logger.MakeChild(targetID)

		if hasNode {
			nodeLogger.Message(targetID + " Information")
			node.Client().NodeInfo(nodeLogger)
		} else {
			nodeLogger.Message("No node [" + node.MachineName() + "]")
		}
		if hasInstances {
			node.Instances().Client().InstancesInfo(nodeLogger)
		} else {
			nodeLogger.Message("|-- No instances [" + node.MachineName() + "]")
		}
	}

	return true
}
Esempio n. 8
0
func (operation *CreateOperation) Run(logger log.Log) bool {
	logger.Info("Running operation: create")
	logger.Debug(log.VERBOSITY_DEBUG, "Run:Targets", operation.targets.TargetOrder())

	for _, targetID := range operation.targets.TargetOrder() {
		target, targetExists := operation.targets.Target(targetID)
		if !targetExists {
			// this is strange
			logger.Warning("Internal target error, was told to use a target that doesn't exist")
			continue
		}

		node, hasNode := target.Node()
		instances, hasInstances := target.Instances()
		nodeLogger := logger.MakeChild(targetID)

		if !hasNode {
			nodeLogger.Warning("No node [" + node.MachineName() + "]")
		} else if !node.Can("create") {
			nodeLogger.Info("Node doesn't create [" + node.MachineName() + ":" + node.Type() + "]")
		} else if !hasInstances {
			nodeLogger.Info("No valid instances specified in target list [" + node.MachineName() + "]")
		} else {
			nodeLogger.Message("Creating instance containers")
			for _, id := range instances.InstancesOrder() {
				instance, _ := instances.Instance(id)
				instance.Client().Create(logger, []string{}, operation.force)
			}
		}
	}

	return true
}
Esempio n. 9
0
// Run all of the prepared operations
func (operations *Operations) Run(logger log.Log) {
	if len(operations.operationsList) == 0 {
		logger.Error("No operation created")
	} else {
		for _, operation := range operations.operationsList {
			operation.Run(logger.MakeChild(operation.Id()))
		}
	}
}
Esempio n. 10
0
func (operation *ScaleOperation) Run(logger log.Log) bool {
	logger.Info("Running operation: scale")
	logger.Debug(log.VERBOSITY_DEBUG, "Run:Targets", operation.targets.TargetOrder())

	if operation.scale == 0 {
		operation.log.Warning("scale operation was told to scale to 0")
		return false
	}

	for _, targetID := range operation.targets.TargetOrder() {
		target, targetExists := operation.targets.Target(targetID)
		if !targetExists {
			// this is strange
			logger.Warning("Internal target error, was told to use a target that doesn't exist")
			continue
		}

		node, hasNode := target.Node()
		nodeLogger := logger.MakeChild(targetID)

		if !hasNode {
			nodeLogger.Info("No node [" + node.MachineName() + "]")
		} else if !node.Can("scale") {
			nodeLogger.Info("Node doesn't Scale [" + node.MachineName() + "]")
		} else {
			nodeLogger.Message("Scaling node " + node.Id())

			if operation.scale > 0 {
				count := operation.ScaleUpNumber(nodeLogger, node.Instances(), operation.scale)

				if count == 0 {
					nodeLogger.Warning("Scale operation could not scale up any new instances of node")
				} else if count < operation.scale {
					nodeLogger.Warning("Scale operation could not scale up all of the requested instances of node. " + strconv.FormatInt(int64(count+1), 10) + " started.")
				} else {
					nodeLogger.Message("Scale operation scaled up " + strconv.FormatInt(int64(count), 10) + " instances")
				}

			} else {
				count := operation.ScaleDownNumber(nodeLogger, node.Instances(), -operation.scale)

				if count == 0 {
					nodeLogger.Warning("Scale operation could not scale down any new instances of node")
				} else if count < (-operation.scale) {
					nodeLogger.Warning("Scale operation could not scale down all of the requested instances of node. " + strconv.FormatInt(int64(count+1), 10) + " stopped.")
				} else {
					nodeLogger.Message("Scale operation scaled down " + strconv.FormatInt(int64(count), 10) + " instances")
				}
			}

		}
	}
	return true
}
Esempio n. 11
0
// Try to configure a project by parsing yaml from a conf file
func (nodes *Nodes) from_NodesYamlFilePath(logger log.Log, project *conf.Project, clientFactories *ClientFactories, yamlFilePath string, overwrite bool) bool {
	// read the config file
	yamlFile, err := ioutil.ReadFile(yamlFilePath)
	if err != nil {
		logger.Debug(log.VERBOSITY_DEBUG_LOTS, "Could not read a YAML file: "+err.Error())
		return false
	}

	if !nodes.from_NodesYamlBytes(logger.MakeChild(yamlFilePath), project, clientFactories, yamlFile, overwrite) {
		logger.Warning("YAML marshalling of the YAML nodes file failed [" + yamlFilePath + "]: " + err.Error())
		return false
	}
	return true
}
Esempio n. 12
0
// Post initialization preparation
func (node *BaseNode) Prepare(logger log.Log, nodes *Nodes) (success bool) {
	logger.Debug(log.VERBOSITY_DEBUG_WOAH, "Prepare: Base Node")
	success = true

	node.log = logger

	logger.Debug(log.VERBOSITY_DEBUG_WOAH, "Preparing Client", nil)
	success = success && node.client.Prepare(logger.MakeChild("client"), nodes, node)

	logger.Debug(log.VERBOSITY_DEBUG_WOAH, "Preparing Instances", nil)
	success = success && node.instances.Prepare(logger.MakeChild("instances"), node.client, nodes, node)

	return success
}
Esempio n. 13
0
// Try to configure a project by parsing yaml from a conf file
func (project *Project) from_ConfYamlFilePath(logger log.Log, yamlFilePath string) bool {
	// read the config file
	yamlFile, err := ioutil.ReadFile(yamlFilePath)
	if err != nil {
		logger.Debug(log.VERBOSITY_DEBUG_LOTS, "Could not read a YAML file: "+err.Error())
		return false
	}

	if !project.from_ConfYamlBytes(logger.MakeChild(yamlFilePath), yamlFile) {
		logger.Warning("YAML marshalling of the YAML conf file failed [" + yamlFilePath + "]: " + err.Error())
		return false
	}
	return true
}
Esempio n. 14
0
func (operation *PauseOperation) Run(logger log.Log) bool {
	logger.Info("Running operation: pause")
	logger.Debug(log.VERBOSITY_DEBUG, "Run:Targets", operation.targets.TargetOrder())

	for _, targetID := range operation.targets.TargetOrder() {
		target, targetExists := operation.targets.Target(targetID)
		if !targetExists {
			// this is strange
			logger.Warning("Internal target error, was told to use a target that doesn't exist")
			continue
		}

		node, hasNode := target.Node()
		instances, hasInstances := target.Instances()

		nodeLogger := logger.MakeChild(targetID)

		if !hasNode {
			nodeLogger.Warning("No node [" + node.MachineName() + "]")
		} else if !node.Can("pause") {
			nodeLogger.Info("Node doesn't Pause [" + node.MachineName() + ":" + node.Type() + "]")
		} else if !hasInstances {
			nodeLogger.Info("No valid instances specified in target list [" + node.MachineName() + "]")
		} else {
			nodeLogger.Message("Pausing instances")

			if !instances.IsFiltered() {
				nodeLogger.Info("Switching to using all instances")
				instances.UseAll()
			}

			for _, id := range instances.InstancesOrder() {
				instance, _ := instances.Instance(id)

				if !instance.IsRunning() {
					if !instance.IsReady() {
						nodeLogger.Info("Instance will not be paused as it is not ready :" + id)
					} else {
						nodeLogger.Info("Instance will not be paused as it is not running :" + id)
					}
				} else {
					instance.Client().Pause(logger)
				}
			}
		}
	}

	return true
}
Esempio n. 15
0
func (instances *FixedInstances) Prepare(logger log.Log, client Client, nodes *Nodes, node Node) bool {
	logger.Debug(log.VERBOSITY_DEBUG_WOAH, "Prepare: Fixed Instances")

	for _, name := range instances.settings.Names {
		machineName := instances.MachineName() + "_" + name

		instance := Instance(&FixedInstance{})
		if instance.Init(logger.MakeChild(name), name, machineName, client, true) {
			instances.instancesMap[name] = instance
			instances.instancesOrder = append(instances.instancesOrder, name)
		}
	}

	return true
}
Esempio n. 16
0
func (instances *ScaledInstances) Prepare(logger log.Log, client Client, nodes *Nodes, node Node) bool {
	instances.log = logger
	logger.Debug(log.VERBOSITY_DEBUG_WOAH, "Prepare: Scaled Instances")

	for i := 0; i <= instances.settings.Maximum; i++ {
		name := strconv.Itoa(int(i))
		machineName := instances.MakeId(i)
		isDefault := (i <= instances.settings.Initial)

		instance := Instance(&ScaledInstance{})
		if instance.Init(logger.MakeChild(name), name, machineName, client, isDefault) {
			instances.instancesMap[name] = instance
			instances.instancesOrder = append(instances.instancesOrder, name)
		}
	}

	return true
}
Esempio n. 17
0
// Generate a factory set from a project
func MakeClientFactories(logger log.Log, project *conf.Project) *ClientFactories {
	factories := &ClientFactories{
		log: logger,
		orderedClientFactories: []ClientFactory{},
	}

	/**
	 * Build Factories from YAML if possible
	 */
	factories.from_ClientFactoriesYaml(logger.MakeChild("fromyaml"), project)

	/**
	 * If no factory is set up then assume that we
	 * should use the docker fsouza library with a
	 * local docker implementation
	 */
	if !factories.HasFactories() {
		logger.Debug(log.VERBOSITY_DEBUG, "No defined clients, retreiving default client")
		factories.from_Default(logger.MakeChild("default"), project)
	}

	return factories
}
Esempio n. 18
0
func (operation *RunOperation) Run(logger log.Log) bool {
	logger.Info("Running operation: run")
	logger.Debug(log.VERBOSITY_DEBUG, "Run:Targets", operation.targets.TargetOrder())

	for _, targetID := range operation.targets.TargetOrder() {
		target, targetExists := operation.targets.Target(targetID)
		if !targetExists {
			// this is strange
			logger.Warning("Internal target error, was told to use a target that doesn't exist")
			continue
		}

		node, hasNode := target.Node()
		instances, _ := target.Instances()
		nodeLogger := logger.MakeChild(targetID)

		if !hasNode {
			nodeLogger.Info("No node [" + node.MachineName() + "]")
		} else if !node.Can("run") {
			nodeLogger.Info("Node doesn't Run [" + node.MachineName() + "]")
		} else {

			instanceIds := instances.InstancesOrder()
			if len(instanceIds) == 0 {
				instanceIds = []string{""}
			}

			for _, id := range instanceIds {
				if instance, ok := instances.Instance(id); ok {
					instance.Client().Run(logger, false, operation.cmd)
				}
			}
		}
	}

	return true
}
Esempio n. 19
0
// MakeCoachProject Project constructor for building a project based on a project path
func MakeCoachProject(logger log.Log, workingDir string, environment string) (project *Project) {
	project = &Project{
		Environment: environment,        // base on the default environment
		Paths:       MakePaths(),        // empty typesafe paths object
		Tokens:      MakeTokens(),       // empty tokens object
		Flags:       MakeProjectFlags(), // empty flags object
	}

	/**
	 * 1. try to get some base default configuration, seeing if there is a
	 *    project .coach folder above the workingdir (or in it) or maybe
	 *		there's a user's ~/.coach
	 */
	project.from_DefaultPaths(logger.MakeChild("defaults"), workingDir)

	// set the two project paths, to be the most important
	project.setConfPath("project-coach")
	// set the user conf paths, to be the least important
	project.setConfPath("user-coach")

	/**
	 * 2. Look for YAML configurations in the Configuration Paths
	 */
	project.from_ConfYaml(logger.MakeChild("confyaml"))

	/**
	 * 3. Try to load secrets from configuration paths
	 */
	project.from_EnvironmentsPath(logger.MakeChild("environment"))

	/**
	 * 4. Try to load secrets from configuration paths
	 */
	project.from_SecretsYaml(logger.MakeChild("secrets"))

	/**
	 * 5. Run the project prepare, which will validate the configuration
	 */
	if !project.Prepare(logger) {
		logger.Warning("Coach configuration processing failed")
	}

	return project
}
Esempio n. 20
0
// Try to configure factories by parsing yaml from a byte stream
func (nodes *Nodes) from_NodesYamlBytes(logger log.Log, project *conf.Project, clientFactories *ClientFactories, yamlBytes []byte, overwrite bool) bool {
	if project != nil {
		// token replace
		tokens := &project.Tokens
		yamlBytes = []byte(tokens.TokenReplace(string(yamlBytes)))
	}

	var nodes_yaml map[string]node_yaml_v2
	err := yaml.Unmarshal(yamlBytes, &nodes_yaml)
	if err != nil {
		logger.Warning("YAML parsing error : " + err.Error())
		return false
	}
	logger.Debug(log.VERBOSITY_DEBUG_STAAAP, "YAML source:", nodes_yaml)

NodesListLoop:
	for name, node_yaml := range nodes_yaml {

		_, exists := nodes.Node(name)

		logger.Debug(log.VERBOSITY_DEBUG_LOTS, "Yaml Node:", name, exists, node_yaml)
		nodeLogger := logger.MakeChild(name)

		// nodes can be marked as disabled (to keep settings, but not use them)
		if node_yaml.Disabled {
			if exists && overwrite {
				nodeLogger.Info("new YAML node key [" + name + "] is marked as disabled but the key already exists. Disabling the previously defined node")
				nodes.DisableNode(name)
			} else if exists {
				nodeLogger.Warning("new YAML node key [" + name + "] is marked as disabled, but the key already exists. Keeping original node as defined.")
			} else {
				nodeLogger.Info("new YAML node key [" + name + "] is marked as disabled")
			}
			continue NodesListLoop
		}
		if exists && !overwrite {
			nodeLogger.Warning("new YAML node key [" + name + "] already exists")
			continue NodesListLoop
		}

		var node Node

		// Start off assuming a default type
		nodeType := NODES_YAML_DEFAULTNODETYPE
		// if the node conf has a type, then use it
		if explicitType, ok := node_yaml.Type(); ok {
			nodeType = explicitType
		}

		switch strings.ToLower(strings.TrimSpace(nodeType)) {
		case "command":
			node = Node(&CommandNode{})
		case "build":
			node = Node(&BuildNode{})
		case "volume":
			node = Node(&VolumeNode{})
		case "pull":
			node = Node(&PullNode{})
		case "service":
			node = Node(&ServiceNode{})
		default:
			nodeLogger.Warning("YAML node is an unknown type: " + nodeType)
			continue NodesListLoop
		}

		if node != nil {
			var client Client
			var instancesSettings InstancesSettings

			var ok bool

			if client, ok = node_yaml.GetClient(nodeLogger, clientFactories); !ok {
				nodeLogger.Error("Invalid Client configuration in node ")
			}
			if instancesSettings, ok = node_yaml.GetInstancesSettings(nodeLogger); !ok {
				nodeLogger.Error("Invalid Instances configuration in node")
			}

			nodeLogger.Debug(log.VERBOSITY_DEBUG_STAAAP, "Building node from components:", client, instancesSettings)

			// run the node initializaer with the collected obkjects
			if node.Init(nodeLogger, name, project, client, instancesSettings) {
				// add any manual dependencies specified
				for _, dependency := range node_yaml.Requires {
					node.AddDependency(dependency)
				}

				nodeLogger.Debug(log.VERBOSITY_DEBUG_LOTS, "Adding node to nodes list:", name, node)
				nodes.SetNode(name, node, true)
			}
		}

	}

	return true
}
Esempio n. 21
0
func MakeOperation(logger log.Log, project *conf.Project, name string, flags []string, targets *libs.Targets) *Operations {
	operations := Operations{}
	operations.Init(logger, OperationsSettings{}, targets)

	opLogger := logger.MakeChild(name)

	var operation Operation
	switch name {
	case "info":
		operation = Operation(&InfoOperation{log: opLogger, targets: targets})
	case "status":
		operation = Operation(&StatusOperation{log: opLogger, targets: targets})

	case "pull":
		operation = Operation(&PullOperation{log: opLogger, targets: targets})
	case "build":
		operation = Operation(&BuildOperation{log: opLogger, targets: targets})
	case "destroy":
		operation = Operation(&DestroyOperation{log: opLogger, targets: targets})

	case "create":
		operation = Operation(&CreateOperation{log: opLogger, targets: targets})
	case "remove":
		operation = Operation(&RemoveOperation{log: opLogger, targets: targets})
	case "start":
		operation = Operation(&StartOperation{log: opLogger, targets: targets})
	case "stop":
		operation = Operation(&StopOperation{log: opLogger, targets: targets})
	case "restart":
		operation = Operation(&RestartOperation{log: opLogger, targets: targets})
	case "scale":
		operation = Operation(&ScaleOperation{log: opLogger, targets: targets})
	case "pause":
		operation = Operation(&PauseOperation{log: opLogger, targets: targets})
	case "unpause":
		operation = Operation(&UnpauseOperation{log: opLogger, targets: targets})

	case "commit":
		operation = Operation(&CommitOperation{log: opLogger, targets: targets})

	case "up":
		operation = Operation(&UpOperation{log: opLogger, targets: targets})
	case "clean":
		operation = Operation(&CleanOperation{log: opLogger, targets: targets})

	case "run":
		operation = Operation(&RunOperation{log: opLogger, targets: targets})

	case "help":
		operation = Operation(&HelpOperation{log: opLogger, conf: project})

	case "init":
		operation = Operation(&InitOperation{log: opLogger, conf: project})
	case "init-generate":
		operation = Operation(&InitGenerateOperation{log: opLogger, conf: project})

	case "tool":
		operation = Operation(&ToolOperation{log: opLogger, conf: project})

	default:
		operation = Operation(&UnknownOperation{id: name})
	}
	operation.Flags(flags)

	operations.AddOperation(operation)

	return &operations
}
Esempio n. 22
0
func (operation *InitOperation) Run(logger log.Log) bool {
	logger.Info("running init operation")

	var err error
	var ok bool
	var targetPath, coachPath string

	targetPath = operation.root
	if targetPath == "" {
		targetPath, ok = operation.conf.Path("project-root")
		if !ok || targetPath == "" {
			targetPath, err = os.Getwd()
			if err != nil {
				logger.Error("No path suggested for new project init")
				return false
			}
		}
	}

	_, err = os.Stat(targetPath)
	if err != nil {
		logger.Error("Invalid path suggested for new project init : [" + targetPath + "] => " + err.Error())
		return false
	}

	coachPath, _ = operation.conf.Paths.Path("coach-root")

	logger.Message("Preparing INIT operation [" + operation.handler + ":" + operation.source + "] in path : " + targetPath)

	_, err = os.Stat(coachPath)
	if !operation.force && err == nil {
		logger.Error("cannot create new project folder, as one already exists")
		return false
	}

	logger = logger.MakeChild(strings.ToUpper(operation.handler))
	tasks := initialize.InitTasks{}
	tasks.Init(logger.MakeChild("TASKS"), operation.conf, targetPath)

	ok = true
	switch operation.handler {
	case "user":
		ok = tasks.Init_User_Run(logger, operation.source)
	case "demo":
		ok = tasks.Init_Demo_Run(logger, operation.source)
	case "git":
		ok = tasks.Init_Git_Run(logger, operation.source)
	case "yaml":
		ok = tasks.Init_Yaml_Run(logger, operation.source)
	case "default":
		ok = tasks.Init_Default_Run(logger, operation.source)
	default:

		logger.Error("Unknown init handler " + operation.handler)
		ok = false

	}

	if ok {
		logger.Info("Running init tasks")
		tasks.RunTasks(logger)
		return true
	} else {
		logger.Warning("No init tasks were defined.")
		return false
	}

}
Esempio n. 23
0
func (client *FSouza_InstanceClient) Run(logger log.Log, persistant bool, cmd []string) bool {
	hushedLogger := logger.MakeChild("RunSupport")
	hushedLogger.Hush()

	instance := client.instance

	// Set up some additional settings for TTY commands
	if client.settings.Config.Tty == true {

		// set a default hostname to make a prettier prompt
		if client.settings.Config.Hostname == "" {
			client.settings.Config.Hostname = instance.Id()
		}

		// make sure that all tty runs have openstdin
		client.settings.Config.OpenStdin = true
	}

	client.settings.Config.AttachStdin = true
	client.settings.Config.AttachStdout = true
	client.settings.Config.AttachStderr = true

	// 1. get the container for the instance (create it if needed)
	hasContainer := client.HasContainer()
	if !hasContainer {
		logger.Info("Creating new disposable RUN container")

		if hasContainer = client.Create(hushedLogger, cmd, false); hasContainer {
			logger.Debug(log.VERBOSITY_DEBUG, "Created disposable run container")
			if !persistant {
				// 5. [DEFERED] remove the container (if not instructed to keep it)
				defer func(client *FSouza_InstanceClient, hushedLogger log.Log) {
					client.backend.Refresh(false, true)
					if client.IsRunning() {
						client.Stop(hushedLogger, true, 0)
					}
					client.Remove(hushedLogger, true)
				}(client, hushedLogger)
			}
		} else {
			logger.Error("Failed to create disposable run container")
		}
	} else {
		logger.Info("Run container already exists")
	}

	if hasContainer {

		// 3. start the container (set up a remove)
		logger.Info("Starting RUN container")
		ok := client.Start(hushedLogger, false)

		// 4. attach to the container
		if ok {
			logger.Info("Attaching to disposable RUN container")
			client.Attach(logger)
			return true
		} else {
			logger.Error("Could not start RUN container")
			return false
		}

	} else {
		logger.Error("Could not create RUN container")
	}
	return false
}
Esempio n. 24
0
func (operation *UpOperation) Run(logger log.Log) bool {
	logger.Info("Running operation: up")
	logger.Debug(log.VERBOSITY_DEBUG, "Run:Targets", operation.targets.TargetOrder())

	for _, targetID := range operation.targets.TargetOrder() {
		target, targetExists := operation.targets.Target(targetID)
		if !targetExists {
			// this is strange
			logger.Warning("Internal target error, was told to use a target that doesn't exist")
			continue
		}

		node, hasNode := target.Node()
		instances, hasInstances := target.Instances()
		nodeLogger := logger.MakeChild(targetID)

		build := node.Can("build")
		pull := node.Can("pull")
		create := node.Can("create")
		start := node.Can("start")

		if !hasNode {
			nodeLogger.Info("No node [" + node.MachineName() + "]")
		} else if !node.Can("Up") {
			nodeLogger.Info("Node doesn't Up [" + node.MachineName() + "]")
		} else {
			nodeLogger.Message("Bringing node up")

			nodeClient := node.Client()
			if build {
				if operation.force || !nodeClient.HasImage() {
					nodeLogger.Message("Building node image")
					nodeClient.Build(nodeLogger, operation.force)
				} else {
					nodeLogger.Info("Node already has an image built")
				}
			}
			if pull {
				if operation.force || !nodeClient.HasImage() {
					nodeLogger.Message("Pulling node image")
					nodeClient.Pull(nodeLogger, operation.force)
				} else {
					nodeLogger.Info("Node already has an image pulled")
				}
			}

			if hasInstances && (create || start) {
				for _, id := range instances.InstancesOrder() {
					instance, _ := instances.Instance(id)
					instanceClient := instance.Client()

					if create {
						if operation.force || !instanceClient.HasContainer() {
							nodeLogger.Message("Creating node instance container : " + id)
							instanceClient.Create(nodeLogger, []string{}, operation.force)
						} else {
							nodeLogger.Info("Instance already has an container created : " + id)
						}
					}
					if start {
						if operation.force || !instanceClient.IsRunning() {
							nodeLogger.Message("Starting node instance container : " + id)
							instanceClient.Start(nodeLogger, operation.force)
						} else {
							nodeLogger.Info("Instance already has an container running : " + id)
						}
					}
				}
			}
		}
	}

	return true
}
Esempio n. 25
0
func (operation *CleanOperation) Run(logger log.Log) bool {
	logger.Info("Running operation: clean")
	logger.Debug(log.VERBOSITY_DEBUG, "Run:Targets", operation.targets.TargetOrder())

	for _, targetID := range operation.targets.TargetOrder() {
		target, targetExists := operation.targets.Target(targetID)
		if !targetExists {
			// this is strange
			logger.Warning("Internal target error, was told to use a target that doesn't exist")
			continue
		}

		node, hasNode := target.Node()
		instances, hasInstances := target.Instances()
		nodeLogger := logger.MakeChild(targetID)

		if !hasNode {
			nodeLogger.Info("No node [" + node.MachineName() + "]")
		} else if !node.Can("clean") {
			nodeLogger.Info("Node doesn't Clean [" + node.MachineName() + "]")
		} else {
			nodeLogger.Message("Cleaning node [" + node.Id() + "]")

			if hasInstances {
				if !(operation.defaultOnly || instances.IsFiltered()) {
					nodeLogger.Info("Switching to using all instances")
					instances.UseAll()
				}

				instanceIds := instances.InstancesOrder()
				if len(instanceIds) > 0 {
					for _, id := range instanceIds {
						instance, _ := instances.Instance(id)
						instanceClient := instance.Client()

						if instanceClient.HasContainer() {
							if instanceClient.IsRunning() {
								instanceClient.Stop(logger, operation.force, operation.timeout)
							}
							instanceClient.Remove(logger, operation.force)
							nodeLogger.Message("Cleaning node instance [" + id + "]")
						} else {
							nodeLogger.Info("Node instance has no container to clean [" + id + "]")
						}
					}
				} else {
					nodeLogger.Info("Node has no instances to clean")
				}
			}

			if operation.wipe && node.Can("build") {
				nodeClient := node.Client()
				nodeClient.Destroy(nodeLogger, operation.force)
				nodeLogger.Message("Node build cleaned")
			} else {
				nodeLogger.Message("Node was not built, so will not be removed")
			}

		}
	}

	return true
}