// Creates new Controller node interface and returns
426092
func newControllerNode(cfg VSphereConfig) (*VSphere, error) {
	vs, err := buildVSphereFromConfig(cfg)
	if err != nil {
		return nil, err
	}
	vs.hostName, err = os.Hostname()
	if err != nil {
		klog.Errorf("Failed to get hostname. err: %+v", err)
		return nil, err
	}
	if cfg.Global.VMUUID != "" {
		vs.vmUUID = cfg.Global.VMUUID
	} else {
		vs.vmUUID, err = getVMUUID()
		if err != nil {
			klog.Errorf("Failed to get uuid. err: %+v", err)
			return nil, err
		}
	}
	runtime.SetFinalizer(vs, logout)
	return vs, nil
}
533473
func NewMockNodeInterface(ctrl *gomock.Controller) *MockNodeInterface {
	mock := &MockNodeInterface{ctrl: ctrl}
	mock.recorder = &MockNodeInterfaceMockRecorder{mock}
	return mock
}
19657
func NewController(backend Backend, t *api.Task) (*Controller, error) {
	spec, err := readSpec(t)
	if err != nil {
		return nil, err
	}
	return &Controller{
		backend:   backend,
		spec:      spec,
		serviceID: t.ServiceID,
		logger: logrus.WithFields(logrus.Fields{
			"controller": "plugin",
			"task":       t.ID,
			"plugin":     spec.Name,
		})}, nil
}
407349
func NewController(ps *pss.Pss) *Controller {
	ctrl := &Controller{
		pss:           ps,
		notifiers:     make(map[string]*notifier),
		subscriptions: make(map[string]*subscription),
	}
	ctrl.pss.Register(&controlTopic, pss.NewHandler(ctrl.Handler))
	return ctrl
}
509844
func NewOrganizationController(service *goa.Service, app application.Application) *OrganizationController {
	return &OrganizationController{Controller: service.NewController("OrganizationController"), app: app}
}
428544
func newControllerInitializers() map[string]initFunc {
	controllers := map[string]initFunc{}
	controllers["cloud-node"] = startCloudNodeController
	controllers["cloud-node-lifecycle"] = startCloudNodeLifecycleController
	controllers["service"] = startServiceController
	controllers["route"] = startRouteController
	return controllers
}
853575
func NewNode(name string) (node Node) {
	node = Node{
		Name:        name,
		Environment: "_default",
		ChefType:    "node",
		JsonClass:   "Chef::Node",
	}
	return
}
148629
func NewControllerAPIv5(ctx facade.Context) (*ControllerAPIv5, error) {
	v6, err := NewControllerAPIv6(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return &ControllerAPIv5{v6}, nil
}
410079
func (s *packetManager) controller() {
	for {
		select {
		case pkt := <-s.requests:
			debug("incoming id (oid): %v (%v)", pkt.id(), pkt.orderId())
			s.incoming = append(s.incoming, pkt)
			s.incoming.Sort()
		case pkt := <-s.responses:
			debug("outgoing id (oid): %v (%v)", pkt.id(), pkt.orderId())
			s.outgoing = append(s.outgoing, pkt)
			s.outgoing.Sort()
		case <-s.fini:
			return
		}
		s.maybeSendPackets()
	}
}
10573
func NewControllerAPIv6(ctx facade.Context) (*ControllerAPIv6, error) {
	v7, err := NewControllerAPIv7(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return &ControllerAPIv6{v7}, nil
}
239926
func NewPlainController(sqlStr string, keyspace string) *PlainController {
	controller := &PlainController{
		sqls:     make([]string, 0, 32),
		keyspace: keyspace,
	}

	sqls, err := sqlparser.SplitStatementToPieces(sqlStr)
	if err != nil {
		panic(err.Error())
	}

	for _, sql := range sqls {
		s := strings.TrimSpace(sql)
		if s != "" {
			controller.sqls = append(controller.sqls, s)
		}
	}
	return controller
}
1051647
func Node() (c *NodeController) {
	return &NodeController{
		List:   nodeList,
		Detail: nodeDetail,
		Raw:    nodeRaw,
		Delete: nodeDelete,
		Edit:   nodeEdit,
		Update: nodeUpdate,
	}
}
89217
func NewLabelController(service *goa.Service, db application.DB, config LabelControllerConfiguration) *LabelController {
	return &LabelController{
		Controller: service.NewController("LabelController"),
		db:         db,
		config:     config}
}
847800
func (e *Environ) ControllerInstances(ctx envcontext.ProviderCallContext, controllerUUID string) ([]instance.Id, error) {
	tags := map[string]string{
		tags.JujuController:   controllerUUID,
		tags.JujuIsController: "true",
	}
	instances, err := e.allInstances(ctx, tags)
	if err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return nil, errors.Trace(err)
	}
	ids := []instance.Id{}
	for _, val := range instances {
		ids = append(ids, val.Id())
	}
	return ids, nil
}
836201
func AddControllerType(moduleSource *Module, controllerType reflect.Type, methods []*MethodType) (newControllerType *ControllerType) {
	if moduleSource == nil {
		moduleSource = appModule
	}

	newControllerType = &ControllerType{ModuleSource: moduleSource, Type: controllerType, Methods: methods, ControllerIndexes: findControllers(controllerType)}
	newControllerType.ControllerEvents = NewControllerTypeEvents(newControllerType)
	newControllerType.Namespace = moduleSource.Namespace()
	controllerName := newControllerType.Name()

	// Store the first controller only in the controllers map with the unmapped namespace.
	if _, found := controllers[controllerName]; !found {
		controllers[controllerName] = newControllerType
		newControllerType.ModuleSource.AddController(newControllerType)
		if newControllerType.ModuleSource == appModule {
			// Add the controller mapping into the global namespace
			controllers[newControllerType.ShortName()] = newControllerType
		}
	} else {
		controllerLog.Errorf("Error, attempt to register duplicate controller as %s", controllerName)
	}
	controllerLog.Debugf("Registered controller: %s", controllerName)

	return
}
725595
func (e *executor) Controller(t *api.Task) (exec.Controller, error) {
	// Get the node description from the executor field
	e.mutex.Lock()
	nodeDescription := e.node
	e.mutex.Unlock()
	ctlr, err := newController(e.client, nodeDescription, t, secrets.Restrict(e.secrets, t))
	if err != nil {
		return nil, err
	}

	return ctlr, nil
}
1281428
func NewController(options ControllerOptions) (*Controller, error) {
	c := &Controller{
		options: options,
	}
	c.closing = make(chan chan error)

	if len(options.ServicedEndpoint) <= 0 {
		return nil, ErrInvalidEndpoint
	}

	// Load keys
	keyshutdown := make(chan interface{})
	go func() {
		// This is a ridiculous shutdown pattern I'll follow for the sake of
		// not destabilizing the controller this late in a release.
		// TODO: Make this not stupid
		errc := <-c.closing
		close(keyshutdown)
		errc <- nil
	}()

	go auth.WatchDelegateKeyFile(containerDelegateKeyFile, keyshutdown)
	go auth.WatchTokenFile(containerTokenFile, keyshutdown)

	// Load the delegate keys and auth tokens first so there's no race btwn starting the watcher routines
	//    and making the first RPC call in getService()
	<-auth.WaitForDelegateKeys(nil)
	<-auth.WaitForAuthToken(nil)

	// get service
	instanceID, err := strconv.Atoi(options.Service.InstanceID)
	if err != nil {
		glog.Errorf("Invalid instance from instanceID:%s", options.Service.InstanceID)
		return c, fmt.Errorf("Invalid instance from instanceID:%s", options.Service.InstanceID)
	}
	service, tenantID, svcPath, err := getService(options.ServicedEndpoint, options.Service.ID, instanceID)
	if err != nil {
		glog.Errorf("%+v", err)
		glog.Errorf("Invalid service from serviceID:%s", options.Service.ID)
		return c, ErrInvalidService
	}
	c.healthChecks = service.HealthChecks
	c.tenantID = tenantID
	options.ServiceNamePath = svcPath

	if service.PIDFile != "" {
		if strings.HasPrefix(service.PIDFile, "exec ") {
			cmd := service.PIDFile[5:len(service.PIDFile)]
			out, err := exec.Command("sh", "-c", cmd).Output()
			if err != nil {
				glog.Errorf("Unable to run command '%s'", cmd)
			} else {
				c.PIDFile = strings.Trim(string(out), "\n ")
			}
		} else {
			c.PIDFile = service.PIDFile
		}
	}

	// create config files
	if err := setupConfigFiles(service); err != nil {
		glog.Errorf("Could not setup config files error:%s", err)
		return c, fmt.Errorf("container: invalid ConfigFiles error:%s", err)
	}

	// get host id
	c.hostID, err = getAgentHostID(options.ServicedEndpoint)
	if err != nil {
		glog.Errorf("Invalid hostID")
		return c, ErrInvalidHostID
	}

	if options.Logforwarder.Enabled && len(service.LogConfigs) > 0 {
		if err := setupLogstashFiles(c.hostID, options.HostIPs, options.ServiceNamePath, service,
			options.Service.InstanceID, options.Logforwarder); err != nil {
			glog.Errorf("Could not setup logstash files error:%s", err)
			return c, fmt.Errorf("container: invalid LogStashFiles error:%s", err)
		}

		logforwarder, exited, err := subprocess.New(time.Second,
			nil,
			options.Logforwarder.Path,
			"-e", // Log to stderr
			"-c", options.Logforwarder.ConfigFile)
		if err != nil {
			return nil, err
		}
		c.logforwarder = logforwarder
		c.logforwarderExited = exited
	}

	//build metric redirect url -- assumes 8444 is port mapped
	metricRedirect := options.Metric.RemoteEndoint
	if len(metricRedirect) == 0 {
		glog.V(1).Infof("container.Controller does not have metric forwarding")
	} else if !options.MetricForwarding {
		glog.V(1).Infof("Not forwarding metrics for this container (%v)", c.tenantID)
	} else {
		if len(c.tenantID) <= 0 {
			return nil, ErrInvalidTenantID
		}
		if len(c.hostID) <= 0 {
			return nil, ErrInvalidHostID
		}
		if len(options.Service.ID) <= 0 {
			return nil, ErrInvalidServiceID
		}

		metricRedirect += "?controlplane_tenant_id=" + c.tenantID
		metricRedirect += "&controlplane_service_id=" + options.Service.ID
		metricRedirect += "&controlplane_host_id=" + c.hostID
		metricRedirect += "&controlplane_instance_id=" + options.Service.InstanceID

		//build and serve the container metric forwarder
		forwarder, err := NewMetricForwarder(options.Metric.Address, metricRedirect)
		if err != nil {
			return c, err
		}
		c.metricForwarder = forwarder

		// setup network stats
		destination := fmt.Sprintf("http://localhost%s/api/metrics/store", options.Metric.Address)
		glog.Infof("pushing network stats to: %s", destination)
		go statReporter(destination, time.Second*15)
	}

	// Keep a copy of the service prerequisites in the Controller object.
	c.prereqs = service.Prereqs

	// set up the zookeeper client
	c.zkInfo, err = getAgentZkInfo(options.ServicedEndpoint)
	if err != nil {
		glog.Errorf("Invalid zk info: %v", err)
		return c, err
	}
	glog.Infof(" c.zkInfo: %+v", c.zkInfo)

	// endpoints are created at the root level (not pool aware)
	rootBasePath := ""
	zClient, err := coordclient.New("zookeeper", c.zkInfo.ZkDSN, rootBasePath, nil)
	if err != nil {
		glog.Errorf("failed create a new coordclient: %v", err)
		return c, err
	}

	zzk.InitializeLocalClient(zClient)

	// get endpoints
	opts := ContainerEndpointsOptions{
		HostID:               c.hostID,
		TenantID:             c.tenantID,
		InstanceID:           instanceID,
		IsShell:              os.Getenv("SERVICED_IS_SERVICE_SHELL") == "true",
		TCPMuxPort:           uint16(options.Mux.Port),
		UseTLS:               !options.Mux.DisableTLS,
		VirtualAddressSubnet: options.VirtualAddressSubnet,
	}
	c.endpoints, err = NewContainerEndpoints(service, opts)
	if err != nil {
		return c, err
	}

	// CC Rest API proxy
	c.ccApiProxy = newServicedApiProxy()

	// check command
	glog.Infof("command: %v [%d]", options.Service.Command, len(options.Service.Command))
	if len(options.Service.Command) < 1 {
		glog.Errorf("Invalid commandif ")
		return c, ErrInvalidCommand
	}

	return c, nil
}