// START: ExternalSink interface implementations
164194
func (h *hawkularSink) Register(mds []core.MetricDescriptor) error {
	// Create model definitions based on the MetricDescriptors
	for _, md := range mds {
		hmd := h.descriptorToDefinition(&md)
		h.models[md.Name] = &hmd
	}

	if !h.disablePreCaching {
		// Fetch currently known metrics from Hawkular-Metrics and cache them
		err := h.cacheDefinitions()
		if err != nil {
			return err
		}
	}

	return nil
}
768832
func (s *Server) Start() error {
	if !atomic.CompareAndSwapUint32(&s.started, 0, 1) {
		return nil
	}

	s.wg.Add(1)
	go s.subscriptionHandler()

	return nil
}
138081
func (s *stream) Start() error {
	if s.ref != nilstream {
		return nil
	}
	wg.Wait()
	p := C.CFStringCreateWithCStringNoCopy(C.kCFAllocatorDefault, C.CString(s.path), C.kCFStringEncodingUTF8, C.kCFAllocatorDefault)
	path := C.CFArrayCreate(C.kCFAllocatorDefault, (*unsafe.Pointer)(unsafe.Pointer(&p)), 1, nil)
	ctx := C.FSEventStreamContext{}
	ref := C.EventStreamCreate(&ctx, C.uintptr_t(s.info), path, C.FSEventStreamEventId(atomic.LoadUint64(&since)), latency, flags)
	if ref == nilstream {
		return errCreate
	}
	C.FSEventStreamScheduleWithRunLoop(ref, runloop, C.kCFRunLoopDefaultMode)
	if C.FSEventStreamStart(ref) == C.Boolean(0) {
		C.FSEventStreamInvalidate(ref)
		return errStart
	}
	C.CFRunLoopWakeUp(runloop)
	s.ref = ref
	return nil
}
953174
func (s *service) Start(ctx context.Context, r *taskAPI.StartRequest) (*taskAPI.StartResponse, error) {
	log.G(ctx).Debugf("Start: %s: %s", r.ID, r.ExecID)
	var p *process
	var err error
	if p, err = s.getProcess(r.ID, r.ExecID); err != nil {
		return nil, err
	}
	p.Lock()
	defer p.Unlock()

	if p.started {
		return nil, errors.New("cannot start already started container or process")
	}

	rhcs := s.newRunhcs()

	// This is a start/exec
	if r.ExecID != "" {
		execFmt := fmt.Sprintf("exec-%s-%s", r.ID, r.ExecID)
		pidfilePath := path.Join(p.bundle, fmt.Sprintf("runhcs-%s-pidfile.pid", execFmt))
		procConfig := path.Join(p.bundle, execFmt+"config.json")
		eopts := &runhcs.ExecOpts{
			IO:      p.relay.io,
			PidFile: pidfilePath,
			Detach:  true,
		}

		if rhcs.Debug {
			if s.shimOpts.DebugType == options.Options_FILE {
				eopts.ShimLog = filepath.Join(p.bundle, fmt.Sprintf("runhcs-shim-%s.log", execFmt))
			} else {
				doForwardLogs := func(source, pipeName string, opt *string) error {
					*opt = safePipePrefix + pipeName
					l, err := winio.ListenPipe(*opt, nil)
					if err != nil {
						return err
					}
					go func() {
						defer l.Close()
						c, err := l.Accept()
						if err != nil {
							log.G(ctx).
								WithField("task-id", r.ID).
								WithField("exec-id", r.ExecID).
								WithError(err).
								Errorf("failed to accept %s", pipeName)
						} else {
							fields := map[string]interface{}{
								"log-source": source,
								"task-id":    r.ID,
								"exec-id":    r.ExecID,
							}
							go forwardRunhcsLogs(ctx, c, fields)
						}
					}()
					return nil
				}

				err = doForwardLogs("runhcs-shim-exec", "runhcs-shim-log-"+execFmt, &eopts.ShimLog)
				if err != nil {
					return nil, err
				}
			}
		}

		// For the exec case increment the startedWg to make sure we publish the
		// started event previous to the exit published in `waitForProcess`.
		p.startedWg.Add(1)
		defer func() {
			if err != nil {
				// If an exec failure takes place decrement the startedWg so we
				// dont get off on counts.
				p.startedWg.Done()
			}
		}()

		// ID here is the containerID to exec the process in.
		err = rhcs.Exec(ctx, r.ID, procConfig, eopts)
		if err != nil {
			return nil, errors.Wrapf(err, "failed to exec process: %s", r.ExecID)
		}

		p.started = true

		// We successfully exec'd the process. Convert from initpid to the container process.
		pid, err := runc.ReadPidFile(pidfilePath)
		if err != nil {
			return nil, errors.Wrap(err, "failed to read container pid from pidfile")
		}

		proc, err := os.FindProcess(pid)
		if err != nil {
			return nil, errors.Wrap(err, "failed to find exec process pid")
		}
		go waitForProcess(ctx, p, proc, s)
	} else {
		if err := rhcs.Start(ctx, p.id); err != nil {
			return nil, errors.Wrapf(err, "failed to start container: %s", p.id)
		}

		p.started = true

		// TODO: JTERRY75 - This is a total hack. We cant return from this call
		// until the state has transitioned. Because runhcs start is long lived it
		// will return before the actual state is "RUNNING" which causes a failure
		// if the 'state' query comes in and it is not in the "RUNNING" state.
		stateRequest := &taskAPI.StateRequest{
			ID:     r.ID,
			ExecID: r.ExecID,
		}
		for {
			sr, err := s.State(ctx, stateRequest)
			if err != nil {
				log.G(ctx).WithError(err).Debug("failed to query state of container")
				break
			}
			// Have we transitioned states yet? Expect != created && != unknown
			if sr.Status != task.StatusCreated && sr.Status != task.StatusUnknown {
				break
			}
			time.Sleep(1 * time.Second)
		}
	}

	pid := p.stat().pid
	if r.ExecID != "" {
		s.publisher.Publish(ctx,
			runtime.TaskExecStartedEventTopic,
			&eventstypes.TaskExecStarted{
				ContainerID: p.cid,
				ExecID:      p.id,
				Pid:         pid,
			})
	} else {
		s.publisher.Publish(ctx,
			runtime.TaskStartEventTopic,
			&eventstypes.TaskStart{
				ContainerID: p.id,
				Pid:         pid,
			})
	}

	p.startedWg.Done()

	return &taskAPI.StartResponse{
		Pid: pid,
	}, nil
}
1207329
func (t *CliLogBoxTask) Start(wg *sync.WaitGroup) golib.StopChan {
	if t.Update == nil {
		return golib.NewStoppedChan(errors.New("CliLogBoxTask.Update cannot be nil"))
	}
	t.InterceptLoggers()
	t.updateTask = &golib.LoopTask{
		Description: "CliLogBoxTask",
		StopHook: func() {
			err := t.updateBox() // One last screen refresh to make sure no messages get lost.
			t.RestoreLoggers()
			golib.Printerr(err)
		},
		Loop: func(stop golib.StopChan) (err error) {
			err = t.updateBox()
			if err == nil {
				// Wait between t.MinUpdateInterval and t.UpdateInterval,
				// but wake up from stop.WaitChan() and t.updateTrigger.
				sleepStart := time.Now()
				select {
				case <-time.After(t.UpdateInterval):
				case <-stop.WaitChan():
				case <-t.updateTrigger:
				}
				sleepTime := time.Now().Sub(sleepStart)
				if diff := t.MinUpdateInterval - sleepTime; diff > 0 {
					select {
					// Don't wait for t.updateTrigger here
					case <-time.After(diff):
					case <-stop.WaitChan():
					}
				}
			}
			return
		},
	}
	return t.updateTask.Start(wg)
}
965435
func (mux *Multiplexer) Start() error {
	mux.rwlock.Lock()
	defer mux.rwlock.Unlock()
	var err error

	if mux.started {
		return fmt.Errorf("multiplexer has been started already")
	}

	// block further Consumer consumers
	mux.started = true

	var hashTopics, manTopics []string

	for _, subscription := range mux.mapping {
		if subscription.manual {
			manTopics = append(manTopics, subscription.topic)
			continue
		}
		hashTopics = append(hashTopics, subscription.topic)
	}

	mux.config.SetRecvMessageChan(make(chan *client.ConsumerMessage))
	mux.config.GroupID = mux.name
	mux.config.SetInitialOffset(sarama.OffsetOldest)
	mux.config.Topics = append(hashTopics, manTopics...)

	// create consumer
	mux.WithFields(logging.Fields{"hashTopics": hashTopics, "manualTopics": manTopics}).Debugf("Consuming started")
	mux.Consumer, err = client.NewConsumer(mux.config, nil)
	if err != nil {
		return err
	}

	if len(hashTopics) == 0 {
		mux.Debug("No topics for hash partitioner")
	} else {
		mux.WithFields(logging.Fields{"topics": hashTopics}).Debugf("Consuming (hash) started")
		mux.Consumer.StartConsumerHandlers()
	}

	if len(manTopics) == 0 {
		mux.Debug("No topics for manual partitioner")
	} else {
		mux.WithFields(logging.Fields{"topics": manTopics}).Debugf("Consuming (manual) started")
		for _, sub := range mux.mapping {
			if sub.manual {
				sConsumer := mux.Consumer.SConsumer
				if sConsumer == nil {
					return fmt.Errorf("consumer for manual partition is not available")
				}
				partitionConsumer, err := sConsumer.ConsumePartition(sub.topic, sub.partition, sub.offset)
				if err != nil {
					return err
				}
				// Store partition consumer in subscription so it can be closed lately
				sub.partitionConsumer = &partitionConsumer
				mux.Logger.WithFields(logging.Fields{"topic": sub.topic, "partition": sub.partition, "offset": sub.offset}).Info("Partition sConsumer started")
				mux.Consumer.StartConsumerManualHandlers(partitionConsumer)
			}
		}

	}

	go mux.genericConsumer()
	go mux.manualConsumer(mux.Consumer)

	return err
}
423363
func (s *Stdout) Start() error {
	if os.Stdout == nil {
		return errors.New("stdout is not available")
	}
	return nil
}
95925
func (s *File) Start() error {

	if s.Dir == "" {
		dir, err := ioutil.TempDir("", "")
		if err != nil {
			return err
		}
		s.Dir = dir
	}
	if err := os.MkdirAll(s.Dir, 0700); err != nil {
		return err
	}
	return nil
}
38003
func (k *KeepAlive) Start(ctx gocontext.Context) {
	for {
		select {
		case <-ctx.Done():
			return
		case <-time.After(k.timeout):
			k.sendKeepAlive()
		}
	}
}
1031452
func (w *GCWorker) Start() {
	var ctx context.Context
	ctx, w.cancel = context.WithCancel(context.Background())
	var wg sync.WaitGroup
	wg.Add(1)
	go w.start(ctx, &wg)
	wg.Wait() // Wait create session finish in worker, some test code depend on this to avoid race.
}
773011
func Start(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
	// Allow insecure Docker registries on all private network ranges in RFC 1918 and RFC 6598.
	dargs := []string{
		"-d",
		"--bip=172.19.42.1/16",
		"--insecure-registry",
		"10.0.0.0/8",
		"--insecure-registry",
		"172.16.0.0/12",
		"--insecure-registry",
		"192.168.0.0/16",
		"--insecure-registry",
		"100.64.0.0/10",
		"--exec-opt",
		"native.cgroupdriver=cgroupfs",
	}

	// For overlay-ish filesystems, force the overlay to kick in if it exists.
	// Then we can check the fstype.
	if err := os.MkdirAll("/", 0700); err == nil {

		cmd := exec.Command("findmnt", "--noheadings", "--output", "FSTYPE", "--target", "/")

		if out, err := cmd.Output(); err == nil && strings.TrimSpace(string(out)) == "overlay" {
			dargs = append(dargs, "--storage-driver=overlay")
		} else {
			log.Infof(c, "File system type: '%s' (%v)", out, err)
		}
	}

	log.Infof(c, "Starting docker with %s", strings.Join(dargs, " "))
	cmd := exec.Command("docker", dargs...)
	if err := cmd.Start(); err != nil {
		log.Errf(c, "Failed to start Docker. %s", err)
		return -1, err
	}
	// Get the PID and return it.
	return cmd.Process.Pid, nil
}
290231
func (rw *GCS) Start() error {
	ctx := context.Background()
	var client *storage.Client
	var err error

	if len(rw.ServiceAccountKey) > 0 {
		opt := option.WithServiceAccountFile(rw.ServiceAccountKey)
		client, err = storage.NewClient(ctx, opt)
	} else {
		client, err = storage.NewClient(ctx)
	}

	if err != nil {
		return err
	}
	rw.bucket = client.Bucket(rw.Bucket)
	return nil
}
475567
func (c *Client) start() {
	log.Tracef("Starting RPC client %s", c.config.Host)

	// Start the I/O processing handlers depending on whether the client is
	// in HTTP POST mode or the default websocket mode.
	if c.config.HTTPPostMode {
		c.wg.Add(1)
		go c.sendPostHandler()
	} else {
		c.wg.Add(3)
		go func() {
			if c.ntfnHandlers != nil {
				if c.ntfnHandlers.OnClientConnected != nil {
					c.ntfnHandlers.OnClientConnected()
				}
			}
			c.wg.Done()
		}()
		go c.wsInHandler()
		go c.wsOutHandler()
	}
}
1105571
func (r *Rescan) Start() <-chan error {
	errChan := make(chan error, 1)

	if !atomic.CompareAndSwapUint32(&r.started, 0, 1) {
		errChan <- fmt.Errorf("Rescan already started")
		return errChan
	}

	r.wg.Add(1)
	go func() {
		defer r.wg.Done()

		rescanArgs := append(r.options, updateChan(r.updateChan))
		err := rescan(r.chain, rescanArgs...)

		close(r.running)

		r.errMtx.Lock()
		r.err = err
		r.errMtx.Unlock()

		errChan <- err
	}()

	return errChan
}
1322831
func (s *Server) Start(ctx context.Context) (*net.TCPAddr, error) {
	return s.srv.Start(ctx, "devshell", s.Port, s.serve)
}
402566
func (gs *GRPCSpanSink) Start(cl *trace.Client) error {
	gs.traceClient = cl

	// Run a background goroutine to do a little bit of connection state
	// tracking.
	go func() {
		for {
			// This call will block on a channel receive until the gRPC connection
			// state changes. When it does, flip the marker over to allow another
			// error to be logged from Ingest().
			gs.grpcConn.WaitForStateChange(ocontext.Background(), gs.grpcConn.GetState())
			atomic.StoreUint32(&gs.loggedSinceTransition, 0)
		}
	}()
	return nil
}
829135
func (m *managerImpl) Start(diskInfoProvider DiskInfoProvider, podFunc ActivePodsFunc, podCleanedUpFunc PodCleanedUpFunc, monitoringInterval time.Duration) {
	thresholdHandler := func(message string) {
		klog.Infof(message)
		m.synchronize(diskInfoProvider, podFunc)
	}
	if m.config.KernelMemcgNotification {
		for _, threshold := range m.config.Thresholds {
			if threshold.Signal == evictionapi.SignalMemoryAvailable || threshold.Signal == evictionapi.SignalAllocatableMemoryAvailable {
				notifier, err := NewMemoryThresholdNotifier(threshold, m.config.PodCgroupRoot, &CgroupNotifierFactory{}, thresholdHandler)
				if err != nil {
					klog.Warningf("eviction manager: failed to create memory threshold notifier: %v", err)
				} else {
					go notifier.Start()
					m.thresholdNotifiers = append(m.thresholdNotifiers, notifier)
				}
			}
		}
	}
	// start the eviction manager monitoring
	go func() {
		for {
			if evictedPods := m.synchronize(diskInfoProvider, podFunc); evictedPods != nil {
				klog.Infof("eviction manager: pods %s evicted, waiting for pod to be cleaned up", format.Pods(evictedPods))
				m.waitForPodsCleanup(podCleanedUpFunc, evictedPods)
			} else {
				time.Sleep(monitoringInterval)
			}
		}
	}()
}