// DefineImport defines the vm import command that will import packages and package types when wanted
186265
func DefineImport(e *vm.Env) {
	e.Define("import", func(source string) *vm.Env {
		methods, ok := Packages[source]
		if !ok {
			panic(fmt.Sprintf("package '%s' not found", source))
		}
		var err error
		pack := e.NewPackage(source)
		for methodName, methodValue := range methods {
			err = pack.Define(methodName, methodValue)
			if err != nil {
				panic(fmt.Sprintf("import Define error: %v", err))
			}
		}
		types, ok := PackageTypes[source]
		if ok {
			for typeName, typeValue := range types {
				err = pack.DefineType(typeName, typeValue)
				if err != nil {
					panic(fmt.Sprintf("import DefineType error: %v", err))
				}
			}
		}
		return pack
	})
}
79666
func (g *Generator) generateImports() {
	imports := make(map[GoImportPath]GoPackageName)
	for i, s := range g.file.Dependency {
		fd := g.fileByName(s)
		importPath := fd.importPath
		// Do not import our own package.
		if importPath == g.file.importPath {
			continue
		}
		// Do not import weak imports.
		if g.weak(int32(i)) {
			continue
		}
		// Do not import a package twice.
		if _, ok := imports[importPath]; ok {
			continue
		}
		// We need to import all the dependencies, even if we don't reference them,
		// because other code and tools depend on having the full transitive closure
		// of protocol buffer types in the binary.
		packageName := g.GoPackageName(importPath)
		if _, ok := g.usedPackages[importPath]; !ok {
			packageName = "_"
		}
		imports[importPath] = packageName
	}
	for importPath := range g.addedImports {
		imports[importPath] = g.GoPackageName(importPath)
	}
	// We almost always need a proto import.  Rather than computing when we
	// do, which is tricky when there's a plugin, just import it and
	// reference it later. The same argument applies to the fmt and math packages.
	g.P("import (")
	g.P(g.Pkg["fmt"] + ` "fmt"`)
	g.P(g.Pkg["math"] + ` "math"`)
	g.P(g.Pkg["proto"]+" ", GoImportPath(g.ImportPrefix)+"github.com/golang/protobuf/proto")
	for importPath, packageName := range imports {
		g.P(packageName, " ", GoImportPath(g.ImportPrefix)+importPath)
	}
	g.P(")")
	g.P()
	// TODO: may need to worry about uniqueness across plugins
	for _, p := range plugins {
		p.GenerateImports(g.file)
		g.P()
	}
	g.P("// Reference imports to suppress errors if they are not otherwise used.")
	g.P("var _ = ", g.Pkg["proto"], ".Marshal")
	g.P("var _ = ", g.Pkg["fmt"], ".Errorf")
	g.P("var _ = ", g.Pkg["math"], ".Inf")
	g.P()
}
1083037
func DefaultImporter(path string, srcDir string) *ast.Package {
	bpkg, err := build.Default.Import(path, srcDir, 0)
	if err != nil {
		return nil
	}
	goFiles := make(map[string]bool)
	for _, f := range bpkg.GoFiles {
		goFiles[f] = true
	}
	for _, f := range bpkg.CgoFiles {
		goFiles[f] = true
	}
	shouldInclude := func(d os.FileInfo) bool {
		return goFiles[d.Name()]
	}
	pkgs, err := parser.ParseDir(FileSet, bpkg.Dir, shouldInclude, 0, DefaultImportPathToName)
	if err != nil {
		if Debug {
			switch err := err.(type) {
			case scanner.ErrorList:
				for _, e := range err {
					debugp("\t%v: %s", e.Pos, e.Msg)
				}
			default:
				debugp("\terror parsing %s: %v", bpkg.Dir, err)
			}
		}
		return nil
	}
	if pkg := pkgs[bpkg.Name]; pkg != nil {
		return pkg
	}
	if Debug {
		debugp("package not found by ParseDir!")
	}
	return nil
}
270378
func (_class VMClass) Import(sessionID SessionRef, url string, sr SRRef, fullRestore bool, force bool) (_retval []VMRef, _err error) {
	_method := "VM.import"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_urlArg, _err := convertStringToXen(fmt.Sprintf("%s(%s)", _method, "url"), url)
	if _err != nil {
		return
	}
	_srArg, _err := convertSRRefToXen(fmt.Sprintf("%s(%s)", _method, "sr"), sr)
	if _err != nil {
		return
	}
	_fullRestoreArg, _err := convertBoolToXen(fmt.Sprintf("%s(%s)", _method, "full_restore"), fullRestore)
	if _err != nil {
		return
	}
	_forceArg, _err := convertBoolToXen(fmt.Sprintf("%s(%s)", _method, "force"), force)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _urlArg, _srArg, _fullRestoreArg, _forceArg)
	if _err != nil {
		return
	}
	_retval, _err = convertVMRefSetToGo(_method + " -> ", _result.Value)
	return
}
1335303
func NewImportNode(tpl Expr, alias string, p Pos) *ImportNode {
	return &ImportNode{p, TrimmableNode{}, tpl, alias}
}
795678
func NewImport(name, path string) *ImportSpec {
	return &ImportSpec{Name: name, Path: path}
}
509980
func (ctx *Context) findImportPath(dir string) (importPath, gopath string, err error) {
	dirResolved, err := filepath.EvalSymlinks(dir)
	if err != nil {
		return "", "", err
	}
	dirs := make([]string, 1)
	dirs = append(dirs, dir)
	if dir != dirResolved {
		dirs = append(dirs, dirResolved)
	}

	for _, gopath := range ctx.GopathList {
		for _, dir := range dirs {
			if pathos.FileHasPrefix(dir, gopath) || pathos.FileStringEquals(dir, gopath) {
				importPath = pathos.FileTrimPrefix(dir, gopath)
				importPath = pathos.SlashToImportPath(importPath)
				return importPath, gopath, nil
			}
		}
	}
	return "", "", ErrNotInGOPATH{dir}
}
534373
func (i *ImportRestriction) forbiddenImportsFor(pkg Package) []string {
	forbiddenImportSet := map[string]struct{}{}
	for _, packageToCheck := range append(pkg.Imports, append(pkg.TestImports, pkg.XTestImports...)...) {
		if !i.isAllowed(packageToCheck) {
			forbiddenImportSet[relativePackage(packageToCheck)] = struct{}{}
		}
	}

	var forbiddenImports []string
	for imp := range forbiddenImportSet {
		forbiddenImports = append(forbiddenImports, imp)
	}
	return forbiddenImports
}
697049
func NewImportCommand() *cobra.Command {
	var (
		clientConfig clientcmd.ClientConfig
		prune        bool
		dryRun       bool
	)
	var command = cobra.Command{
		Use:   "import SOURCE",
		Short: "Import Argo CD data from stdin (specify `-') or a file",
		Run: func(c *cobra.Command, args []string) {
			if len(args) != 1 {
				c.HelpFunc()(c, args)
				os.Exit(1)
			}
			config, err := clientConfig.ClientConfig()
			config.QPS = 100
			config.Burst = 50
			errors.CheckError(err)
			namespace, _, err := clientConfig.Namespace()
			errors.CheckError(err)
			acdClients := newArgoCDClientsets(config, namespace)

			var input []byte
			if in := args[0]; in == "-" {
				input, err = ioutil.ReadAll(os.Stdin)
			} else {
				input, err = ioutil.ReadFile(in)
			}
			errors.CheckError(err)
			var dryRunMsg string
			if dryRun {
				dryRunMsg = " (dry run)"
			}

			// pruneObjects tracks live objects and it's current resource version. any remaining
			// items in this map indicates the resource should be pruned since it no longer appears
			// in the backup
			pruneObjects := make(map[kube.ResourceKey]string)
			configMaps, err := acdClients.configMaps.List(metav1.ListOptions{})
			errors.CheckError(err)
			for _, cm := range configMaps.Items {
				cmName := cm.GetName()
				if cmName == common.ArgoCDConfigMapName || cmName == common.ArgoCDRBACConfigMapName {
					pruneObjects[kube.ResourceKey{Group: "", Kind: "ConfigMap", Name: cm.GetName()}] = cm.GetResourceVersion()
				}
			}
			secrets, err := acdClients.secrets.List(metav1.ListOptions{})
			errors.CheckError(err)
			for _, secret := range secrets.Items {
				if isArgoCDSecret(nil, secret) {
					pruneObjects[kube.ResourceKey{Group: "", Kind: "Secret", Name: secret.GetName()}] = secret.GetResourceVersion()
				}
			}
			applications, err := acdClients.applications.List(metav1.ListOptions{})
			errors.CheckError(err)
			for _, app := range applications.Items {
				pruneObjects[kube.ResourceKey{Group: "argoproj.io", Kind: "Application", Name: app.GetName()}] = app.GetResourceVersion()
			}
			projects, err := acdClients.projects.List(metav1.ListOptions{})
			errors.CheckError(err)
			for _, proj := range projects.Items {
				pruneObjects[kube.ResourceKey{Group: "argoproj.io", Kind: "AppProject", Name: proj.GetName()}] = proj.GetResourceVersion()
			}

			// Create or replace existing object
			objs, err := kube.SplitYAML(string(input))
			errors.CheckError(err)
			for _, obj := range objs {
				gvk := obj.GroupVersionKind()
				key := kube.ResourceKey{Group: gvk.Group, Kind: gvk.Kind, Name: obj.GetName()}
				resourceVersion, exists := pruneObjects[key]
				delete(pruneObjects, key)
				var dynClient dynamic.ResourceInterface
				switch obj.GetKind() {
				case "Secret":
					dynClient = acdClients.secrets
				case "ConfigMap":
					dynClient = acdClients.configMaps
				case "AppProject":
					dynClient = acdClients.projects
				case "Application":
					dynClient = acdClients.applications
				}
				if !exists {
					if !dryRun {
						_, err = dynClient.Create(obj, metav1.CreateOptions{})
						errors.CheckError(err)
					}
					fmt.Printf("%s/%s %s created%s\n", gvk.Group, gvk.Kind, obj.GetName(), dryRunMsg)
				} else {
					if !dryRun {
						obj.SetResourceVersion(resourceVersion)
						_, err = dynClient.Update(obj, metav1.UpdateOptions{})
						errors.CheckError(err)
					}
					fmt.Printf("%s/%s %s replaced%s\n", gvk.Group, gvk.Kind, obj.GetName(), dryRunMsg)
				}
			}

			// Delete objects not in backup
			for key := range pruneObjects {
				if prune {
					var dynClient dynamic.ResourceInterface
					switch key.Kind {
					case "Secret":
						dynClient = acdClients.secrets
					case "AppProject":
						dynClient = acdClients.projects
					case "Application":
						dynClient = acdClients.applications
					default:
						log.Fatalf("Unexpected kind '%s' in prune list", key.Kind)
					}
					if !dryRun {
						err = dynClient.Delete(key.Name, &metav1.DeleteOptions{})
						errors.CheckError(err)
					}
					fmt.Printf("%s/%s %s pruned%s\n", key.Group, key.Kind, key.Name, dryRunMsg)
				} else {
					fmt.Printf("%s/%s %s needs pruning\n", key.Group, key.Kind, key.Name)
				}
			}
		},
	}

	clientConfig = cli.AddKubectlFlagsToCmd(&command)
	command.Flags().BoolVar(&dryRun, "dry-run", false, "Print what will be performed")
	command.Flags().BoolVar(&prune, "prune", false, "Prune secrets, applications and projects which do not appear in the backup")

	return &command
}
983207
func addImportForType(imports importMap, t reflect.Type) {
	// If there is no package path, this is a built-in type and we don't need an
	// import.
	pkgPath := t.PkgPath()
	if pkgPath == "" {
		return
	}

	// Work around a bug in Go:
	//
	//     http://code.google.com/p/go/issues/detail?id=2660
	//
	var errorPtr *error
	if t == reflect.TypeOf(errorPtr).Elem() {
		return
	}

	// Use the identifier that's part of the type's string representation as the
	// import identifier. This means that we'll do the right thing for package
	// "foo/bar" with declaration "package baz".
	match := typePackageIdentifierRegexp.FindStringSubmatch(t.String())
	if match == nil {
		return
	}

	imports[match[1]] = pkgPath
}
615552
func (s *SegmentResponse) SetImportDefinition(v *SegmentImportResource) *SegmentResponse {
	s.ImportDefinition = v
	return s
}
1038804
func (s *LDAPService) NewImportLdapUsersParams() *ImportLdapUsersParams {
	p := &ImportLdapUsersParams{}
	p.p = make(map[string]interface{})
	return p
}
152080
func (ce *ContainerEndpoints) AddExport(cancel <-chan struct{}, bind zkservice.ExportBinding) {
	logger := plog.WithFields(log.Fields{
		"application": bind.Application,
		"portnumber":  bind.PortNumber,
		"protocol":    bind.Protocol,
	})

	exp := registry.ExportDetails{
		ExportBinding: bind,
		PrivateIP:     ce.state.PrivateIP,
		HostIP:        ce.state.HostIP,
		MuxPort:       ce.opts.TCPMuxPort,
		InstanceID:    ce.state.InstanceID,
	}

	logger.Debug("Registering export")
	defer logger.Debug("Unregistered export")

	for {
		select {
		case conn := <-zzk.Connect("/", zzk.GetLocalConnection):
			if conn != nil {

				logger.Debug("Received coordinator connection")
				registry.RegisterExport(cancel, conn, ce.opts.TenantID, exp)
				select {
				case <-cancel:
					return
				default:
				}
			}
		case <-cancel:
			return
		}
	}
}
811838
func srcImporter(typesImporter types.Importer, path string) (pkg *types.Package, err error) {
	return typesImporter.Import(path)
}
660373
func handleImport(s *Server) http.Handler {
	return contextHandler(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		span, jsonMetrics, err := unmarshalMetricsFromHTTP(ctx, s.TraceClient, w, r)
		if err != nil {
			log.WithError(err).Error("Error unmarshalling metrics in global import")
			span.Add(ssf.Count("import.unmarshal.errors_total", 1, nil))
			return
		}
		// the server usually waits for this to return before finalizing the
		// response, so this part must be done asynchronously
		go s.ImportMetrics(span.Attach(ctx), jsonMetrics)
	})
}
527253
func addImportsForInterfaceMethods(imports importMap, it reflect.Type) {
	// Handle each method.
	for i := 0; i < it.NumMethod(); i++ {
		m := it.Method(i)
		addImportsForType(imports, m.Type)
	}
}
897586
func Import(ctx context.Context, c *vim25.Client, name string, datastore *object.Datastore, p ImportParams) error {
	m := ovf.NewManager(c)
	fm := datastore.NewFileManager(p.Datacenter, p.Force)

	disk, err := stat(name)
	if err != nil {
		return err
	}

	var rename string

	p.Path = strings.TrimSuffix(p.Path, "/")
	if p.Path != "" {
		disk.ImportName = p.Path
		rename = path.Join(disk.ImportName, disk.Name)
	}

	// "target" is the path that will be created by ImportVApp()
	// ImportVApp uses the same name for the VM and the disk.
	target := fmt.Sprintf("%s/%s.vmdk", disk.ImportName, disk.ImportName)

	if _, err = datastore.Stat(ctx, target); err == nil {
		if p.Force {
			// If we don't delete, the nfc upload adds a file name suffix
			if err = fm.Delete(ctx, target); err != nil {
				return err
			}
		} else {
			return fmt.Errorf("%s: %s", os.ErrExist, datastore.Path(target))
		}
	}

	// If we need to rename at the end, check if the file exists early unless Force.
	if !p.Force && rename != "" {
		if _, err = datastore.Stat(ctx, rename); err == nil {
			return fmt.Errorf("%s: %s", os.ErrExist, datastore.Path(rename))
		}
	}

	// Expand the ovf template
	descriptor, err := disk.ovf()
	if err != nil {
		return err
	}

	pool := p.Pool     // TODO: use datastore to derive a default
	folder := p.Folder // TODO: use datacenter to derive a default

	kind := p.Type
	if kind == "" {
		kind = types.VirtualDiskTypeThin
	}

	params := types.OvfCreateImportSpecParams{
		DiskProvisioning: string(kind),
		EntityName:       disk.ImportName,
	}

	spec, err := m.CreateImportSpec(ctx, descriptor, pool, datastore, params)
	if err != nil {
		return err
	}
	if spec.Error != nil {
		return errors.New(spec.Error[0].LocalizedMessage)
	}

	lease, err := pool.ImportVApp(ctx, spec.ImportSpec, folder, p.Host)
	if err != nil {
		return err
	}

	info, err := lease.Wait(ctx, spec.FileItem)
	if err != nil {
		return err
	}

	f, err := os.Open(filepath.Clean(name))
	if err != nil {
		return err
	}

	opts := soap.Upload{
		ContentLength: disk.Size,
		Progress:      p.Logger,
	}

	u := lease.StartUpdater(ctx, info)
	defer u.Done()

	item := info.Items[0] // we only have 1 disk to upload

	err = lease.Upload(ctx, item, f, opts)
	if err != nil {
		return err
	}

	err = f.Close()
	if err != nil {
		return err
	}

	if err = lease.Complete(ctx); err != nil {
		return err
	}

	// ImportVApp created a VM, here we detach the vmdk, then delete the VM.
	vm := object.NewVirtualMachine(c, info.Entity)

	device, err := vm.Device(ctx)
	if err != nil {
		return err
	}

	device = device.SelectByType((*types.VirtualDisk)(nil))

	err = vm.RemoveDevice(ctx, true, device...)
	if err != nil {
		return err
	}

	task, err := vm.Destroy(ctx)
	if err != nil {
		return err
	}

	if err = task.Wait(ctx); err != nil {
		return err
	}

	if rename == "" {
		return nil
	}

	return fm.Move(ctx, target, rename)
}