//DeDeploySysCCs is used in unit tests to stop and remove the system chaincodes before
//restarting them in the same process. This allows clean start of the system
//in the same process
333664
func (p *Provider) DeDeploySysCCs(chainID string, ccp ccprovider.ChaincodeProvider) {
	for _, sysCC := range p.SysCCs {
		deDeploySysCC(chainID, ccp, sysCC)
	}
}
334924
func DepriveMutiBreak(s string) string {
	re, _ := regexp.Compile(`([^\n\f\r\t 　 ]*)([ 　 ]*[\n\f\r\t]+[ 　 ]*)+`)
	return re.ReplaceAllString(s, "${1}\n")

}
401675
func (lscc *LifeCycleSysCC) getCCCode(ccname string, cdbytes []byte) (*pb.ChaincodeDeploymentSpec, []byte, error) {
	cd, err := lscc.getChaincodeData(ccname, cdbytes)
	if err != nil {
		return nil, nil, err
	}

	ccpack, err := lscc.Support.GetChaincodeFromLocalStorage(ccname, cd.Version)
	if err != nil {
		return nil, nil, InvalidDeploymentSpecErr(err.Error())
	}

	//this is the big test and the reason every launch should go through
	//getChaincode call. We validate the chaincode entry against the
	//the chaincode in FS
	if err = ccpack.ValidateCC(cd); err != nil {
		return nil, nil, InvalidCCOnFSError(err.Error())
	}

	//these are guaranteed to be non-nil because we got a valid ccpack
	depspec := ccpack.GetDepSpec()
	depspecbytes := ccpack.GetDepSpecBytes()

	return depspec, depspecbytes, nil
}
1317358
func (s *Switch) deleteCircuits(inKeys ...CircuitKey) error {
	return s.circuits.DeleteCircuits(inKeys...)
}
737274
func (containers Containers) stripProvisioningDuplicates() (deduplicated Containers) {
	seenProvisioningKeys := make(map[string]bool)
	for _, container := range containers {
		// for 2 containers that would the same provisioning
		// commands, the key should be equal
		key := container.BuildParams().Context() + "#" + container.Image()
		if _, ok := seenProvisioningKeys[key]; !ok {
			deduplicated = append(deduplicated, container)
			seenProvisioningKeys[key] = true
		}
	}
	return
}
288653
func (lscc *LifeCycleSysCC) getChaincodes(stub shim.ChaincodeStubInterface) pb.Response {
	// get all rows from LSCC
	itr, err := stub.GetStateByRange("", "")

	if err != nil {
		return shim.Error(err.Error())
	}
	defer itr.Close()

	// array to store metadata for all chaincode entries from LSCC
	var ccInfoArray []*pb.ChaincodeInfo

	for itr.HasNext() {
		response, err := itr.Next()
		if err != nil {
			return shim.Error(err.Error())
		}

		// CollectionConfig isn't ChaincodeData
		if privdata.IsCollectionConfigKey(response.Key) {
			continue
		}

		ccdata := &ccprovider.ChaincodeData{}
		if err = proto.Unmarshal(response.Value, ccdata); err != nil {
			return shim.Error(err.Error())
		}

		var path string
		var input string

		// if chaincode is not installed on the system we won't have
		// data beyond name and version
		ccpack, err := lscc.Support.GetChaincodeFromLocalStorage(ccdata.Name, ccdata.Version)
		if err == nil {
			path = ccpack.GetDepSpec().GetChaincodeSpec().ChaincodeId.Path
			input = ccpack.GetDepSpec().GetChaincodeSpec().Input.String()
		}

		// add this specific chaincode's metadata to the array of all chaincodes
		ccInfo := &pb.ChaincodeInfo{Name: ccdata.Name, Version: ccdata.Version, Path: path, Input: input, Escc: ccdata.Escc, Vscc: ccdata.Vscc}
		ccInfoArray = append(ccInfoArray, ccInfo)
	}
	// add array with info about all instantiated chaincodes to the query
	// response proto
	cqr := &pb.ChaincodeQueryResponse{Chaincodes: ccInfoArray}

	cqrbytes, err := proto.Marshal(cqr)
	if err != nil {
		return shim.Error(err.Error())
	}

	return shim.Success(cqrbytes)
}
1111699
func deduplicate(sds []IdentityAndSignature) []IdentityAndSignature {
	ids := make(map[string]struct{})
	result := make([]IdentityAndSignature, 0, len(sds))
	for i, sd := range sds {
		identity, err := sd.Identity()
		if err != nil {
			cauthdslLogger.Errorf("Principal deserialization failure (%s) for identity %d", err, i)
			continue
		}
		key := identity.GetIdentifier().Mspid + identity.GetIdentifier().Id

		if _, ok := ids[key]; ok {
			cauthdslLogger.Warningf("De-duplicating identity [%s] at index %d in signature set", key, i)
		} else {
			result = append(result, sd)
			ids[key] = struct{}{}
		}
	}
	return result
}
688819
func (sub *Subscription) ChaincodeDeployDone(succeeded bool) {
	// Run a new goroutine which would dispatch a single pending update.
	// This is to prevent any ledger locks being obtained during the state query
	// to affect the locks held while invoking this method by the ledger itself.
	// We first lock and then take the pending update, to preserve order.
	sub.Lock()
	go func() {
		defer func() {
			sub.pendingUpdates = nil
			sub.Unlock()
		}()
		// If we haven't succeeded in deploying the chaincode, just skip the update
		if !succeeded {
			Logger.Errorf("Chaincode deploy for updates %v failed", sub.pendingUpdates)
			return
		}
		for _, update := range sub.pendingUpdates {
			sub.processPendingUpdate(update)
		}
	}()
}
633429
func (w *Watcher) getDeploysImpl(ws memdb.WatchSet, state *state.StateStore) (interface{}, uint64, error) {

	iter, err := state.Deployments(ws)
	if err != nil {
		return nil, 0, err
	}

	var deploys []*structs.Deployment
	for {
		raw := iter.Next()
		if raw == nil {
			break
		}
		deploy := raw.(*structs.Deployment)
		deploys = append(deploys, deploy)
	}

	// Use the last index that affected the deployment table
	index, err := state.Index("deployment")
	if err != nil {
		return nil, 0, err
	}

	return deploys, index, nil
}
134010
func parseSeccompArgs(patchSeccompMode string, patchSeccompSet string) (*types.Isolator, error) {
	// Parse mode flag and additional keyed arguments.
	var errno, mode string
	args := strings.Split(patchSeccompMode, ",")
	for _, a := range args {
		kv := strings.Split(a, "=")
		switch len(kv) {
		case 1:
			// mode, either "remove" or "retain"
			mode = kv[0]
		case 2:
			// k=v argument, only "errno" allowed for now
			if kv[0] == "errno" {
				errno = kv[1]
			} else {
				return nil, fmt.Errorf("invalid seccomp-mode optional argument: %s", a)
			}
		default:
			return nil, fmt.Errorf("cannot parse seccomp-mode argument: %s", a)
		}
	}

	// Instantiate an Isolator with the content specified by the --seccomp-set parameter.
	var err error
	var seccomp types.AsIsolator
	switch mode {
	case "remove":
		seccomp, err = types.NewLinuxSeccompRemoveSet(errno, strings.Split(patchSeccompSet, ",")...)
	case "retain":
		seccomp, err = types.NewLinuxSeccompRetainSet(errno, strings.Split(patchSeccompSet, ",")...)
	default:
		err = fmt.Errorf("unknown seccomp mode %s", mode)
	}
	if err != nil {
		return nil, fmt.Errorf("cannot parse seccomp isolator: %s", err)
	}
	seccompIsolator, err := seccomp.AsIsolator()
	if err != nil {
		return nil, err
	}
	return seccompIsolator, nil
}
71656
func (w *MockGCWorker) DeleteRanges(ctx context.Context, safePoint uint64) error {
	logutil.Logger(ctx).Error("deleteRanges is called")
	return w.worker.deleteRanges(ctx, safePoint)
}
604918
func (c *container) debugGCS() {
	if c == nil || c.isWindows || c.hcsContainer == nil {
		return
	}
	cfg := opengcs.Config{
		Uvm:               c.hcsContainer,
		UvmTimeoutSeconds: 600,
	}
	cfg.DebugGCS()
}
707311
func (vs *VSphere) cleanUpDummyVMs(dummyVMPrefix string) {
	// Create context
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	for {
		time.Sleep(CleanUpDummyVMRoutineInterval * time.Minute)
		vsi, err := vs.getVSphereInstanceForServer(vs.cfg.Workspace.VCenterIP, ctx)
		if err != nil {
			klog.V(4).Infof("Failed to get VSphere instance with err: %+v. Retrying again...", err)
			continue
		}
		dc, err := vclib.GetDatacenter(ctx, vsi.conn, vs.cfg.Workspace.Datacenter)
		if err != nil {
			klog.V(4).Infof("Failed to get the datacenter: %s from VC. err: %+v", vs.cfg.Workspace.Datacenter, err)
			continue
		}
		// Get the folder reference for global working directory where the dummy VM needs to be created.
		vmFolder, err := dc.GetFolderByPath(ctx, vs.cfg.Workspace.Folder)
		if err != nil {
			klog.V(4).Infof("Unable to get the kubernetes folder: %q reference. err: %+v", vs.cfg.Workspace.Folder, err)
			continue
		}
		// A write lock is acquired to make sure the cleanUp routine doesn't delete any VM's created by ongoing PVC requests.
		cleanUpDummyVMs := func() {
			cleanUpDummyVMLock.Lock()
			defer cleanUpDummyVMLock.Unlock()
			err = diskmanagers.CleanUpDummyVMs(ctx, vmFolder, dc)
			if err != nil {
				klog.V(4).Infof("Unable to clean up dummy VM's in the kubernetes cluster: %q. err: %+v", vs.cfg.Workspace.Folder, err)
			}
		}
		cleanUpDummyVMs()
	}
}
1229591
func CleanUpDummyVMs(ctx context.Context, folder *vclib.Folder, dc *vclib.Datacenter) error {
	vmList, err := folder.GetVirtualMachines(ctx)
	if err != nil {
		klog.V(4).Infof("Failed to get virtual machines in the kubernetes cluster: %s, err: %+v", folder.InventoryPath, err)
		return err
	}
	if vmList == nil || len(vmList) == 0 {
		klog.Errorf("No virtual machines found in the kubernetes cluster: %s", folder.InventoryPath)
		return fmt.Errorf("No virtual machines found in the kubernetes cluster: %s", folder.InventoryPath)
	}
	var dummyVMList []*vclib.VirtualMachine
	// Loop through VM's in the Kubernetes cluster to find dummy VM's
	for _, vm := range vmList {
		vmName, err := vm.ObjectName(ctx)
		if err != nil {
			klog.V(4).Infof("Unable to get name from VM with err: %+v", err)
			continue
		}
		if strings.HasPrefix(vmName, vclib.DummyVMPrefixName) {
			vmObj := vclib.VirtualMachine{VirtualMachine: object.NewVirtualMachine(dc.Client(), vm.Reference()), Datacenter: dc}
			dummyVMList = append(dummyVMList, &vmObj)
		}
	}
	for _, vm := range dummyVMList {
		err = vm.DeleteVM(ctx)
		if err != nil {
			klog.V(4).Infof("Unable to delete dummy VM with err: %+v", err)
			continue
		}
	}
	return nil
}
1237256
func resetFlags() {
	flags = &pflag.FlagSet{}

	flags.StringVarP(&chaincodeLang, "lang", "l", "golang",
		fmt.Sprintf("Language the %s is written in", chainFuncName))
	flags.StringVarP(&chaincodeCtorJSON, "ctor", "c", "{}",
		fmt.Sprintf("Constructor message for the %s in JSON format", chainFuncName))
	flags.StringVarP(&chaincodePath, "path", "p", common.UndefinedParamValue,
		fmt.Sprintf("Path to %s", chainFuncName))
	flags.StringVarP(&chaincodeName, "name", "n", common.UndefinedParamValue,
		fmt.Sprint("Name of the chaincode"))
	flags.StringVarP(&chaincodeVersion, "version", "v", common.UndefinedParamValue,
		fmt.Sprint("Version of the chaincode specified in install/instantiate/upgrade commands"))
	flags.StringVarP(&chaincodeUsr, "username", "u", common.UndefinedParamValue,
		fmt.Sprint("Username for chaincode operations when security is enabled"))
	flags.StringVarP(&channelID, "channelID", "C", "",
		fmt.Sprint("The channel on which this command should be executed"))
	flags.StringVarP(&policy, "policy", "P", common.UndefinedParamValue,
		fmt.Sprint("The endorsement policy associated to this chaincode"))
	flags.StringVarP(&escc, "escc", "E", common.UndefinedParamValue,
		fmt.Sprint("The name of the endorsement system chaincode to be used for this chaincode"))
	flags.StringVarP(&vscc, "vscc", "V", common.UndefinedParamValue,
		fmt.Sprint("The name of the verification system chaincode to be used for this chaincode"))
	flags.BoolVarP(&getInstalledChaincodes, "installed", "", false,
		"Get the installed chaincodes on a peer")
	flags.BoolVarP(&getInstantiatedChaincodes, "instantiated", "", false,
		"Get the instantiated chaincodes on a channel")
	flags.StringVar(&collectionsConfigFile, "collections-config", common.UndefinedParamValue,
		fmt.Sprint("The fully qualified path to the collection JSON file including the file name"))
	flags.StringArrayVarP(&peerAddresses, "peerAddresses", "", []string{common.UndefinedParamValue},
		fmt.Sprint("The addresses of the peers to connect to"))
	flags.StringArrayVarP(&tlsRootCertFiles, "tlsRootCertFiles", "", []string{common.UndefinedParamValue},
		fmt.Sprint("If TLS is enabled, the paths to the TLS root cert files of the peers to connect to. The order and number of certs specified should match the --peerAddresses flag"))
	flags.StringVarP(&connectionProfile, "connectionProfile", "", common.UndefinedParamValue,
		fmt.Sprint("Connection profile that provides the necessary connection information for the network. Note: currently only supported for providing peer connection information"))
	flags.BoolVar(&waitForEvent, "waitForEvent", false,
		fmt.Sprint("Whether to wait for the event from each peer's deliver filtered service signifying that the 'invoke' transaction has been committed successfully"))
	flags.DurationVar(&waitForEventTimeout, "waitForEventTimeout", 30*time.Second,
		fmt.Sprint("Time to wait for the event from each peer's deliver filtered service signifying that the 'invoke' transaction has been committed successfully"))
}
302815
func (t *SubprocessTest) TearDown() {
	err := t.destroy()
	if err != nil {
		panic(err)
	}
}
924878
func createChaincodeDeployProposal(txh fab.TransactionHeader, deploy chaincodeProposalType, channelID string, chaincode chaincodeDeployRequest) (*fab.TransactionProposal, error) {

	// Generate arguments for deploy (channel, marshaled CCDS, marshaled chaincode policy, marshaled collection policy)
	args := [][]byte{}
	args = append(args, []byte(channelID))

	ccds := &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{
		Type: pb.ChaincodeSpec_GOLANG, ChaincodeId: &pb.ChaincodeID{Name: chaincode.Name, Path: chaincode.Path, Version: chaincode.Version},
		Input: &pb.ChaincodeInput{Args: chaincode.Args}}}
	ccdsBytes, err := protoutil.Marshal(ccds)
	if err != nil {
		return nil, errors.WithMessage(err, "marshal of chaincode deployment spec failed")
	}
	args = append(args, ccdsBytes)

	chaincodePolicyBytes, err := protoutil.Marshal(chaincode.Policy)
	if err != nil {
		return nil, errors.WithMessage(err, "marshal of chaincode policy failed")
	}
	args = append(args, chaincodePolicyBytes)

	args = append(args, []byte(escc))
	args = append(args, []byte(vscc))

	if chaincode.CollConfig != nil {
		collConfigBytes, err := proto.Marshal(&common.CollectionConfigPackage{Config: chaincode.CollConfig})
		if err != nil {
			return nil, errors.WithMessage(err, "marshal of collection policy failed")
		}
		args = append(args, collConfigBytes)
	}

	// Fcn is deploy or upgrade
	fcn := ""
	switch deploy {
	case InstantiateChaincode:
		fcn = lsccDeploy
	case UpgradeChaincode:
		fcn = lsccUpgrade
	default:
		return nil, errors.New("chaincode deployment type unknown")
	}

	cir := fab.ChaincodeInvokeRequest{
		ChaincodeID: lscc,
		Fcn:         fcn,
		Args:        args,
	}
	return txn.CreateChaincodeInvokeProposal(txh, cir)
}