// NewDockerCgroupNetController returns a handle to call functions on the cgroup net_cls controller
6441
func NewDockerCgroupNetController() Cgroupnetcls {

	controller := &netCls{
		markchan:         make(chan uint64),
		ReleaseAgentPath: "",
		TriremePath:      "",
	}

	return controller
}
309061
func NewController(bk *buckets.Bucket) *Controller {
	prefix := map[string]*buckets.PrefixScanner{
		"/mon": bk.NewPrefixScanner([]byte("/mon")),
		"/tue": bk.NewPrefixScanner([]byte("/tue")),
		"/wed": bk.NewPrefixScanner([]byte("/wed")),
		"/thu": bk.NewPrefixScanner([]byte("/thu")),
		"/fri": bk.NewPrefixScanner([]byte("/fri")),
		"/sat": bk.NewPrefixScanner([]byte("/sat")),
		"/sun": bk.NewPrefixScanner([]byte("/sun")),
	}
	return &Controller{bk, prefix}
}
1335940
func NewDockerClientFromConfig(config *ClientConfig) libdocker.Interface {
	if config != nil {
		// Create docker client.
		client := libdocker.ConnectToDockerOrDie(
			config.DockerEndpoint,
			config.RuntimeRequestTimeout,
			config.ImagePullProgressDeadline,
			config.WithTraceDisabled,
			config.EnableSleep,
		)
		return client
	}

	return nil
}
157594
func (i *Instance) cgroupChainRules(cfg *ACLInfo) [][]string {

	// Rules for older distros (eg RH 6.9/Ubuntu 14.04), due to absence of
	// cgroup match modules, source ports are used  to trap outgoing traffic.
	if i.isLegacyKernel && (cfg.PUType == common.HostNetworkPU || cfg.PUType == common.HostPU) {
		return i.legacyPuChainRules(
			cfg.ContextID,
			cfg.AppChain,
			cfg.NetChain,
			cfg.CgroupMark,
			cfg.TCPPorts,
			cfg.UDPPorts,
			cfg.ProxyPort,
			cfg.ProxySetName,
			cfg.AppSection,
			cfg.NetSection,
			cfg.PUType,
		)
	}

	tmpl := template.Must(template.New(cgroupCaptureTemplate).Funcs(template.FuncMap{
		"isUDPPorts": func() bool {
			return cfg.UDPPorts != "0"
		},
		"isTCPPorts": func() bool {
			return cfg.TCPPorts != "0"
		},
		"isHostPU": func() bool {
			return cfg.AppSection == HostModeOutput && cfg.NetSection == HostModeInput
		},
	}).Parse(cgroupCaptureTemplate))

	rules, err := extractRulesFromTemplate(tmpl, cfg)
	if err != nil {
		zap.L().Warn("unable to extract rules", zap.Error(err))
	}

	return append(rules, i.proxyRules(cfg)...)
}
773404
func (n *Network) NetworkGroupRunner() ifrit.Runner {
	members := grouper.Members{
		{Name: "brokers", Runner: n.BrokerGroupRunner()},
		{Name: "orderers", Runner: n.OrdererGroupRunner()},
		{Name: "peers", Runner: n.PeerGroupRunner()},
	}
	return grouper.NewOrdered(syscall.SIGTERM, members)
}
841476
func NewPVProtectionController(pvInformer coreinformers.PersistentVolumeInformer, cl clientset.Interface, storageObjectInUseProtectionFeatureEnabled bool) *Controller {
	e := &Controller{
		client:                              cl,
		queue:                               workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "pvprotection"),
		storageObjectInUseProtectionEnabled: storageObjectInUseProtectionFeatureEnabled,
	}
	if cl != nil && cl.CoreV1().RESTClient().GetRateLimiter() != nil {
		metrics.RegisterMetricAndTrackRateLimiterUsage("persistentvolume_protection_controller", cl.CoreV1().RESTClient().GetRateLimiter())
	}

	e.pvLister = pvInformer.Lister()
	e.pvListerSynced = pvInformer.Informer().HasSynced
	pvInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: e.pvAddedUpdated,
		UpdateFunc: func(old, new interface{}) {
			e.pvAddedUpdated(new)
		},
	})

	return e
}
649556
func (mr *MockCgroupnetclsMockRecorder) Creategroup(cgroupname interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Creategroup", reflect.TypeOf((*MockCgroupnetcls)(nil).Creategroup), cgroupname)
}
676553
func NewGroupCreateType(Description string) *GroupCreateType {
	s := new(GroupCreateType)
	s.Description = Description
	return s
}
1321201
func getCgroupInfo(cadvisor cadvisor.Interface, containerName string, updateStats bool) (*cadvisorapiv2.ContainerInfo, error) {
	var maxAge *time.Duration
	if updateStats {
		age := 0 * time.Second
		maxAge = &age
	}
	infoMap, err := cadvisor.ContainerInfoV2(containerName, cadvisorapiv2.RequestOptions{
		IdType:    cadvisorapiv2.TypeName,
		Count:     2, // 2 samples are needed to compute "instantaneous" CPU
		Recursive: false,
		MaxAge:    maxAge,
	})
	if err != nil {
		return nil, fmt.Errorf("failed to get container info for %q: %v", containerName, err)
	}
	if len(infoMap) != 1 {
		return nil, fmt.Errorf("unexpected number of containers: %v", len(infoMap))
	}
	info := infoMap[containerName]
	return &info, nil
}
1160035
func newGroup(client *Client, id int32) *GroupNode {
	return &GroupNode{
		client: client,
		id:     id,
	}
}
980391
func New(client *containerd.Client, root, cgroup string, networkProviders map[pb.NetMode]network.Provider) executor.Executor {
	// clean up old hosts/resolv.conf file. ignore errors
	os.RemoveAll(filepath.Join(root, "hosts"))
	os.RemoveAll(filepath.Join(root, "resolv.conf"))

	return containerdExecutor{
		client:           client,
		root:             root,
		networkProviders: networkProviders,
		cgroupParent:     cgroup,
	}
}
1316899
func NewDockerRegistryServiceController(secrets informers.SecretInformer, serviceInformer informers.ServiceInformer, cl kclientset.Interface, options DockerRegistryServiceControllerOptions) *DockerRegistryServiceController {
	e := &DockerRegistryServiceController{
		client:                 cl,
		additionalRegistryURLs: options.AdditionalRegistryURLs,
		clusterDNSSuffix:       options.ClusterDNSSuffix,
		dockercfgController:    options.DockercfgController,
		registryLocationQueue:  workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()),
		secretsToUpdate:        workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()),
		dockerURLsInitialized:  options.DockerURLsInitialized,
	}

	// we're only watching two of these, but we already watch all services for the service serving cert signer
	// and this correctly handles namespaces coming and going
	serviceInformer.Informer().AddEventHandler(
		cache.FilteringResourceEventHandler{
			FilterFunc: func(obj interface{}) bool {
				switch t := obj.(type) {
				case *v1.Service:
					for _, location := range serviceLocations {
						if t.Namespace == location.namespace && t.Name == location.name {
							return true
						}
					}
				}
				return false
			},
			Handler: cache.ResourceEventHandlerFuncs{
				AddFunc: func(obj interface{}) {
					e.enqueueRegistryLocationQueue()
				},
				UpdateFunc: func(old, cur interface{}) {
					e.enqueueRegistryLocationQueue()
				},
				DeleteFunc: func(obj interface{}) {
					e.enqueueRegistryLocationQueue()
				},
			}},
	)
	e.servicesSynced = serviceInformer.Informer().HasSynced
	e.serviceLister = serviceInformer.Lister()

	e.syncRegistryLocationHandler = e.syncRegistryLocationChange

	e.secretCache = secrets.Informer().GetIndexer()
	e.secretsSynced = secrets.Informer().GetController().HasSynced
	e.syncSecretHandler = e.syncSecretUpdate

	return e
}
310849
func NewCGroupFingerprint(logger log.Logger) Fingerprint {
	f := &CGroupFingerprint{
		logger:             logger.Named("cgroup"),
		lastState:          cgroupUnavailable,
		mountPointDetector: &DefaultMountPointDetector{},
	}
	return f
}
824477
func newContainerConfig(ctx context.Context, owner, id string, spec *specs.Spec) (*hcsshim.ContainerConfig, error) {
	var (
		conf = &hcsshim.ContainerConfig{
			SystemType: "Container",
			Name:       id,
			Owner:      owner,
			HostName:   spec.Hostname,
		}
	)

	if spec.Windows.Network != nil {
		conf.AllowUnqualifiedDNSQuery = spec.Windows.Network.AllowUnqualifiedDNSQuery
		conf.EndpointList = spec.Windows.Network.EndpointList
		conf.NetworkSharedContainerName = spec.Windows.Network.NetworkSharedContainerName
		if spec.Windows.Network.DNSSearchList != nil {
			conf.DNSSearchList = strings.Join(spec.Windows.Network.DNSSearchList, ",")
		}
	}

	return conf, nil
}
748093
func (env *azureEnviron) initResourceGroup(ctx context.ProviderCallContext, controllerUUID string, controller bool) error {
	resourceGroupsClient := resources.GroupsClient{env.resources}

	env.mu.Lock()
	tags := tags.ResourceTags(
		names.NewModelTag(env.config.Config.UUID()),
		names.NewControllerTag(controllerUUID),
		env.config,
	)
	env.mu.Unlock()

	logger.Debugf("creating resource group %q", env.resourceGroup)
	sdkCtx := stdcontext.Background()
	if _, err := resourceGroupsClient.CreateOrUpdate(sdkCtx, env.resourceGroup, resources.Group{
		Location: to.StringPtr(env.location),
		Tags:     *to.StringMapPtr(tags),
	}); err != nil {
		return errorutils.HandleCredentialError(errors.Annotate(err, "creating resource group"), ctx)
	}

	if !controller {
		// When we create a resource group for a non-controller model,
		// we must create the common resources up-front. This is so
		// that parallel deployments do not affect dynamic changes,
		// e.g. those made by the firewaller. For the controller model,
		// we fold the creation of these resources into the bootstrap
		// machine's deployment.
		if err := env.createCommonResourceDeployment(ctx, tags, nil); err != nil {
			return errors.Trace(err)
		}
	}

	// New models are not given a storage account. Initialise the
	// storage account pointer to a pointer to a nil pointer, so
	// "getStorageAccount" avoids making an API call.
	env.storageAccount = new(*storage.Account)

	return nil
}
1011050
func NewEngineGroup(args1 interface{}, args2 interface{}, policies ...GroupPolicy) (*EngineGroup, error) {
	var eg EngineGroup
	if len(policies) > 0 {
		eg.policy = policies[0]
	} else {
		eg.policy = RoundRobinPolicy()
	}

	driverName, ok1 := args1.(string)
	conns, ok2 := args2.([]string)
	if ok1 && ok2 {
		engines := make([]*Engine, len(conns))
		for i, conn := range conns {
			engine, err := NewEngine(driverName, conn)
			if err != nil {
				return nil, err
			}
			engine.engineGroup = &eg
			engines[i] = engine
		}

		eg.Engine = engines[0]
		eg.slaves = engines[1:]
		return &eg, nil
	}

	master, ok3 := args1.(*Engine)
	slaves, ok4 := args2.([]*Engine)
	if ok3 && ok4 {
		master.engineGroup = &eg
		for i := 0; i < len(slaves); i++ {
			slaves[i].engineGroup = &eg
		}
		eg.Engine = master
		eg.slaves = slaves
		return &eg, nil
	}
	return nil, ErrParamsType
}
397860
func (ac *APIController) EndpointGroupCreate(endpointGroup *contivModel.EndpointGroup) error {
	log.Infof("Received EndpointGroupCreate: %+v", endpointGroup)

	// Find the tenant
	tenant := contivModel.FindTenant(endpointGroup.TenantName)
	if tenant == nil {
		return core.Errorf("Tenant not found")
	}
	// Find the network
	nwObjKey := endpointGroup.TenantName + ":" + endpointGroup.NetworkName
	network := contivModel.FindNetwork(nwObjKey)
	if network == nil {
		return core.Errorf("Network %s not found", endpointGroup.NetworkName)
	}
	// If there is a Network with the same name as this endpointGroup, reject.
	nameClash := contivModel.FindNetwork(endpointGroup.Key)
	if nameClash != nil {
		return core.Errorf("Network %s conflicts with the endpointGroup name",
			nameClash.NetworkName)
	}
	// create the endpoint group state
	err := master.CreateEndpointGroup(endpointGroup.TenantName, endpointGroup.NetworkName,
		endpointGroup.GroupName, endpointGroup.IpPool, endpointGroup.CfgdTag)
	if err != nil {
		log.Errorf("Error creating endpoint group %+v. Err: %v", endpointGroup, err)
		return err
	}
	// for each policy create an epg policy Instance
	for _, policyName := range endpointGroup.Policies {
		policyKey := GetpolicyKey(endpointGroup.TenantName, policyName)
		// find the policy
		policy := contivModel.FindPolicy(policyKey)
		if policy == nil {
			log.Errorf("Could not find policy %s", policyName)
			endpointGroupCleanup(endpointGroup)
			return core.Errorf("Policy not found")
		}

		// attach policy to epg
		err = master.PolicyAttach(endpointGroup, policy)
		if err != nil {
			log.Errorf("Error attaching policy %s to epg %s", policyName, endpointGroup.Key)
			endpointGroupCleanup(endpointGroup)
			return err
		}

		// establish Links
		modeldb.AddLinkSet(&policy.LinkSets.EndpointGroups, endpointGroup)
		modeldb.AddLinkSet(&endpointGroup.LinkSets.Policies, policy)

		// Write the policy
		err = policy.Write()
		if err != nil {
			endpointGroupCleanup(endpointGroup)
			return err
		}
	}

	// If endpoint group is to be attached to any netprofile, then attach the netprofile and create links and linksets.
	if endpointGroup.NetProfile != "" {
		profileKey := GetNetprofileKey(endpointGroup.TenantName, endpointGroup.NetProfile)
		netprofile := contivModel.FindNetprofile(profileKey)
		if netprofile == nil {
			log.Errorf("Error finding netprofile: %s", profileKey)
			return errors.New("netprofile not found")
		}

		// attach NetProfile to epg
		err = master.UpdateEndpointGroup(netprofile.Bandwidth, endpointGroup.GroupName, endpointGroup.TenantName, netprofile.DSCP, netprofile.Burst)
		if err != nil {
			log.Errorf("Error attaching NetProfile %s to epg %s", endpointGroup.NetProfile, endpointGroup.Key)
			endpointGroupCleanup(endpointGroup)
			return err
		}

		//establish links (epg - netprofile)
		modeldb.AddLink(&endpointGroup.Links.NetProfile, netprofile)
		//establish linksets (Netprofile - epg)
		modeldb.AddLinkSet(&netprofile.LinkSets.EndpointGroups, endpointGroup)

		//Write the attached Netprofile to modeldb
		err = netprofile.Write()
		if err != nil {
			endpointGroupCleanup(endpointGroup)
			return err
		}
	}

	// Setup external contracts this EPG might have.
	err = setupExternalContracts(endpointGroup, endpointGroup.ExtContractsGrps)
	if err != nil {
		log.Errorf("Error setting up external contracts for epg %s", endpointGroup.Key)
		endpointGroupCleanup(endpointGroup)
		return err
	}

	// Setup links
	modeldb.AddLink(&endpointGroup.Links.Network, network)
	modeldb.AddLink(&endpointGroup.Links.Tenant, tenant)
	modeldb.AddLinkSet(&network.LinkSets.EndpointGroups, endpointGroup)
	modeldb.AddLinkSet(&tenant.LinkSets.EndpointGroups, endpointGroup)

	// Save the tenant and network since we added the links
	err = network.Write()
	if err != nil {
		endpointGroupCleanup(endpointGroup)
		return err
	}

	err = tenant.Write()
	if err != nil {
		endpointGroupCleanup(endpointGroup)
		return err
	}

	return nil
}