// serviced restore FILEPATH
969769
func (c *ServicedCli) cmdRestore(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "restore")
		return
	}

	err := c.driver.Restore(args[0])
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
}
87998
func (td *TempDir) Restore() {
	err := os.RemoveAll(td.dir)
	if err != nil {
		msg := fmt.Sprintf("cannot remove temporary directory %q: %v", td.dir, err)
		td.assert.Fail(msg)
	}
}
954984
func (n *networkNamespace) Restore(ifsopt map[string][]IfaceOption, routes []*types.StaticRoute, gw net.IP, gw6 net.IP) error {
	// restore interfaces
	for name, opts := range ifsopt {
		if !strings.Contains(name, "+") {
			return fmt.Errorf("wrong iface name in restore osl sandbox interface: %s", name)
		}
		seps := strings.Split(name, "+")
		srcName := seps[0]
		dstPrefix := seps[1]
		i := &nwIface{srcName: srcName, dstName: dstPrefix, ns: n}
		i.processInterfaceOptions(opts...)
		if i.master != "" {
			i.dstMaster = n.findDst(i.master, true)
			if i.dstMaster == "" {
				return fmt.Errorf("could not find an appropriate master %q for %q",
					i.master, i.srcName)
			}
		}
		if n.isDefault {
			i.dstName = i.srcName
		} else {
			links, err := n.nlHandle.LinkList()
			if err != nil {
				return fmt.Errorf("failed to retrieve list of links in network namespace %q during restore", n.path)
			}
			// due to the docker network connect/disconnect, so the dstName should
			// restore from the namespace
			for _, link := range links {
				addrs, err := n.nlHandle.AddrList(link, netlink.FAMILY_V4)
				if err != nil {
					return err
				}
				ifaceName := link.Attrs().Name
				if strings.HasPrefix(ifaceName, "vxlan") {
					if i.dstName == "vxlan" {
						i.dstName = ifaceName
						break
					}
				}
				// find the interface name by ip
				if i.address != nil {
					for _, addr := range addrs {
						if addr.IPNet.String() == i.address.String() {
							i.dstName = ifaceName
							break
						}
						continue
					}
					if i.dstName == ifaceName {
						break
					}
				}
				// This is to find the interface name of the pair in overlay sandbox
				if strings.HasPrefix(ifaceName, "veth") {
					if i.master != "" && i.dstName == "veth" {
						i.dstName = ifaceName
					}
				}
			}

			var index int
			indexStr := strings.TrimPrefix(i.dstName, dstPrefix)
			if indexStr != "" {
				index, err = strconv.Atoi(indexStr)
				if err != nil {
					return err
				}
			}
			index++
			n.Lock()
			if index > n.nextIfIndex[dstPrefix] {
				n.nextIfIndex[dstPrefix] = index
			}
			n.iFaces = append(n.iFaces, i)
			n.Unlock()
		}
	}

	// restore routes
	for _, r := range routes {
		n.Lock()
		n.staticRoutes = append(n.staticRoutes, r)
		n.Unlock()
	}

	// restore gateway
	if len(gw) > 0 {
		n.Lock()
		n.gw = gw
		n.Unlock()
	}

	if len(gw6) > 0 {
		n.Lock()
		n.gwv6 = gw6
		n.Unlock()
	}

	return nil
}
428258
func (c *ServicedCli) cmdServiceAttach(ctx *cli.Context) error {
	// verify args
	args := ctx.Args()
	if len(args) < 1 {
		if !ctx.Bool("help") {
			fmt.Fprintf(os.Stderr, "Incorrect Usage.\n\n")
		}
		cli.ShowSubcommandHelp(ctx)
		c.exit(1)
		return nil
	}

	// Bash completion
	if args[len(args)-1] == "--generate-bash-completion" {
		// CC-892: The attach command does not require an additional argument after
		// SERVICE_ID. Disable bash completion after SERVICE_ID.
		return c.exit(1)
	}

	svc, instanceID, err := c.searchForService(ctx.Args().First(), ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return err
	}

	if instanceID < 0 {
		instanceID = 0
	}
	command := ""
	argv := []string{}
	if len(args) > 1 {
		command = args[1]
		argv = args[2:]
	}

	if err := c.driver.AttachServiceInstance(svc.ID, instanceID, command, argv); err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return err
	}
	return nil
}
494751
func (c *ServicedCli) cmdConfig(ctx *cli.Context) {
	configValues := c.config.GetConfigValues()

	// build a sorted list of keys
	keys := []string{}
	for key, _ := range(configValues) {
		keys = append(keys, key)
	}
	sort.Strings(keys)

	for _, key := range(keys) {
		entry, _ := configValues[key]
		fmt.Printf("%s=%s\n", entry.Name, entry.Value)
	}
}
770373
func (p *Process) Restore(r io.Reader) error {
	p.mtx.Lock()
	defer p.mtx.Unlock()

	logger := p.Logger.New("fn", "Restore")
	logger.Info("begin restore")

	// Stop if running.
	if p.running {
		logger.Info("stopping process")
		if err := p.stop(); err != nil {
			logger.Error("error stopping process", "err", err)
			return err
		}
	}

	// Create dump file in data directory.
	logger.Info("copying dump.rdb")
	if err := func() error {
		f, err := os.Create(filepath.Join(p.DataDir, "dump.rdb"))
		if err != nil {
			logger.Error("error creating dump file", "err", err)
			return err
		}
		defer f.Close()

		// Copy from reader to dump file.
		n, err := io.Copy(f, r)
		if err != nil {
			logger.Error("error creating dump file", "err", err)
			return err
		}
		logger.Info("copy completed", "n", n)

		return nil
	}(); err != nil {
		return err
	}

	// Restart process.
	if err := p.start(); err != nil {
		logger.Error("error restarting process", "err", err)
		return err
	}

	return nil
}
494792
func (c *ServicedCli) cmdScriptParse(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) != 1 {
		fmt.Fprintf(os.Stderr, "Incorrect Usage.\n\n")
		return
	}
	fileName := args[0]
	config := script.Config{}
	err := c.driver.ScriptParse(fileName, &config)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
	return
}
1106151
func (c *ServicedCli) Run(args []string) {
	if err := c.app.Run(args); err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
	}
}
1096261
func (c *ServicedCli) cmdServiceRestart(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "restart")
		c.exit(1)
		return
	}

	var sIds []string
	var instances []struct {
		Service  string
		Instance int
	}

	for _, arg := range args {
		svc, instanceID, err := c.searchForService(arg, ctx.Bool("no-prefix-match"))
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
			return
		}

		if instanceID < 0 {
			sIds = append(sIds, svc.ID)
		} else {
			instances = append(instances, struct {
				Service  string
				Instance int
			}{
				svc.ID,
				instanceID,
			})
		}
	}

	// Batch start services
	if len(sIds) > 0 {
		if ctx.Bool("rebalance") {
			if affected, err := c.driver.RebalanceService(api.SchedulerConfig{sIds, ctx.Bool("auto-launch"), ctx.Bool("sync")}); err != nil {
				fmt.Fprintln(os.Stderr, err)
				c.exit(1)
			} else {
				fmt.Printf("Restarting %d service(s)\n", affected)
			}
		} else {
			if affected, err := c.driver.RestartService(api.SchedulerConfig{sIds, ctx.Bool("auto-launch"), ctx.Bool("sync")}); err != nil {
				fmt.Fprintln(os.Stderr, err)
				c.exit(1)
			} else {
				fmt.Printf("Restarting %d service(s)\n", affected)
			}
		}
	}

	// Iterate and reschedule any instances specified
	for _, instance := range instances {
		if err := c.driver.StopServiceInstance(instance.Service, instance.Instance); err != nil {
			fmt.Fprintln(os.Stderr, err)
			c.exit(1)
		} else {
			fmt.Printf("Restarting instance %s/%d\n", instance.Service, instance.Instance)
		}
	}
	return
}
1325738
func (c *ServicedCli) cmdAddVirtualIP(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) != 4 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "add-virtual-ip")
		return
	}

	requestVirtualIP := pool.VirtualIP{PoolID: args[0], IP: args[1], Netmask: args[2], BindInterface: args[3]}
	if err := c.driver.AddVirtualIP(requestVirtualIP); err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}

	fmt.Println("Added virtual IP:", args[1])
}
1084234
func (fsm *SimpleFSM) Restore(rc io.ReadCloser) error {
	defer rc.Close()
	var logs [][]byte
	if err := gob.NewDecoder(rc).Decode(&logs); err != nil {
		return err
	}
	fsm.mu.Lock()
	fsm.logs = logs
	fsm.mu.Unlock()
	return nil
}
1189927
func BuildFromPath(path string) (*ServiceDefinition, error) {
	sd, err := getServiceDefinition(path)
	if err != nil {
		return nil, err
	}
	return sd, sd.ValidEntity()
}
152160
func (b *BatchProvider) restore(buf *bytes.Buffer) error {

	cmd := exec.Command(restoreCmd, "--wait")
	cmd.Stdin = buf
	out, err := cmd.CombinedOutput()
	if err != nil {
		again, _ := b.createDataBuffer()
		zap.L().Error("Failed to execute command", zap.Error(err),
			zap.ByteString("Output", out),
			zap.String("Output", again.String()),
		)
		return fmt.Errorf("Failed to execute iptables-restore: %s", err)
	}
	return nil
}
16936
func (f *Facade) ResolveServicePath(ctx datastore.Context, svcPath string, noprefix bool) ([]service.ServiceDetails, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.ResolveServicePath"))
	var (
		parent  string
		current string
		result  = []service.ServiceDetails{}
	)
	plog := plog.WithFields(log.Fields{
		"svcpath": svcPath,
	})

	// Empty paths match nothing
	if isEmptyPath(svcPath) {
		plog.Debug("Empty path produced empty result")
		return result, nil
	}

	// Clean up trailing slashes and lowercase the requested path
	svcPath = strings.TrimRight(svcPath, "/")
	svcPath = strings.ToLower(svcPath)

	// First pass: get all services that match either ID exactly or name by regex.
	// The default matching is to use a "contains" regex. This is overridable
	// via the noprefix boolean which changes the regex to an "ends with" match
	parent, current = path.Split(svcPath)

	details, err := f.serviceStore.GetServiceDetailsByIDOrName(ctx, current, noprefix)
	if err != nil {
		return nil, err
	}
	plog.WithFields(log.Fields{
		"svcPath": svcPath,
		"current": current,
		"noprefix":  noprefix,
		"matches": len(details),
	}).Debug("Found possible service matches")

	// Populate the ancestry for all of the found services, so we can check
	// their parents
	for _, detail := range details {
		d, err := f.GetServiceDetailsAncestry(ctx, detail.ID)
		if err != nil {
			return nil, err
		}
		result = append(result, *d)
	}

	// Now walk up the path, filtering parents as we go
	level := 1
	for !isEmptyPath(parent) {
		// Split the path to get the segment at this level
		parent, current = path.Split(strings.TrimRight(parent, "/"))

		// Technically this won't ever be needed, as it gets lowered in cli/cmd
		// before it gets here, but for the sake of local clarity...
		current = strings.ToLower(current)

		filtered := make([]service.ServiceDetails, 0)

		// Walk up parents to the current level and check their names to filter
		// the list of potentials
		for _, d := range result {
			p := &d
			for i := 0; i < level; i++ {
				p = p.Parent
				if p == nil {
					break
				}
			}

			// If the parent name at this level matches OR this is the last
			// segment and it matches the deployment ID, it's considered
			// a match
			if (p != nil && strings.ToLower(p.Name) == current) || (isEmptyPath(parent) && strings.ToLower(d.DeploymentID) == current) {
				filtered = append(filtered, d)
			}
		}
		result = filtered
		level++
	}
	plog.WithField("results", len(result)).Debug("Filtered service matches by parent")

	return result, nil
}
1164292
func (c *ServicedCli) searchForService(keyword string, prefix bool) (*service.ServiceDetails, int, error) {

	// If the last segment is an integer, it is an instance ID
	servicepath, instanceIDString := path.Split(keyword)
	instanceID := -1
	if num, err := strconv.Atoi(instanceIDString); err != nil {
		// It's not an integer, so just use the original path
		servicepath = keyword
	} else {
		instanceID = num
	}

	matches, err := c.driver.ResolveServicePath(servicepath, prefix)
	if err != nil {
		return nil, 0, err
	}

	// check the number of matches
	if count := len(matches); count == 0 {
		return nil, 0, errors.New("service not found")
	} else if count == 1 {
		return &matches[0], instanceID, nil
	}

	// more than one match, display a dialog
	var svcpath func(*service.ServiceDetails) string
	svcpath = func(svc *service.ServiceDetails) string {
		parent := svc.Parent
		if parent != nil {
			return path.Join(svcpath(parent), svc.Name)
		}
		return path.Join(svc.DeploymentID, svc.Name)
	}

	t := NewTable("Name,ServiceID,DepID/Path")
	t.Padding = 6
	for _, row := range matches {
		t.AddRow(map[string]interface{}{
			"Name":       row.Name,
			"ServiceID":  row.ID,
			"PoolID":     row.PoolID,
			"DepID/Path": svcpath(&row),
		})
	}
	t.Print()
	return nil, 0, fmt.Errorf("multiple results found; select one from list")
}
1278344
func (c *ServicedCli) cmdTemplateCompile(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "compile")
		return
	}

	cfg := api.CompileTemplateConfig{
		Dir: args[0],
		Map: *ctx.Generic("map").(*api.ImageMap),
	}

	if template, err := c.driver.CompileServiceTemplate(cfg); err != nil {
		fmt.Fprintln(os.Stderr, err)
	} else if template == nil {
		fmt.Fprintln(os.Stderr, "received nil template")
	} else {
		cmd := fmt.Sprintf("cd %s && git rev-parse HEAD", args[0])
		commit, err := exec.Command("sh", "-c", cmd).Output()
		if err != nil {
			commit = []byte("unknown")
		}
		cmd = fmt.Sprintf("cd %s && git config --get remote.origin.url", args[0])
		repo, err := exec.Command("sh", "-c", cmd).Output()
		if err != nil {
			repo = []byte("unknown")
		}
		cmd = fmt.Sprintf("cd %s && git rev-parse --abbrev-ref HEAD", args[0])
		branch, err := exec.Command("sh", "-c", cmd).Output()
		if err != nil {
			branch = []byte("unknown")
		}
		cmd = fmt.Sprintf("cd %s && git describe --always", args[0])
		tag, err := exec.Command("sh", "-c", cmd).Output()
		if err != nil {
			tag = []byte("unknown")
		}
		templateVersion := map[string]string{
			"repo":   strings.Trim(string(repo), "\n"),
			"branch": strings.Trim(string(branch), "\n"),
			"tag":    strings.Trim(string(tag), "\n"),
			"commit": strings.Trim(string(commit), "\n"),
		}
		mTemplate := metaTemplate{*template, servicedversion.GetVersion(), templateVersion}
		jsonTemplate, err := json.MarshalIndent(mTemplate, " ", "  ")
		if err != nil {
			fmt.Fprintf(os.Stderr, "failed to marshal template: %s\n", err)
		} else {
			fmt.Println(string(jsonTemplate))
		}
	}
}
237986
func (c *ServicedCli) cmdSnapshotCommit(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "commit")
		return
	}
	cfg := api.SnapshotConfig{
		DockerID: args[0],
	}

	if snapshot, err := c.driver.AddSnapshot(cfg); err != nil {
		fmt.Fprintln(os.Stderr, err)
	} else if snapshot == "" {
		fmt.Fprintln(os.Stderr, "received nil snapshot")
	} else {
		fmt.Println(snapshot)
	}
}