// Run the wake command.
433099
func wakeCmd(args []string, aliases *Aliases) error {
	if len(args) <= 0 {
		return errors.New("No mac address specified to wake command")
	}

	// bcastInterface can be "eth0", "eth1", etc.. An empty string implies
	// that we use the default interface when sending the UDP packet (nil).
	bcastInterface := ""
	macAddr := args[0]

	// First we need to see if this macAddr is actually an alias, if it is:
	// we set the eth interface based on the stored item, and set the macAddr
	// based on the alias of the entry.
	mi, err := aliases.Get(macAddr)
	if err == nil {
		macAddr = mi.Mac
		bcastInterface = mi.Iface
	}

	// Always use the interface specified in the command line, if it exists.
	if cliFlags.BroadcastInterface != "" {
		bcastInterface = cliFlags.BroadcastInterface
	}

	// Populate the local address in the event that the broadcast interface has
	// been set.
	var localAddr *net.UDPAddr
	if bcastInterface != "" {
		localAddr, err = ipFromInterface(bcastInterface)
		if err != nil {
			return err
		}
	}

	// The address to broadcast to is usually the default `255.255.255.255` but
	// can be overloaded by specifying an override in the CLI arguments.
	bcastAddr := fmt.Sprintf("%s:%s", cliFlags.BroadcastIP, cliFlags.UDPPort)
	udpAddr, err := net.ResolveUDPAddr("udp", bcastAddr)
	if err != nil {
		return err
	}

	// Build the magic packet.
	mp, err := wol.New(macAddr)
	if err != nil {
		return err
	}

	// Grab a stream of bytes to send.
	bs, err := mp.Marshal()
	if err != nil {
		return err
	}

	// Grab a UDP connection to send our packet of bytes.
	conn, err := net.DialUDP("udp", localAddr, udpAddr)
	if err != nil {
		return err
	}
	defer conn.Close()

	fmt.Printf("Attempting to send a magic packet to MAC %s\n", macAddr)
	fmt.Printf("... Broadcasting to: %s\n", bcastAddr)
	n, err := conn.Write(bs)
	if err == nil && n != 102 {
		err = fmt.Errorf("magic packet sent was %d bytes (expected 102 bytes sent)", n)
	}
	if err != nil {
		return err
	}

	fmt.Printf("Magic packet sent successfully to %s\n", macAddr)
	return nil
}
436436
func (c *Controller) Run() (err error) {
	defer c.shutdown()
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT)

	instID, err := strconv.Atoi(c.options.Service.InstanceID)
	if err != nil {
		return err
	}

	env := os.Environ()
	env = append(env, "CONTROLPLANE=1")
	env = append(env, fmt.Sprintf("CONTROLPLANE_CONSUMER_URL=http://localhost%s/api/metrics/store", c.options.Metric.Address))
	env = append(env, fmt.Sprintf("CONTROLPLANE_HOST_ID=%s", c.hostID))
	env = append(env, fmt.Sprintf("CONTROLPLANE_TENANT_ID=%s", c.tenantID))
	env = append(env, fmt.Sprintf("CONTROLPLANE_INSTANCE_ID=%s", c.options.Service.InstanceID))
	env = append(env, fmt.Sprintf("CONTROLPLANE_SERVICED_ID=%s", c.options.Service.ID))

	if err := writeEnvFile(env); err != nil {
		return err
	}

	args := []string{"-c", "exec " + strings.Join(c.options.Service.Command, " ")}

	startService := func() (*subprocess.Instance, chan error) {
		service, serviceExited, _ := subprocess.New(time.Second*10, env, "/bin/sh", args...)
		return service, serviceExited
	}

	sendSignal := func(service *subprocess.Instance, sig os.Signal) bool {
		switch {
		case c.PIDFile != "":
			c.forwardSignal(sig)
		case service != nil:
			service.Notify(sig)
		default:
			return false
		}
		return true
	}

	rpcDead, err := c.rpcHealthCheck()
	if err != nil {
		glog.Errorf("Could not setup RPC ping check: %s", err)
		return err
	}

	storageDead, err := c.storageHealthCheck()
	if err != nil {
		glog.Errorf("Could not set up storage check: %s", err)
		return err
	}

	prereqsPassed := make(chan bool)
	var startAfter <-chan time.Time
	var exitAfter <-chan time.Time
	var service *subprocess.Instance = nil
	serviceExited := make(chan error, 1)
	endpointExit := make(chan struct{})
	c.endpoints.Run(endpointExit)

	// Start CC Rest API Proxy
	go c.ccApiProxy.run()

	// HACK: I guess this is how it used to work?  This code is horrible.
	go func() {
		errc := <-c.closing
		close(endpointExit)
		errc <- nil
	}()

	if err := c.handleControlCenterImports(rpcDead); err != nil {
		glog.Error("Could not setup Control Center specific imports: ", err)
		return err
	}
	go c.checkPrereqs(prereqsPassed, rpcDead)
	go c.reapZombies(rpcDead)
	healthExit := make(chan struct{})
	defer close(healthExit)

	if os.Getenv("SERVICED_IS_SERVICE_SHELL") != "true" {
		c.kickOffHealthChecks(healthExit)
	}

	exited := false

	var shutdownService = func(service *subprocess.Instance, sig os.Signal) {
		c.options.Service.Autorestart = false
		if sendSignal(service, sig) {
			// nil out all other channels because we're shutting down
			sigc = nil
			prereqsPassed = nil
			startAfter = nil
			rpcDead = nil
			storageDead = nil

			// exitAfter is the deadman switch for unresponsive processes and any processes that have already exited
			exitAfter = time.After(time.Second * 30)

			glog.Infof("Closing healthExit on signal %v for %q", sig, c.options.Service.ID)
			close(healthExit)
			glog.Infof("Closed healthExit on signal %v for %q", sig, c.options.Service.ID)
		} else {
			c.exitStatus = 1
			exited = true
			glog.Infof("Exited due to sendSignal(%v) failed for %q", sig, c.options.Service.ID)
		}
	}

	for !exited {
		select {
		case sig := <-sigc:
			glog.Infof("Notifying subprocess of signal %v for service %s", sig, c.options.Service.ID)
			shutdownService(service, sig)
			glog.Infof("Notification complete for signal %v for service %s", sig, c.options.Service.ID)

		case <-exitAfter:
			glog.Infof("Killing unresponsive subprocess for service %s", c.options.Service.ID)
			sendSignal(service, syscall.SIGKILL)
			glog.Infof("Kill signal sent for service %s", c.options.Service.ID)
			c.exitStatus = 1
			exited = true

		case <-prereqsPassed:
			startAfter = time.After(time.Millisecond * 1)
			prereqsPassed = nil

		case exitError := <-serviceExited:
			if !c.options.Service.Autorestart {
				exitStatus, _ := utils.GetExitStatus(exitError)
				if c.options.Logforwarder.Enabled {
					time.Sleep(c.options.Logforwarder.SettleTime)
				}
				glog.Infof("Service %s Exited with status:%d due to %+v", c.options.Service.ID, exitStatus, exitError)
				//set loop to end
				exited = true
				//exit with exit code, defer so that other cleanup can happen
				c.exitStatus = exitStatus

			} else {
				glog.Infof("Restarting service process for service %s in 10 seconds.", c.options.Service.ID)
				service = nil
				startAfter = time.After(time.Second * 10)
			}

		case <-startAfter:
			glog.Infof("Starting service process for service %s", c.options.Service.ID)
			service, serviceExited = startService()
			startAfter = nil
		case <-rpcDead:
			glog.Infof("RPC Server has gone away, cleaning up service %s", c.options.Service.ID)
			shutdownService(service, syscall.SIGTERM)
			glog.Infof("RPC Server shutdown for service %s complete", c.options.Service.ID)
		case <-storageDead:
			glog.Infof("Distributed storage for service %s has gone away; shutting down", c.options.Service.ID)
			shutdownService(service, syscall.SIGTERM)
			glog.Infof("Distributed storage shutdown for service %s complete", c.options.Service.ID)
		}
	}
	// Signal to health check registry that this instance is giving up the ghost.
	client, err := node.NewLBClient(c.options.ServicedEndpoint)
	if err != nil {
		glog.Errorf("Could not create a client to endpoint: %s, %s", c.options.ServicedEndpoint, err)
		return nil
	}
	defer client.Close()
	c.Close()
	req := master.ServiceInstanceRequest{
		ServiceID:  c.options.Service.ID,
		InstanceID: instID,
	}
	client.ReportInstanceDead(req, nil)
	return nil
}
461584
func (c *CniMonitor) Run(ctx context.Context) error {

	return c.proc.config.IsComplete()
}
300180
func (e *BoxAuditSchedulerBackground) Run(m libkb.MetaContext) (err error) {
	return RunEngine2(m, e.task)
}
72551
func (i *initCmd) run() error {
	if err := i.tlsOptions(); err != nil {
		return err
	}
	i.opts.Namespace = i.namespace
	i.opts.UseCanary = i.canary
	i.opts.ImageSpec = i.image
	i.opts.ForceUpgrade = i.forceUpgrade
	i.opts.ServiceAccount = i.serviceAccount
	i.opts.MaxHistory = i.maxHistory
	i.opts.Replicas = i.replicas

	writeYAMLManifests := func(manifests []string) error {
		w := i.out
		for _, manifest := range manifests {
			if _, err := fmt.Fprintln(w, "---"); err != nil {
				return err
			}

			if _, err := fmt.Fprintln(w, manifest); err != nil {
				return err
			}
		}

		// YAML ending document boundary marker
		_, err := fmt.Fprintln(w, "...")
		return err
	}
	if len(i.opts.Output) > 0 {
		var manifests []string
		var err error
		if manifests, err = installer.TillerManifests(&i.opts); err != nil {
			return err
		}
		switch i.opts.Output.String() {
		case "json":
			for _, manifest := range manifests {
				var out bytes.Buffer
				jsonb, err := yaml.ToJSON([]byte(manifest))
				if err != nil {
					return err
				}
				buf := bytes.NewBuffer(jsonb)
				if err := json.Indent(&out, buf.Bytes(), "", "    "); err != nil {
					return err
				}
				if _, err = i.out.Write(out.Bytes()); err != nil {
					return err
				}
				fmt.Fprint(i.out, "\n")
			}
			return nil
		case "yaml":
			return writeYAMLManifests(manifests)
		default:
			return fmt.Errorf("unknown output format: %q", i.opts.Output)
		}
	}
	if settings.Debug {
		var manifests []string
		var err error

		// write Tiller manifests
		if manifests, err = installer.TillerManifests(&i.opts); err != nil {
			return err
		}

		if err = writeYAMLManifests(manifests); err != nil {
			return err
		}
	}

	if i.dryRun {
		return nil
	}

	if err := installer.Initialize(i.home, i.out, i.skipRefresh, settings, stableRepositoryURL, localRepositoryURL); err != nil {
		return fmt.Errorf("error initializing: %s", err)
	}
	fmt.Fprintf(i.out, "$HELM_HOME has been configured at %s.\n", settings.Home)

	if !i.clientOnly {
		if i.kubeClient == nil {
			_, c, err := getKubeClient(settings.KubeContext, settings.KubeConfig)
			if err != nil {
				return fmt.Errorf("could not get kubernetes client: %s", err)
			}
			i.kubeClient = c
		}
		if err := installer.Install(i.kubeClient, &i.opts); err != nil {
			if !apierrors.IsAlreadyExists(err) {
				return fmt.Errorf("error installing: %s", err)
			}
			if i.upgrade {
				if err := installer.Upgrade(i.kubeClient, &i.opts); err != nil {
					return fmt.Errorf("error when upgrading: %s", err)
				}
				if err := i.ping(i.opts.SelectImage()); err != nil {
					return err
				}
				fmt.Fprintln(i.out, "\nTiller (the Helm server-side component) has been upgraded to the current version.")
			} else {
				fmt.Fprintln(i.out, "Warning: Tiller is already installed in the cluster.\n"+
					"(Use --client-only to suppress this message, or --upgrade to upgrade Tiller to the current version.)")
			}
		} else {
			fmt.Fprintln(i.out, "\nTiller (the Helm server-side component) has been installed into your Kubernetes Cluster.")
			if !tlsVerify {
				fmt.Fprintln(i.out, "\nPlease note: by default, Tiller is deployed with an insecure 'allow unauthenticated users' policy.\n"+
					"To prevent this, run `helm init` with the --tiller-tls-verify flag.\n"+
					"For more information on securing your installation see: https://docs.helm.sh/using_helm/#securing-your-helm-installation")
			}
		}
		if err := i.ping(i.opts.SelectImage()); err != nil {
			return err
		}
	} else {
		fmt.Fprintln(i.out, "Not installing Tiller due to 'client-only' flag having been set")
	}

	needsDefaultImage := !i.clientOnly && !i.opts.UseCanary && len(i.opts.ImageSpec) == 0 && version.BuildMetadata == "unreleased"
	if needsDefaultImage {
		fmt.Fprintf(i.out, "\nWarning: You appear to be using an unreleased version of Helm. Please either use the\n"+
			"--canary-image flag, or specify your desired tiller version with --tiller-image.\n\n"+
			"Ex:\n"+
			"$ helm init --tiller-image gcr.io/kubernetes-helm/tiller:v2.8.2\n\n")
	}

	return nil
}
400120
func (a *Autopilot) run() {
	defer a.waitGroup.Done()

	// Monitor server health until shutdown
	ticker := time.NewTicker(a.interval)
	defer ticker.Stop()

	for {
		select {
		case <-a.shutdownCh:
			return
		case <-ticker.C:
			if err := a.promoteServers(); err != nil {
				a.logger.Printf("[ERR] autopilot: Error promoting servers: %v", err)
			}

			if err := a.pruneDeadServers(); err != nil {
				a.logger.Printf("[ERR] autopilot: Error checking for dead servers to remove: %s", err)
			}
		case <-a.removeDeadCh:
			if err := a.pruneDeadServers(); err != nil {
				a.logger.Printf("[ERR] autopilot: Error checking for dead servers to remove: %s", err)
			}
		}
	}
}
1305136
func (s *Scheduler) Run() {
	s.mu.Lock()
	s.state = stateRunning
	s.mu.Unlock()

	s.startProcessRequestsLoop()
}
1063182
func (s *SortCommand) Run() (*Reply, error) {
	args := packArgs("SORT", s.key)
	if s.by != "" {
		args = append(args, "BY", s.by)
	}
	if s.limit {
		args = append(args, "LIMIT", s.offset, s.count)
	}
	if s.get != nil && len(s.get) > 0 {
		for _, pattern := range s.get {
			args = append(args, "GET", pattern)
		}
	}
	if s.order != "" {
		args = append(args, s.order)
	}
	if s.alpha {
		args = append(args, "ALPHA")
	}
	if s.store != "" {
		args = append(args, "STORE", s.store)
	}
	return s.redis.ExecuteCommand(args...)
}
369237
func (c *ListCommand) Run(ctx *cmd.Context) error {
	apiclient, err := c.deps.NewClient(c)
	if err != nil {
		return errors.Trace(err)
	}
	defer apiclient.Close()

	var unit string
	var application string
	if names.IsValidApplication(c.target) {
		application = c.target
	} else {
		application, err = names.UnitApplication(c.target)
		if err != nil {
			return errors.Errorf("%q is neither an application nor a unit", c.target)
		}
		unit = c.target
	}

	vals, err := apiclient.ListResources([]string{application})
	if err != nil {
		return errors.Trace(err)
	}
	if len(vals) != 1 {
		return errors.Errorf("bad data returned from server")
	}
	v := vals[0]

	// It's a lot easier to read and to digest a list of resources
	// when  they are ordered.
	sort.Sort(charmResourceList(v.CharmStoreResources))
	sort.Sort(resourceList(v.Resources))
	for _, u := range v.UnitResources {
		sort.Sort(resourceList(u.Resources))
	}

	if unit == "" {
		return c.formatApplicationResources(ctx, v)
	}
	return c.formatUnitResources(ctx, unit, application, v)
}
37
func (s *Service) Run() {
	flag.Usage = s.Usage
	flag.Parse()
	args := flag.Args()
	if len(args) == 0 && s.defaultCommand != "" {
		args = append([]string{s.defaultCommand}, args...)
	}
	if len(args) == 0 {
		s.Usage()
		BootPrintln()
		return
	}
	err := s.RunCommand(args[0], args[1:]...)
	if err != nil {
		panic(err)
	}
}
453592
func (c *CmdSimpleFSClearConflicts) Run() error {
	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	return cli.SimpleFSClearConflictState(context.TODO(), c.path)
}
470533
func (b *Driver) Wake() (err error) {
	buf := []byte{0x01}

	err = b.adaptor().WriteCharacteristic(wakeCharacteristic, buf)
	if err != nil {
		fmt.Println("Wake error:", err)
		return err
	}

	return
}
347648
func (c *enableCommand) Run(_ *cmd.Context) error {
	api, err := c.apiFunc(c)
	if err != nil {
		return errors.Annotate(err, "cannot connect to the API")
	}
	defer api.Close()

	return api.SwitchBlockOff(c.target)
}
113240
func (cmd *connectCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
	c := cli.GetContext(app, cmd, env)
	if err := cmd.validateFlags(c); err != nil {
		logging.Errorf(c, "%s", err.Error())
		return 1
	}
	if cmd.server == ":metadata" {
		meta := getMetadata(c)
		srv, err := meta.Get("instance/attributes/swarming-server")
		if err != nil {
			logging.Errorf(c, "%s", err.Error())
			return 1
		}
		cmd.server = srv
	}
	if cmd.provider != "" {
		meta := getMetadata(c)
		name, err := meta.InstanceName()
		if err != nil {
			logging.Errorf(c, "%s", err.Error())
			return 1
		}
		if cmd.provider == ":metadata" {
			cmd.provider, err = meta.Get("instance/attributes/provider")
			if err != nil {
				logging.Errorf(c, "%s", err.Error())
				return 1
			}
		}
		prov := newInstances(c, cmd.serviceAccount, cmd.provider)
		inst, err := prov.Get(c, &instances.GetRequest{
			Hostname: name,
		})
		if err != nil {
			logging.Errorf(c, "%s", err.Error())
			return 1
		}
		cmd.server = inst.Swarming
	}

	swr := getSwarming(c)
	swr.server = cmd.server
	if err := swr.Configure(c, cmd.dir, cmd.user); err != nil {
		logging.Errorf(c, "%s", err.Error())
		return 1
	}
	return 0
}
871666
func (cmd *ConfigCommand) Run(_ context.Context) error {
	buf, err := toml.Marshal(*cmd.Config)
	if err != nil {
		return err
	}
	fmt.Fprintln(cmd.Stdout, string(buf))
	return nil
}
1145422
func (m *Launcher) Run(ctx context.Context, args ...string) error {
	cmd := &cobra.Command{
		Use:   "run",
		Short: "Start the influxd server (default)",
		RunE: func(cmd *cobra.Command, args []string) error {
			return m.run(ctx)
		},
	}

	buildLauncherCommand(m, cmd)

	cmd.SetArgs(args)
	return cmd.Execute()
}
454240
func (c *Cmd) Run() {
	if c.stdin != nil {
		c.cmd.Stdin = c.stdin
	}

	if c.env != nil {
		c.cmd.Env = c.env
	} else {
		c.cmd.Env = os.Environ()
	}

	var outBuf bytes.Buffer
	c.cmd.Stdout = &outBuf

	var errBuf bytes.Buffer
	c.cmd.Stderr = &errBuf

	if err := c.cmd.Run(); err != nil {
		c.exitError = err
	}
	c.stdout = string(outBuf.Bytes())
	c.stderr = string(errBuf.Bytes())
	c.executed = true
}