// CreateGraph creates a new graph with given name and options, and opens a connection to it.
// If a graph with given name already exists within the database, a DuplicateError is returned.
976217
func (d *database) CreateGraph(ctx context.Context, name string, options *CreateGraphOptions) (Graph, error) {
	input := createGraphOptions{
		Name: name,
	}
	if options != nil {
		input.OrphanVertexCollections = options.OrphanVertexCollections
		input.EdgeDefinitions = options.EdgeDefinitions
		input.IsSmart = options.IsSmart
		if options.SmartGraphAttribute != "" || options.NumberOfShards != 0 {
			input.Options = &createGraphAdditionalOptions{
				SmartGraphAttribute: options.SmartGraphAttribute,
				NumberOfShards:      options.NumberOfShards,
			}
		}
	}
	req, err := d.conn.NewRequest("POST", path.Join(d.relPath(), "_api/gharial"))
	if err != nil {
		return nil, WithStack(err)
	}
	if _, err := req.SetBody(input); err != nil {
		return nil, WithStack(err)
	}
	resp, err := d.conn.Do(ctx, req)
	if err != nil {
		return nil, WithStack(err)
	}
	if err := resp.CheckStatus(201, 202); err != nil {
		return nil, WithStack(err)
	}
	g, err := newGraph(name, d)
	if err != nil {
		return nil, WithStack(err)
	}
	return g, nil
}
1084372
func NewGraph(defs ...Definition) Graph {
	defMap := make(map[interface{}]Definition, len(defs))
	for _, def := range defs {
		defMap[def.Ptr()] = def
	}
	return &graph{
		definitions: defMap,
	}
}
504270
func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error {
	return d.create(id, parent, opts, true)
}
1358585
func (network *HNSNetwork) Create() (*HNSNetwork, error) {
	operation := "Create"
	title := "hcsshim::HNSNetwork::" + operation
	logrus.Debugf(title+" id=%s", network.Id)

	for _, subnet := range network.Subnets {
		if (subnet.AddressPrefix != "") && (subnet.GatewayAddress == "") {
			return nil, errors.New("network create error, subnet has address prefix but no gateway specified")
		}
	}

	jsonString, err := json.Marshal(network)
	if err != nil {
		return nil, err
	}
	return HNSNetworkRequest("POST", "", string(jsonString))
}
970097
func (d *database) Graph(ctx context.Context, name string) (Graph, error) {
	escapedName := pathEscape(name)
	req, err := d.conn.NewRequest("GET", path.Join(d.relPath(), "_api/gharial", escapedName))
	if err != nil {
		return nil, WithStack(err)
	}
	resp, err := d.conn.Do(ctx, req)
	if err != nil {
		return nil, WithStack(err)
	}
	if err := resp.CheckStatus(200); err != nil {
		return nil, WithStack(err)
	}
	g, err := newGraph(name, d)
	if err != nil {
		return nil, WithStack(err)
	}
	return g, nil
}
189057
func (c *Context) Graph(typ GraphType, opts *ContextGraphOpts) (*Graph, tfdiags.Diagnostics) {
	if opts == nil {
		opts = &ContextGraphOpts{Validate: true}
	}

	log.Printf("[INFO] terraform: building graph: %s", typ)
	switch typ {
	case GraphTypeApply:
		return (&ApplyGraphBuilder{
			Config:     c.config,
			Changes:    c.changes,
			State:      c.state,
			Components: c.components,
			Schemas:    c.schemas,
			Targets:    c.targets,
			Destroy:    c.destroy,
			Validate:   opts.Validate,
		}).Build(addrs.RootModuleInstance)

	case GraphTypeValidate:
		// The validate graph is just a slightly modified plan graph
		fallthrough
	case GraphTypePlan:
		// Create the plan graph builder
		p := &PlanGraphBuilder{
			Config:     c.config,
			State:      c.state,
			Components: c.components,
			Schemas:    c.schemas,
			Targets:    c.targets,
			Validate:   opts.Validate,
		}

		// Some special cases for other graph types shared with plan currently
		var b GraphBuilder = p
		switch typ {
		case GraphTypeValidate:
			b = ValidateGraphBuilder(p)
		}

		return b.Build(addrs.RootModuleInstance)

	case GraphTypePlanDestroy:
		return (&DestroyPlanGraphBuilder{
			Config:     c.config,
			State:      c.state,
			Components: c.components,
			Schemas:    c.schemas,
			Targets:    c.targets,
			Validate:   opts.Validate,
		}).Build(addrs.RootModuleInstance)

	case GraphTypeRefresh:
		return (&RefreshGraphBuilder{
			Config:     c.config,
			State:      c.state,
			Components: c.components,
			Schemas:    c.schemas,
			Targets:    c.targets,
			Validate:   opts.Validate,
		}).Build(addrs.RootModuleInstance)

	case GraphTypeEval:
		return (&EvalGraphBuilder{
			Config:     c.config,
			State:      c.state,
			Components: c.components,
			Schemas:    c.schemas,
		}).Build(addrs.RootModuleInstance)

	default:
		// Should never happen, because the above is exhaustive for all graph types.
		panic(fmt.Errorf("unsupported graph type %s", typ))
	}
}
1263883
func CreateNoError(t *testing.T, ctx context.Context, client client.APIClient, name string, ops ...func(*types.NetworkCreate)) string { // nolint: golint
	t.Helper()

	name, err := createNetwork(ctx, client, name, ops...)
	assert.NilError(t, err)
	return name
}
1024899
func StartGraphAPI(name string, restBase string) error {
	graphPlugin := newGraphPlugin(name)
	if _, _, err := startServer(name, restBase, 0, graphPlugin); err != nil {
		return err
	}

	return nil
}
226618
func (r *AppRepo) Create(app *App) error {
	if !utils.AppNamePattern.Match([]byte(app.Name)) {
		return ErrAppNameInvalid
	}

	if len(app.Name) > AppNameMax {
		return ErrAppNameTooLong
	}

	if _, err := r.DB.NamedExec(`INSERT INTO apps (name) VALUES (:name)`, app); err != nil {
		return err
	}

	newApp, err := r.GetByName(app.Name)
	if err != nil {
		return err
	}

	app.ID = newApp.ID
	app.CreatedAt = newApp.CreatedAt
	app.UpdatedAt = newApp.UpdatedAt

	return nil
}
95322
func (s *memoryStore) NewGraph(ctx context.Context, id string) (storage.Graph, error) {
	g := &memory{
		id:    id,
		idx:   make(map[string]*triple.Triple, initialAllocation),
		idxS:  make(map[string]map[string]*triple.Triple, initialAllocation),
		idxP:  make(map[string]map[string]*triple.Triple, initialAllocation),
		idxO:  make(map[string]map[string]*triple.Triple, initialAllocation),
		idxSP: make(map[string]map[string]*triple.Triple, initialAllocation),
		idxPO: make(map[string]map[string]*triple.Triple, initialAllocation),
		idxSO: make(map[string]map[string]*triple.Triple, initialAllocation),
	}

	s.rwmu.Lock()
	defer s.rwmu.Unlock()
	if _, ok := s.graphs[id]; ok {
		return nil, fmt.Errorf("memory.NewGraph(%q): graph already exists", id)
	}
	s.graphs[id] = g
	return g, nil
}
806070
func (g *Graph) MakeNode() Node {
	newNode := &node{index: len(g.nodes)}
	newNode.container = Node{node: newNode, Value: new(interface{})}
	g.nodes = append(g.nodes, newNode)
	return newNode.container
}
897114
func (d *ChainDescriber) MakeGraph() (osgraph.Graph, error) {
	g := osgraph.New()

	loaders := []GraphLoader{}
	for namespace := range d.namespaces {
		klog.V(4).Infof("Loading build configurations from %q", namespace)
		loaders = append(loaders, &bcLoader{namespace: namespace, lister: d.c})
	}
	loadingFuncs := []func() error{}
	for _, loader := range loaders {
		loadingFuncs = append(loadingFuncs, loader.Load)
	}

	if errs := parallel.Run(loadingFuncs...); len(errs) > 0 {
		return g, utilerrors.NewAggregate(errs)
	}

	for _, loader := range loaders {
		loader.AddToGraph(g)
	}

	buildedges.AddAllInputOutputEdges(g)

	return g, nil
}
116510
func createCredentialGraph(ctx context.Context, credBody *PlaintextCredential,
	parent registry.CredentialGraph, sigID *identity.ID, encID *identity.ID,
	kp *crypto.KeyPairs, ct *registry.ClaimTree, client *registry.Client,
	engine *crypto.Engine, g *secure.Guard) (*registry.CredentialGraphV2, error) {

	pathExp, err := credBody.PathExp.WithInstance("*")
	if err != nil {
		return nil, err
	}

	keyringBody := primitive.NewKeyring(credBody.OrgID, credBody.ProjectID, pathExp)
	if parent != nil {
		keyringBody.Previous = parent.GetKeyring().GetID()
		keyringBody.KeyringVersion = parent.KeyringVersion() + 1
	}

	keyring, err := engine.SignedKeyring(ctx, keyringBody, sigID, &kp.Signature)
	if err != nil {
		return nil, err
	}

	mek, err := g.Random(64)
	defer mek.Destroy()
	if err != nil {
		return nil, err
	}

	subjects, err := getKeyringMembers(ctx, client, credBody.OrgID)
	if err != nil {
		return nil, err
	}

	// use their public key to encrypt the mek with a random nonce.
	members := []registry.KeyringMember{}
	for _, subject := range subjects {
		for _, id := range subject.KeyOwnerIDs() {
			// For this user/mtoken, find their public encryption key
			enc, err := ct.FindActive(&id, primitive.EncryptionKeyType)
			if err == registry.ErrMissingKeyForOwner {
				// If we didn't find an active key, don't encode this
				// user/token in the keyring, but keep going.
				continue
			}
			if err != nil {
				return nil, err
			}
			encPubKey := enc.PublicKey

			encmek, nonce, err := engine.Box(ctx, mek, &kp.Encryption, []byte(*encPubKey.Body.Key.Value))
			if err != nil {
				return nil, err
			}

			key := &primitive.KeyringMemberKey{
				Algorithm: crypto.EasyBox,
				Nonce:     base64.New(nonce),
				Value:     base64.New(encmek),
			}

			member, err := newV2KeyringMember(ctx, engine, credBody.OrgID, keyring.ID,
				encPubKey.Body.OwnerID, encPubKey.ID, encID, sigID, key, kp)
			if err != nil {
				return nil, err
			}

			members = append(members, *member)
		}
	}

	graph := registry.CredentialGraphV2{
		KeyringSectionV2: registry.KeyringSectionV2{
			Keyring: keyring,
			Claims:  []envelope.KeyringMemberClaim{},
			Members: members,
		},
	}

	return &graph, nil
}
1006562
func (d *driver) createNetwork(config *configuration) error {
	networkList := d.getNetworks()
	for _, nw := range networkList {
		if config.Parent == nw.config.Parent {
			return fmt.Errorf("network %s is already using parent interface %s",
				getDummyName(stringid.TruncateID(nw.config.ID)), config.Parent)
		}
	}
	if !parentExists(config.Parent) {
		// if the --internal flag is set, create a dummy link
		if config.Internal {
			err := createDummyLink(config.Parent, getDummyName(stringid.TruncateID(config.ID)))
			if err != nil {
				return err
			}
			config.CreatedSlaveLink = true
			// notify the user in logs they have limited communications
			if config.Parent == getDummyName(stringid.TruncateID(config.ID)) {
				logrus.Debugf("Empty -o parent= and --internal flags limit communications to other containers inside of network: %s",
					config.Parent)
			}
		} else {
			// if the subinterface parent_iface.vlan_id checks do not pass, return err.
			//  a valid example is 'eth0.10' for a parent iface 'eth0' with a vlan id '10'
			err := createVlanLink(config.Parent)
			if err != nil {
				return err
			}
			// if driver created the networks slave link, record it for future deletion
			config.CreatedSlaveLink = true
		}
	}
	n := &network{
		id:        config.ID,
		driver:    d,
		endpoints: endpointTable{},
		config:    config,
	}
	// add the *network
	d.addNetwork(n)

	return nil
}
465889
func (g *MutableDirectedGraph) Copy() *MutableDirectedGraph {
	newGraph := NewMutableDirectedGraph(g.rootNodeNames)

	// copy nodes
	for _, n := range g.Nodes() {
		newNode, ok := n.(*Node)
		if !ok {
			continue
		}

		if err := newGraph.AddNode(newNode); err != nil {
			// this should never happen: the only error that could occur is a node name collision,
			// which would imply that the original graph that we are copying had node-name collisions.
			panic(fmt.Errorf("unexpected error while copying graph: %v", err))
		}
	}

	// copy edges
	for _, n := range g.Nodes() {
		node, ok := n.(*Node)
		if !ok {
			continue
		}

		if _, exists := newGraph.NodeByName(node.UniqueName); !exists {
			continue
		}

		from := g.From(n)
		for _, to := range from {
			if newGraph.HasEdgeFromTo(n, to) {
				continue
			}

			newGraph.SetEdge(simple.Edge{F: n, T: to})
		}
	}

	return newGraph
}
628873
func (s *Statement) AddGraph(g string) {
	s.graphNames = append(s.graphNames, g)
}
417965
func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
	if _, err := d.getNetwork(id); err == nil {
		return types.ForbiddenErrorf("network %s exists", id)
	}

	genData, ok := option[netlabel.GenericData].(map[string]string)
	if !ok {
		return fmt.Errorf("Unknown generic data option")
	}

	// Parse and validate the config. It should not conflict with existing networks' config
	config, err := d.parseNetworkOptions(id, genData)
	if err != nil {
		return err
	}

	err = config.processIPAM(id, ipV4Data, ipV6Data)
	if err != nil {
		return err
	}

	err = d.createNetwork(config)

	if err != nil {
		return err
	}

	// A non blank hnsid indicates that the network was discovered
	// from HNS. No need to call HNS if this network was discovered
	// from HNS
	if config.HnsID == "" {
		subnets := []hcsshim.Subnet{}

		for _, ipData := range ipV4Data {
			subnet := hcsshim.Subnet{
				AddressPrefix: ipData.Pool.String(),
			}

			if ipData.Gateway != nil {
				subnet.GatewayAddress = ipData.Gateway.IP.String()
			}

			subnets = append(subnets, subnet)
		}

		network := &hcsshim.HNSNetwork{
			Name:               config.Name,
			Type:               d.name,
			Subnets:            subnets,
			DNSServerList:      config.DNSServers,
			DNSSuffix:          config.DNSSuffix,
			MacPools:           config.MacPools,
			SourceMac:          config.SourceMac,
			NetworkAdapterName: config.NetworkAdapterName,
		}

		if config.VLAN != 0 {
			vlanPolicy, err := json.Marshal(hcsshim.VlanPolicy{
				Type: "VLAN",
				VLAN: config.VLAN,
			})

			if err != nil {
				return err
			}
			network.Policies = append(network.Policies, vlanPolicy)
		}

		if config.VSID != 0 {
			vsidPolicy, err := json.Marshal(hcsshim.VsidPolicy{
				Type: "VSID",
				VSID: config.VSID,
			})

			if err != nil {
				return err
			}
			network.Policies = append(network.Policies, vsidPolicy)
		}

		if network.Name == "" {
			network.Name = id
		}

		configurationb, err := json.Marshal(network)
		if err != nil {
			return err
		}

		configuration := string(configurationb)
		logrus.Debugf("HNSNetwork Request =%v Address Space=%v", configuration, subnets)

		hnsresponse, err := hcsshim.HNSNetworkRequest("POST", "", configuration)
		if err != nil {
			return err
		}

		config.HnsID = hnsresponse.Id
		genData[HNSID] = config.HnsID

	} else {
		// Delete any stale HNS endpoints for this network.
		if endpoints, err := hcsshim.HNSListEndpointRequest(); err == nil {
			for _, ep := range endpoints {
				if ep.VirtualNetwork == config.HnsID {
					logrus.Infof("Removing stale HNS endpoint %s", ep.Id)
					_, err = hcsshim.HNSEndpointRequest("DELETE", ep.Id, "")
					if err != nil {
						logrus.Warnf("Error removing HNS endpoint %s", ep.Id)
					}
				}
			}
		} else {
			logrus.Warnf("Error listing HNS endpoints for network %s", config.HnsID)
		}
	}

	n, err := d.getNetwork(id)
	if err != nil {
		return err
	}
	n.created = true
	return d.storeUpdate(config)
}