// Builds all networks, meant to be called after the data is loaded into the struct attributes
320980
func (fw *FirewallSSO) init(ctx context.Context) error {
	for _, net := range fw.Networks {
		err := net.init(ctx)
		if err != nil {
			return err
		}
	}
	return nil
}
1216290
func (c *Client) CreateNetwork(p *CreateNetworkParameter) (*Network, error) {
	obj, err := c.Request("createNetwork", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Network), err
}
249736
func (n *switchingNetworking) Subnets(instId instance.Id, subnetIds []network.Id) ([]network.SubnetInfo, error) {
	if err := n.initNetworking(); err != nil {
		return nil, errors.Trace(err)
	}
	return n.networking.Subnets(instId, subnetIds)
}
535238
func (d *driver) populateNetworks() error {
	kvol, err := d.store.List(datastore.Key(macvlanPrefix), &configuration{})
	if err != nil && err != datastore.ErrKeyNotFound {
		return fmt.Errorf("failed to get macvlan network configurations from store: %v", err)
	}
	// If empty it simply means no macvlan networks have been created yet
	if err == datastore.ErrKeyNotFound {
		return nil
	}
	for _, kvo := range kvol {
		config := kvo.(*configuration)
		if err = d.createNetwork(config); err != nil {
			logrus.Warnf("Could not create macvlan network for id %s from persistent state", config.ID)
		}
	}

	return nil
}
37167
func (b *serverBuilder) Build() (*ServerBuildResult, error) {

	// start
	b.callEventHandlerIfExists(ServerBuildOnStart)
	b.currentBuildValue = &ServerBuildValue{}
	b.currentBuildResult = &ServerBuildResult{}

	if len(b.errors) > 0 {
		return b.currentBuildResult, b.getFlattenErrors()
	}

	// build parameter
	if err := b.buildParams(); err != nil {
		return b.currentBuildResult, err
	}

	// create server
	b.callEventHandlerIfExists(ServerBuildOnCreateServerBefore)
	if err := b.createServer(); err != nil {
		return b.currentBuildResult, err
	}
	b.callEventHandlerIfExists(ServerBuildOnCreateServerAfter)

	// create disks
	if err := b.createDisks(); err != nil {
		return b.currentBuildResult, err
	}

	if !b.canAutoBoot() {
		// connect exists disks
		if err := b.connectDisks(); err != nil {
			return b.currentBuildResult, err
		}

		// insert cdrom
		if b.isoImageID > 0 {
			b.callEventHandlerIfExists(ServerBuildOnInsertCDROMBefore)
			if err := b.insertCDROM(); err != nil {
				return b.currentBuildResult, err
			}
			b.callEventHandlerIfExists(ServerBuildOnInsertCDROMAfter)
		}

		// connect packet filters
		if err := b.connectPacketFilters(); err != nil {
			return b.currentBuildResult, err
		}

		// boot server
		if b.bootAfterCreate {
			b.callEventHandlerIfExists(ServerBuildOnBootBefore)
			if err := b.bootServer(); err != nil {
				return b.currentBuildResult, err
			}
			b.callEventHandlerIfExists(ServerBuildOnBootAfter)
		}
	}

	if len(b.displayIPAddresses) > 0 {
		for i, nic := range b.currentBuildResult.Server.Interfaces {
			ifID := nic.ID
			displayIP := b.displayIPAddresses[i]
			if displayIP != "" {
				if _, err := b.client.InterfaceSetDisplayIPAddress(ifID, displayIP); err != nil {
					return b.currentBuildResult, err
				}
				// reload server
				server, err := b.client.ServerRead(b.currentBuildResult.Server.ID)
				if err != nil {
					return b.currentBuildResult, err
				}
				b.currentBuildResult.Server = server
			}
		}
	}

	// complete
	b.callEventHandlerIfExists(ServerBuildOnComplete)
	return b.currentBuildResult, nil
}
1002927
func CreateNetwork(obj *Network) error {
	// Validate parameters
	err := ValidateNetwork(obj)
	if err != nil {
		log.Errorf("ValidateNetwork retruned error for: %+v. Err: %v", obj, err)
		return err
	}

	// Check if we handle this object
	if objCallbackHandler.NetworkCb == nil {
		log.Errorf("No callback registered for network object")
		return errors.New("Invalid object type")
	}

	saveObj := obj

	collections.networkMutex.Lock()
	key := collections.networks[obj.Key]
	collections.networkMutex.Unlock()

	// Check if object already exists
	if key != nil {
		// Perform Update callback
		err = objCallbackHandler.NetworkCb.NetworkUpdate(collections.networks[obj.Key], obj)
		if err != nil {
			log.Errorf("NetworkUpdate retruned error for: %+v. Err: %v", obj, err)
			return err
		}

		// save the original object after update
		collections.networkMutex.Lock()
		saveObj = collections.networks[obj.Key]
		collections.networkMutex.Unlock()
	} else {
		// save it in cache
		collections.networkMutex.Lock()
		collections.networks[obj.Key] = obj
		collections.networkMutex.Unlock()

		// Perform Create callback
		err = objCallbackHandler.NetworkCb.NetworkCreate(obj)
		if err != nil {
			log.Errorf("NetworkCreate retruned error for: %+v. Err: %v", obj, err)
			collections.networkMutex.Lock()
			delete(collections.networks, obj.Key)
			collections.networkMutex.Unlock()
			return err
		}
	}

	// Write it to modeldb
	collections.networkMutex.Lock()
	err = saveObj.Write()
	collections.networkMutex.Unlock()
	if err != nil {
		log.Errorf("Error saving network %s to db. Err: %v", saveObj.Key, err)
		return err
	}

	return nil
}
342509
func (daemon *Daemon) getAllNetworks() []libnetwork.Network {
	c := daemon.netController
	if c == nil {
		return nil
	}
	return c.Networks()
}
613504
func BuildConnectionStringWithChroot(nodes []string, chroot string) string {
	return fmt.Sprintf("%s%s", strings.Join(nodes, ","), chroot)
}
560391
func Networks(namespace Namespace, networks networkMap, servicesNetworks map[string]struct{}) (map[string]types.NetworkCreate, []string) {
	if networks == nil {
		networks = make(map[string]composetypes.NetworkConfig)
	}

	externalNetworks := []string{}
	result := make(map[string]types.NetworkCreate)
	for internalName := range servicesNetworks {
		network := networks[internalName]
		if network.External.External {
			externalNetworks = append(externalNetworks, network.Name)
			continue
		}

		createOpts := types.NetworkCreate{
			Labels:     AddStackLabel(namespace, network.Labels),
			Driver:     network.Driver,
			Options:    network.DriverOpts,
			Internal:   network.Internal,
			Attachable: network.Attachable,
		}

		if network.Ipam.Driver != "" || len(network.Ipam.Config) > 0 {
			createOpts.IPAM = &networktypes.IPAM{}
		}

		if network.Ipam.Driver != "" {
			createOpts.IPAM.Driver = network.Ipam.Driver
		}
		for _, ipamConfig := range network.Ipam.Config {
			config := networktypes.IPAMConfig{
				Subnet: ipamConfig.Subnet,
			}
			createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
		}

		networkName := namespace.Scope(internalName)
		if network.Name != "" {
			networkName = network.Name
		}
		result[networkName] = createOpts
	}

	return result, externalNetworks
}
1066882
func initNetworkBootstrappers(s *server) ([]discovery.NetworkPeerBootstrapper, error) {
	srvrLog.Infof("Initializing peer network bootstrappers!")

	var bootStrappers []discovery.NetworkPeerBootstrapper

	// First, we'll create an instance of the ChannelGraphBootstrapper as
	// this can be used by default if we've already partially seeded the
	// network.
	chanGraph := autopilot.ChannelGraphFromDatabase(s.chanDB.ChannelGraph())
	graphBootstrapper, err := discovery.NewGraphBootstrapper(chanGraph)
	if err != nil {
		return nil, err
	}
	bootStrappers = append(bootStrappers, graphBootstrapper)

	// If this isn't simnet mode, then one of our additional bootstrapping
	// sources will be the set of running DNS seeds.
	if !cfg.Bitcoin.SimNet || !cfg.Litecoin.SimNet {
		dnsSeeds, ok := chainDNSSeeds[*activeNetParams.GenesisHash]

		// If we have a set of DNS seeds for this chain, then we'll add
		// it as an additional bootstrapping source.
		if ok {
			srvrLog.Infof("Creating DNS peer bootstrapper with "+
				"seeds: %v", dnsSeeds)

			dnsBootStrapper := discovery.NewDNSSeedBootstrapper(
				dnsSeeds, cfg.net,
			)
			bootStrappers = append(bootStrappers, dnsBootStrapper)
		}
	}

	return bootStrappers, nil
}
391913
func (b *PlanBuilder) Build(node ast.Node) (Plan, error) {
	b.optFlag = flagPrunColumns
	switch x := node.(type) {
	case *ast.AdminStmt:
		return b.buildAdmin(x)
	case *ast.DeallocateStmt:
		return &Deallocate{Name: x.Name}, nil
	case *ast.DeleteStmt:
		return b.buildDelete(x)
	case *ast.ExecuteStmt:
		return b.buildExecute(x)
	case *ast.ExplainStmt:
		return b.buildExplain(x)
	case *ast.ExplainForStmt:
		return b.buildExplainFor(x)
	case *ast.TraceStmt:
		return b.buildTrace(x)
	case *ast.InsertStmt:
		return b.buildInsert(x)
	case *ast.LoadDataStmt:
		return b.buildLoadData(x)
	case *ast.LoadStatsStmt:
		return b.buildLoadStats(x), nil
	case *ast.PrepareStmt:
		return b.buildPrepare(x), nil
	case *ast.SelectStmt:
		return b.buildSelect(x)
	case *ast.UnionStmt:
		return b.buildUnion(x)
	case *ast.UpdateStmt:
		return b.buildUpdate(x)
	case *ast.ShowStmt:
		return b.buildShow(x)
	case *ast.DoStmt:
		return b.buildDo(x)
	case *ast.SetStmt:
		return b.buildSet(x)
	case *ast.AnalyzeTableStmt:
		return b.buildAnalyze(x)
	case *ast.BinlogStmt, *ast.FlushStmt, *ast.UseStmt,
		*ast.BeginStmt, *ast.CommitStmt, *ast.RollbackStmt, *ast.CreateUserStmt, *ast.SetPwdStmt,
		*ast.GrantStmt, *ast.DropUserStmt, *ast.AlterUserStmt, *ast.RevokeStmt, *ast.KillStmt, *ast.DropStatsStmt,
		*ast.GrantRoleStmt, *ast.RevokeRoleStmt, *ast.SetRoleStmt, *ast.SetDefaultRoleStmt:
		return b.buildSimple(node.(ast.StmtNode))
	case ast.DDLNode:
		return b.buildDDL(x)
	case *ast.CreateBindingStmt:
		return b.buildCreateBindPlan(x)
	case *ast.DropBindingStmt:
		return b.buildDropBindPlan(x)
	case *ast.ChangeStmt:
		return b.buildChange(x)
	}
	return nil, ErrUnsupportedType.GenWithStack("Unsupported type %T", node)
}
1111080
func (_m *APIClient) NetworkCreate(ctx context.Context, name string, options types.NetworkCreate) (types.NetworkCreateResponse, error) {
	ret := _m.Called(ctx, name, options)

	var r0 types.NetworkCreateResponse
	if rf, ok := ret.Get(0).(func(context.Context, string, types.NetworkCreate) types.NetworkCreateResponse); ok {
		r0 = rf(ctx, name, options)
	} else {
		r0 = ret.Get(0).(types.NetworkCreateResponse)
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, string, types.NetworkCreate) error); ok {
		r1 = rf(ctx, name, options)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
1323266
func (b *APILoadBalancerBuilder) Build(c *fi.ModelBuilderContext) error {
	// Configuration where an ELB fronts the API
	if !b.UseLoadBalancerForAPI() {
		return nil
	}

	lbSpec := b.Cluster.Spec.API.LoadBalancer
	if lbSpec == nil {
		// Skipping API ELB creation; not requested in Spec
		return nil
	}

	switch lbSpec.Type {
	case kops.LoadBalancerTypeInternal, kops.LoadBalancerTypePublic:
	// OK

	default:
		return fmt.Errorf("unhandled LoadBalancer type %q", lbSpec.Type)
	}

	// Compute the subnets - only one per zone, and then break ties based on chooseBestSubnetForELB
	var elbSubnets []*awstasks.Subnet
	{
		subnetsByZone := make(map[string][]*kops.ClusterSubnetSpec)
		for i := range b.Cluster.Spec.Subnets {
			subnet := &b.Cluster.Spec.Subnets[i]

			switch subnet.Type {
			case kops.SubnetTypePublic, kops.SubnetTypeUtility:
				if lbSpec.Type != kops.LoadBalancerTypePublic {
					continue
				}

			case kops.SubnetTypePrivate:
				if lbSpec.Type != kops.LoadBalancerTypeInternal {
					continue
				}

			default:
				return fmt.Errorf("subnet %q had unknown type %q", subnet.Name, subnet.Type)
			}

			subnetsByZone[subnet.Zone] = append(subnetsByZone[subnet.Zone], subnet)
		}

		for zone, subnets := range subnetsByZone {
			subnet := b.chooseBestSubnetForELB(zone, subnets)

			elbSubnets = append(elbSubnets, b.LinkToSubnet(subnet))
		}
	}

	var elb *awstasks.LoadBalancer
	{
		loadBalancerName := b.GetELBName32("api")

		idleTimeout := LoadBalancerDefaultIdleTimeout
		if lbSpec.IdleTimeoutSeconds != nil {
			idleTimeout = time.Second * time.Duration(*lbSpec.IdleTimeoutSeconds)
		}

		listeners := map[string]*awstasks.LoadBalancerListener{
			"443": {InstancePort: 443},
		}

		if lbSpec.SSLCertificate != "" {
			listeners["443"] = &awstasks.LoadBalancerListener{InstancePort: 443, SSLCertificateID: lbSpec.SSLCertificate}
		}

		if lbSpec.SecurityGroupOverride != nil {
			glog.V(1).Infof("WARNING: You are overwriting the Load Balancers, Security Group. When this is done you are responsible for ensure the correct rules!")
		}

		tags := b.CloudTags(loadBalancerName, false)
		for k, v := range b.Cluster.Spec.CloudLabels {
			tags[k] = v
		}
		// Override the returned name to be the expected ELB name
		tags["Name"] = "api." + b.ClusterName()

		elb = &awstasks.LoadBalancer{
			Name:      fi.String("api." + b.ClusterName()),
			Lifecycle: b.Lifecycle,

			LoadBalancerName: fi.String(loadBalancerName),
			SecurityGroups: []*awstasks.SecurityGroup{
				b.LinkToELBSecurityGroup("api"),
			},
			Subnets:   elbSubnets,
			Listeners: listeners,

			// Configure fast-recovery health-checks
			HealthCheck: &awstasks.LoadBalancerHealthCheck{
				Target:             fi.String("SSL:443"),
				Timeout:            fi.Int64(5),
				Interval:           fi.Int64(10),
				HealthyThreshold:   fi.Int64(2),
				UnhealthyThreshold: fi.Int64(2),
			},

			ConnectionSettings: &awstasks.LoadBalancerConnectionSettings{
				IdleTimeout: fi.Int64(int64(idleTimeout.Seconds())),
			},

			Tags: tags,
		}

		switch lbSpec.Type {
		case kops.LoadBalancerTypeInternal:
			elb.Scheme = fi.String("internal")
		case kops.LoadBalancerTypePublic:
			elb.Scheme = nil
		default:
			return fmt.Errorf("unknown elb Type: %q", lbSpec.Type)
		}

		c.AddTask(elb)
	}

	// Create security group for API ELB
	var lbSG *awstasks.SecurityGroup
	{
		lbSG = &awstasks.SecurityGroup{
			Name:             fi.String(b.ELBSecurityGroupName("api")),
			Lifecycle:        b.SecurityLifecycle,
			Description:      fi.String("Security group for api ELB"),
			RemoveExtraRules: []string{"port=443"},
			VPC:              b.LinkToVPC(),
		}
		lbSG.Tags = b.CloudTags(*lbSG.Name, false)

		if lbSpec.SecurityGroupOverride != nil {
			lbSG.ID = fi.String(*lbSpec.SecurityGroupOverride)
			lbSG.Shared = fi.Bool(true)
		}

		c.AddTask(lbSG)
	}

	// Allow traffic from ELB to egress freely
	{
		t := &awstasks.SecurityGroupRule{
			Name:          fi.String("api-elb-egress"),
			Lifecycle:     b.SecurityLifecycle,
			CIDR:          fi.String("0.0.0.0/0"),
			Egress:        fi.Bool(true),
			SecurityGroup: lbSG,
		}
		c.AddTask(t)
	}

	// Allow traffic into the ELB from KubernetesAPIAccess CIDRs
	{
		for _, cidr := range b.Cluster.Spec.KubernetesAPIAccess {
			t := &awstasks.SecurityGroupRule{
				Name:          fi.String("https-api-elb-" + cidr),
				Lifecycle:     b.SecurityLifecycle,
				CIDR:          fi.String(cidr),
				FromPort:      fi.Int64(443),
				Protocol:      fi.String("tcp"),
				SecurityGroup: lbSG,
				ToPort:        fi.Int64(443),
			}
			c.AddTask(t)

			// Allow ICMP traffic required for PMTU discovery
			c.AddTask(&awstasks.SecurityGroupRule{
				Name:          fi.String("icmp-pmtu-api-elb-" + cidr),
				Lifecycle:     b.SecurityLifecycle,
				CIDR:          fi.String(cidr),
				FromPort:      fi.Int64(3),
				Protocol:      fi.String("icmp"),
				SecurityGroup: lbSG,
				ToPort:        fi.Int64(4),
			})
		}
	}

	// Add precreated additional security groups to the ELB
	{
		for _, id := range b.Cluster.Spec.API.LoadBalancer.AdditionalSecurityGroups {
			t := &awstasks.SecurityGroup{
				Name:      fi.String(id),
				Lifecycle: b.SecurityLifecycle,
				ID:        fi.String(id),
				Shared:    fi.Bool(true),
			}
			if err := c.EnsureTask(t); err != nil {
				return err
			}
			elb.SecurityGroups = append(elb.SecurityGroups, t)
		}
	}

	masterGroups, err := b.GetSecurityGroups(kops.InstanceGroupRoleMaster)
	if err != nil {
		return err
	}

	// Allow HTTPS to the master instances from the ELB
	{
		for _, masterGroup := range masterGroups {
			suffix := masterGroup.Suffix
			c.AddTask(&awstasks.SecurityGroupRule{
				Name:          fi.String(fmt.Sprintf("https-elb-to-master%s", suffix)),
				Lifecycle:     b.SecurityLifecycle,
				FromPort:      fi.Int64(443),
				Protocol:      fi.String("tcp"),
				SecurityGroup: masterGroup.Task,
				SourceGroup:   lbSG,
				ToPort:        fi.Int64(443),
			})
		}
	}

	if dns.IsGossipHostname(b.Cluster.Name) || b.UsePrivateDNS() {
		// Ensure the ELB hostname is included in the TLS certificate,
		// if we're not going to use an alias for it
		// TODO: I don't love this technique for finding the task by name & modifying it
		masterKeypairTask, found := c.Tasks["Keypair/master"]
		if !found {
			return fmt.Errorf("keypair/master task not found")
		}
		masterKeypair := masterKeypairTask.(*fitasks.Keypair)
		masterKeypair.AlternateNameTasks = append(masterKeypair.AlternateNameTasks, elb)
	}

	// When Spotinst Elastigroups are used, there is no need to create
	// a separate task for the attachment of the load balancer since this
	// is already done as part of the Elastigroup's creation, if needed.
	if !featureflag.Spotinst.Enabled() {
		for _, ig := range b.MasterInstanceGroups() {
			c.AddTask(&awstasks.LoadBalancerAttachment{
				Name:             fi.String("api-" + ig.ObjectMeta.Name),
				Lifecycle:        b.Lifecycle,
				AutoscalingGroup: b.LinkToAutoscalingGroup(ig),
				LoadBalancer:     b.LinkToELB("api"),
			})
		}
	}

	return nil

}
31814
func (p *pruner) buildGraph(options PrunerOptions) kerrors.Aggregate {
	p.g = genericgraph.New()

	var errs []error

	errs = append(errs, p.addImagesToGraph(options.Images)...)
	errs = append(errs, p.addImageStreamsToGraph(options.Streams, options.LimitRanges)...)
	errs = append(errs, p.addPodsToGraph(options.Pods)...)
	errs = append(errs, p.addReplicationControllersToGraph(options.RCs)...)
	errs = append(errs, p.addBuildConfigsToGraph(options.BCs)...)
	errs = append(errs, p.addBuildsToGraph(options.Builds)...)
	errs = append(errs, p.addDaemonSetsToGraph(options.DSs)...)
	errs = append(errs, p.addDeploymentsToGraph(options.Deployments)...)
	errs = append(errs, p.addDeploymentConfigsToGraph(options.DCs)...)
	errs = append(errs, p.addReplicaSetsToGraph(options.RSs)...)

	return kerrors.NewAggregate(errs)
}
1105725
func (nDB *NetworkDB) addNetworkNode(nid string, nodeName string) {
	nodes := nDB.networkNodes[nid]
	for _, node := range nodes {
		if node == nodeName {
			return
		}
	}

	nDB.networkNodes[nid] = append(nDB.networkNodes[nid], nodeName)
}
1068422
func (s *NetworkService) NewListNetworksParams() *ListNetworksParams {
	p := &ListNetworksParams{}
	p.p = make(map[string]interface{})
	return p
}
1365649
func SplitNetworks(network *net.IPNet, newsize uint) ([]*net.IPNet, error) {
	var ret []*net.IPNet
	oldsize, _ := network.Mask.Size()

	// use a stack to avoid a recurvive function
	ret = append(ret, network)
	for i := oldsize; i < int(newsize); i++ {
		var tmp []*net.IPNet

		// parse network array to split all of them in two
		for _, n := range ret {
			one, two := SplitNetworkInTwo(n)
			tmp = append(tmp, one)
			tmp = append(tmp, two)
		}
		ret = tmp
	}

	return ret, nil
}