// Fix command removes duplicates and conflicts from the hosts file
493427
func Fix(c *cli.Context) {
	hostsfile := AlwaysLoadHostFile(c)
	if bytes.Equal(hostsfile.GetData(), hostsfile.Format()) {
		MaybePrintln(c, fmt.Sprintf("%s is already formatted and contains no dupes or conflicts; nothing to do", GetHostsPath()))
		os.Exit(0)
	}
	MaybeSaveHostFile(c, hostsfile)
}
413629
func (c *ServicedCli) cmdHostAdd(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 2 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "add")
		return
	}

	var address utils.URL
	if err := address.Set(args[0]); err != nil {
		fmt.Println(err)
		return
	}
	if ip := net.ParseIP(address.Host); ip == nil {
		// Host did not parse, try resolving
		addr, err := net.ResolveTCPAddr("tcp", args[0])
		if err != nil {
			fmt.Printf("Could not resolve %s.\n\n", args[0])
			return
		}
		address.Host = addr.IP.String()
		if strings.HasPrefix(address.Host, "127.") {
			fmt.Printf("%s must not resolve to a loopback address\n\n", args[0])
			return
		}
	}

	// Parse/resolve the NAT address, if provided.
	var nat utils.URL
	natString := ctx.String("nat-address")
	if len(natString) > 0 {
		if err := nat.Set(natString); err != nil {
			fmt.Println(err)
			return
		}
		if natip := net.ParseIP(nat.Host); natip == nil {
			// NAT did not parse, try resolving
			addr, err := net.ResolveTCPAddr("tcp", natString)
			if err != nil {
				fmt.Printf("Could not resolve nat address (%s): %s\n", natString, err)
				return
			}
			nat.Host = addr.IP.String()
		}
		if strings.HasPrefix(nat.Host, "127.") {
			fmt.Printf("The nat address %s must not resolve to a loopback address\n", natString)
			return
		}
	}

	cfg := api.HostConfig{
		Address: &address,
		Nat:     &nat,
		PoolID:  args[1],
		Memory:  ctx.String("memory"),
	}

	host, privateKey, err := c.driver.AddHost(cfg)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	} else if host == nil {
		fmt.Fprintln(os.Stderr, "received nil host")
		return
	}

	keyfileName := ctx.String("key-file")
	registerHost := ctx.Bool("register")
	c.outputDelegateKey(host, nat, privateKey, keyfileName, registerHost)
}
743982
func Apply(c *cli.Context) {
	if len(c.Args()) != 1 {
		MaybeError(c, "Usage should be apply [filename]")
	}
	filename := c.Args()[0]

	jsonbytes, err := ioutil.ReadFile(filename)
	if err != nil {
		MaybeError(c, fmt.Sprintf("Unable to read %s: %s", filename, err))
	}

	hostfile := AlwaysLoadHostFile(c)
	err = hostfile.Hosts.Apply(jsonbytes)
	if err != nil {
		MaybeError(c, fmt.Sprintf("Error applying changes to hosts file: %s", err))
	}

	MaybeSaveHostFile(c, hostfile)
	MaybePrintln(c, fmt.Sprintf("%s applied", filename))
}
1106090
func (p *Pipelined) Command(args ...interface{}) error {
	err := p.conn.SendCommand(args...)
	if err == nil {
		p.times++
	}
	return err
}
1120290
func (info *Info) Command() string {
	terms := []string{info.ContainerEntrypoint}
	terms = append(terms, info.ContainerArgs...)
	command := strings.Join(terms, " ")
	return command
}
349317
func Patch(cmd *cli.Cmd) {
	uuid := cmd.String(cli.StringArg{
		Name:      "UUID",
		Desc:      "Application UUID",
		HideValue: true,
	})

	image := cmd.String(cli.StringOpt{
		Name:      "image_url",
		Desc:      "Image URL",
		HideValue: true,
	})

	name := cmd.String(cli.StringOpt{
		Name:      "name",
		Desc:      "Application Name",
		HideValue: true,
	})

	envFile := cmd.String(cli.StringOpt{
		Name:      "env_file",
		Desc:      "Environment variables file",
		HideValue: true,
	})

	enVars := cmd.Strings(cli.StringsOpt{
		Name:      "e env",
		Desc:      "Environment variable (i.e. MYSQL_PASSWORD=complexpassword",
		HideValue: true,
	})

	rules := cmd.Strings(cli.StringsOpt{
		Name:      "r rule",
		Desc:      "Application Deployment rules",
		HideValue: true,
	})

	labels := cmd.Strings(cli.StringsOpt{
		Name:      "l label",
		Desc:      "Label associated with the aplication",
		HideValue: true,
	})

	meta := cmd.String(cli.StringOpt{
		Name:      "m metadata",
		Desc:      "Metadata associated with the application being created. Must be JSON formatted.",
		HideValue: true,
	})

	cmd.Action = func() {
		originalApp := &application.Application{
			UUID: *uuid,
		}

		originalApp, _, errs := originalApp.Show()

		if len(errs) != 0 {
			log.Fatalf("Unable to retrieve application: %s", errs)
		}

		patchedApp := *originalApp

		if *envFile != "" || len(*enVars) > 0 {
			patchedApp.Environment = transformEnvironment(envFile, enVars)
		} else if *image != "" {
			patchedApp.ImageURL = *image
		} else if *meta != "" || len(*labels) > 0 {
			patchedApp.Metadata = metaData(*meta, *labels)
		} else if *name != "" {
			patchedApp.Name = *name
		} else if len(*rules) > 0 {
			patchedApp.Rules = transformRules(rules)
		}

		pApp, resp, errs := originalApp.Patch(&patchedApp)

		if len(errs) > 0 {
			log.Fatalf("Could not patch application: %s", errs[0])
		}

		if resp.StatusCode != 200 {
			log.Fatalf("Could not patch application: %s", resp.Status)
		}

		printAppDetail(pApp)
	}
}
286910
func (g *Git) Apply(patch string) *command.Model {
	return g.command("apply", "--index", patch)
}
519916
func stringsReplace(args string, fileContent contentMessage) string {
	// replace all instances of {}
	str := args
	if strings.Contains(str, "{}") {
		str = strings.Replace(str, "{}", fileContent.Key, -1)
	}

	// replace all instances of {""}
	if strings.Contains(str, `{""}`) {
		str = strings.Replace(str, `{""}`, strconv.Quote(fileContent.Key), -1)
	}

	// replace all instances of {base}
	if strings.Contains(str, "{base}") {
		str = strings.Replace(str, "{base}", filepath.Base(fileContent.Key), -1)
	}

	// replace all instances of {"base"}
	if strings.Contains(str, `{"base"}`) {
		str = strings.Replace(str, `{"base"}`, strconv.Quote(filepath.Base(fileContent.Key)), -1)
	}

	// replace all instances of {dir}
	if strings.Contains(str, "{dir}") {
		str = strings.Replace(str, "{dir}", filepath.Dir(fileContent.Key), -1)
	}

	// replace all instances of {"dir"}
	if strings.Contains(str, `{"dir"}`) {
		str = strings.Replace(str, `{"dir"}`, strconv.Quote(filepath.Dir(fileContent.Key)), -1)
	}

	// replace all instances of {size}
	if strings.Contains(str, "{size}") {
		str = strings.Replace(str, "{size}", humanize.IBytes(uint64(fileContent.Size)), -1)
	}

	// replace all instances of {"size"}
	if strings.Contains(str, `{"size"}`) {
		str = strings.Replace(str, `{"size"}`, strconv.Quote(humanize.IBytes(uint64(fileContent.Size))), -1)
	}

	// replace all instances of {time}
	if strings.Contains(str, "{time}") {
		str = strings.Replace(str, "{time}", fileContent.Time.Format(printDate), -1)
	}

	// replace all instances of {"time"}
	if strings.Contains(str, `{"time"}`) {
		str = strings.Replace(str, `{"time"}`, strconv.Quote(fileContent.Time.Format(printDate)), -1)
	}

	// replace all instances of {url}
	if strings.Contains(str, "{url}") {
		str = strings.Replace(str, "{url}", getShareURL(fileContent.Key), -1)
	}

	// replace all instances of {"url"}
	if strings.Contains(str, `{"url"}`) {
		str = strings.Replace(str, `{"url"}`, strconv.Quote(getShareURL(fileContent.Key)), -1)
	}

	return str
}
244677
func (e *Echo) Patch(path string, h interface{}, m ...interface{}) {
	e.add(PATCH, "", path, h, m...)
}
717632
func fixURL(u *url.URL) *url.URL {
	if u.Scheme == "" {
		s := strings.Split(u.String(), "/")
		u.Scheme = "http"
		u.Host = s[0]
		u.Path = u.Path[len(s[0]):]
	}
	return u
}
980933
func (h *Hostfile) Save() error {
	file, err := os.OpenFile(h.Path, os.O_RDWR|os.O_APPEND|os.O_TRUNC, 0644)
	if err != nil {
		return err
	}

	defer file.Close()
	_, err = file.Write(h.Format())

	return err
}
998026
func (c Configuration) Resolve() (string, error) {
	listenAddrType := c.ListenAddressType

	var listenAddress string
	switch listenAddrType {
	case ConfigResolver:
		if c.Value == nil {
			err := fmt.Errorf("missing listen address value using: resolver=%s",
				string(listenAddrType))
			return "", err
		}
		listenAddress = *c.Value

	case EnvironmentResolver:
		// environment variable for port is required
		if c.EnvVarListenPort == nil {
			err := fmt.Errorf("missing port env var name using: resolver=%s",
				string(listenAddrType))
			return "", err
		}
		portStr := os.Getenv(*c.EnvVarListenPort)
		port, err := strconv.Atoi(portStr)
		if err != nil {
			err := fmt.Errorf("invalid port env var value using: resolver=%s, name=%s",
				string(listenAddrType), *c.EnvVarListenPort)
			return "", err
		}
		// if environment variable for hostname is not set, use the default
		if c.EnvVarListenHost == nil {
			listenAddress = fmt.Sprintf("%s:%d", defaultHostname, port)
		} else {
			envHost := os.Getenv(*c.EnvVarListenHost)
			listenAddress = fmt.Sprintf("%s:%d", envHost, port)
		}

	default:
		return "", fmt.Errorf("unknown listen address type: resolver=%s",
			string(listenAddrType))
	}

	return listenAddress, nil
}
821802
func resolveGoModFile(dir string) (*os.File, string, error) {
	goModPath := filepath.Join(dir, "go.mod")
	f, err := os.Open(goModPath)
	if err != nil {
		if os.IsNotExist(err) && dir != filepath.Dir(dir) {
			return resolveGoModFile(filepath.Dir(dir))
		}
		return nil, "", err
	}
	return f, dir, nil
}
237809
func FixShardReplication(ctx context.Context, ts *Server, logger logutil.Logger, cell, keyspace, shard string) error {
	sri, err := ts.GetShardReplication(ctx, cell, keyspace, shard)
	if err != nil {
		return err
	}

	for _, node := range sri.Nodes {
		ti, err := ts.GetTablet(ctx, node.TabletAlias)
		if IsErrType(err, NoNode) {
			logger.Warningf("Tablet %v is in the replication graph, but does not exist, removing it", node.TabletAlias)
			return RemoveShardReplicationRecord(ctx, ts, cell, keyspace, shard, node.TabletAlias)
		}
		if err != nil {
			// unknown error, we probably don't want to continue
			return err
		}

		if ti.Keyspace != keyspace || ti.Shard != shard || ti.Alias.Cell != cell {
			logger.Warningf("Tablet '%v' is in the replication graph, but has wrong keyspace/shard/cell, removing it", ti.Tablet)
			return RemoveShardReplicationRecord(ctx, ts, cell, keyspace, shard, node.TabletAlias)
		}

		logger.Infof("Keeping tablet %v in the replication graph", node.TabletAlias)
	}

	logger.Infof("All entries in replication graph are valid")
	return nil
}
182078
func (res *Resource) Patch(storage store.Update) {
	res.HandleFuncC(
		pat.Patch(patID),
		func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			res.patchHandler(ctx, w, r, storage)
		},
	)

	res.addRoute(patch, patID)
}
1065313
func OnOff(c *cli.Context) {
	if len(c.Args()) != 1 {
		MaybeError(c, "expected <hostname>")
	}
	domain := c.Args()[0]
	hostsfile := MaybeLoadHostFile(c)

	// Switch on / off commands
	success := false
	if c.Command.Name == "on" {
		success = hostsfile.Hosts.Enable(domain)
	} else {
		success = hostsfile.Hosts.Disable(domain)
	}

	if success {
		MaybeSaveHostFile(c, hostsfile)
		if c.Command.Name == "on" {
			MaybePrintln(c, fmt.Sprintf("Enabled %s", domain))
		} else {
			MaybePrintln(c, fmt.Sprintf("Disabled %s", domain))
		}
	} else {
		MaybeError(c, fmt.Sprintf("%s not found in %s", domain, GetHostsPath()))
	}
}
989526
func deleteHostCmd(params *Parameters) *subcommands.Command {
	return &subcommands.Command{
		UsageLine: "del-host -name name",
		ShortDesc: "deletes a host",
		LongDesc:  "Deletes a physical or virtual host from the database.\n\nExample:\ncrimson del-host -name vm100-y1",
		CommandRun: func() subcommands.CommandRun {
			cmd := &DeleteHostCmd{}
			cmd.Initialize(params)
			cmd.Flags.StringVar(&cmd.req.Name, "name", "", "The name of the host to delete.")
			cmd.Flags.Int64Var(&cmd.req.Vlan, "vlan", 0, "The VLAN the host belongs to.")
			return cmd
		},
	}
}