// reloadPluginMounts reloads provided mounts, regardless of
// plugin name, as long as the backend type is plugin.
555997
func (c *Core) reloadMatchingPluginMounts(ctx context.Context, mounts []string) error {
	c.mountsLock.RLock()
	defer c.mountsLock.RUnlock()
	c.authLock.RLock()
	defer c.authLock.RUnlock()

	ns, err := namespace.FromContext(ctx)
	if err != nil {
		return err
	}

	var errors error
	for _, mount := range mounts {
		entry := c.router.MatchingMountEntry(ctx, mount)
		if entry == nil {
			errors = multierror.Append(errors, fmt.Errorf("cannot fetch mount entry on %q", mount))
			continue
		}

		var isAuth bool
		fullPath := c.router.MatchingMount(ctx, mount)
		if strings.HasPrefix(fullPath, credentialRoutePrefix) {
			isAuth = true
		}

		// We dont reload mounts that are not in the same namespace
		if ns.ID != entry.Namespace().ID {
			continue
		}

		err := c.reloadBackendCommon(ctx, entry, isAuth)
		if err != nil {
			errors = multierror.Append(errors, errwrap.Wrapf(fmt.Sprintf("cannot reload plugin on %q: {{err}}", mount), err))
			continue
		}
		c.logger.Info("successfully reloaded plugin", "plugin", entry.Accessor, "path", entry.Path)
	}
	return errors
}
1364602
func (pm *PluginManager) loadPlugins() error {
	files, err := ioutil.ReadDir(pm.cfg.Dir)
	if err != nil {
		return err
	}

	// Make sure all the files were going to load
	// are indeed compiled shared libs of plugins
	for _, file := range files {
		if strings.HasSuffix(file.Name(), ".so") {
			err = pm.loadPlugin(pm.cfg.Dir, file.Name())
			if err != nil {
				return err
			}
		}
	}

	return nil
}
644323
func Plugins(dir string) (err error) {
	var fileInfoArray []os.FileInfo
	var fileInfo os.FileInfo

	if fileInfoArray, err = ioutil.ReadDir(dir); err == nil && len(fileInfoArray) > 0 {
		for _, fileInfo = range fileInfoArray {
			if err = loadPlugin(dir, fileInfo); err != nil {
				lo.G.Debug("error loading plugin: ", err, fileInfo)
				break
			}
			lo.G.Debug("loading plugin from: ", fileInfo)
		}

	} else if err != nil {
		lo.G.Debug("not loading plugins: ", err, fileInfoArray)
		err = fmt.Errorf("error loading plugins: %v %v", err, fileInfoArray)
	}
	return
}
1225449
func loadPlugins(baseCmd *cobra.Command, out io.Writer) {

	// If HELM_NO_PLUGINS is set to 1, do not load plugins.
	if os.Getenv("HELM_NO_PLUGINS") == "1" {
		return
	}

	// debug("HELM_PLUGIN_DIRS=%s", settings.PluginDirs())
	found, err := findPlugins(settings.PluginDirs())
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to load plugins: %s", err)
		return
	}

	processParent := func(cmd *cobra.Command, args []string) ([]string, error) {
		k, u := manuallyProcessArgs(args)
		if err := cmd.Parent().ParseFlags(k); err != nil {
			return nil, err
		}
		return u, nil
	}

	// Now we create commands for all of these.
	for _, plug := range found {
		plug := plug
		md := plug.Metadata
		if md.Usage == "" {
			md.Usage = fmt.Sprintf("the %q plugin", md.Name)
		}

		c := &cobra.Command{
			Use:   md.Name,
			Short: md.Usage,
			Long:  md.Description,
			RunE: func(cmd *cobra.Command, args []string) error {
				u, err := processParent(cmd, args)
				if err != nil {
					return err
				}

				// Call setupEnv before PrepareCommand because
				// PrepareCommand uses os.ExpandEnv and expects the
				// setupEnv vars.
				plugin.SetupPluginEnv(settings, md.Name, plug.Dir)
				main, argv := plug.PrepareCommand(u)

				prog := exec.Command(main, argv...)
				prog.Env = os.Environ()
				prog.Stdin = os.Stdin
				prog.Stdout = out
				prog.Stderr = os.Stderr
				if err := prog.Run(); err != nil {
					if eerr, ok := err.(*exec.ExitError); ok {
						os.Stderr.Write(eerr.Stderr)
						status := eerr.Sys().(syscall.WaitStatus)
						return pluginError{
							error: fmt.Errorf("plugin %q exited with error", md.Name),
							code:  status.ExitStatus(),
						}
					}
					return err
				}
				return nil
			},
			// This passes all the flags to the subcommand.
			DisableFlagParsing: true,
		}

		if md.UseTunnel {
			c.PreRunE = func(cmd *cobra.Command, args []string) error {
				// Parse the parent flag, but not the local flags.
				if _, err := processParent(cmd, args); err != nil {
					return err
				}
				return setupConnection()
			}
		}

		// TODO: Make sure a command with this name does not already exist.
		baseCmd.AddCommand(c)
	}
}
1002496
func (r *Router) Remount(ctx context.Context, src, dst string) error {
	ns, err := namespace.FromContext(ctx)
	if err != nil {
		return err
	}
	src = ns.Path + src
	dst = ns.Path + dst

	r.l.Lock()
	defer r.l.Unlock()

	// Check for existing mount
	raw, ok := r.root.Get(src)
	if !ok {
		return fmt.Errorf("no mount at %q", src)
	}

	// Update the mount point
	r.root.Delete(src)
	r.root.Insert(dst, raw)
	return nil
}
841121
func (p *plugin) Load() {
	dir, file := filepath.Split(p.Path())
	p.name = file
	name := filepath.Base(dir) + "." + file[:len(file)-3]
	s, err := py.NewUnicode(name)
	if err != nil {
		log.Warn(err)
		return
	}
	defer s.Decref()

	log.Debug("Loading plugin %s", name)
	l := py.NewLock()
	defer l.Unlock()
	if r, err := module.Base().CallMethodObjArgs("reload_plugin", s); err != nil {
		log.Warn(err)
		return
	} else if r != nil {
		r.Decref()
	}
}
398658
func (c *PluginReattachConfig) PluginConfig() *plugin.ReattachConfig {
	var addr net.Addr
	switch c.AddrNet {
	case "unix", "unixgram", "unixpacket":
		addr, _ = net.ResolveUnixAddr(c.AddrNet, c.AddrName)
	case "tcp", "tcp4", "tcp6":
		addr, _ = net.ResolveTCPAddr(c.AddrNet, c.AddrName)
	}
	return &plugin.ReattachConfig{Pid: c.Pid, Addr: addr}
}
1325267
func LoadPlugins(eventName string) ([]Plugin, error) {
	routing, err := readPluginRouting()
	if err != nil {
		return []Plugin{}, err
	}

	pluginNames := []string{}
	for name, route := range routing.RouteMap {
		if route.TriggerEvent == eventName {
			pluginNames = append(pluginNames, name)
		}
	}

	plugins := []Plugin{}
	for _, name := range pluginNames {
		plugin, found, err := LoadPlugin(name)
		if err != nil {
			return []Plugin{}, err
		}
		if !found {
			return []Plugin{}, fmt.Errorf("Plugin (%s) exist in routing, but not found", name)
		}
		plugins = append(plugins, plugin)
	}

	return plugins, nil
}
180029
func ReattachConfigToGoPlugin(rc *ReattachConfig) (*plugin.ReattachConfig, error) {
	if rc == nil {
		return nil, fmt.Errorf("nil ReattachConfig cannot be converted")
	}

	plug := &plugin.ReattachConfig{
		Protocol: plugin.Protocol(rc.Protocol),
		Pid:      rc.Pid,
	}

	switch rc.Network {
	case "tcp", "tcp4", "tcp6":
		addr, err := net.ResolveTCPAddr(rc.Network, rc.Addr)
		if err != nil {
			return nil, err
		}
		plug.Addr = addr
	case "udp", "udp4", "udp6":
		addr, err := net.ResolveUDPAddr(rc.Network, rc.Addr)
		if err != nil {
			return nil, err
		}
		plug.Addr = addr
	case "unix", "unixgram", "unixpacket":
		addr, err := net.ResolveUnixAddr(rc.Network, rc.Addr)
		if err != nil {
			return nil, err
		}
		plug.Addr = addr
	default:
		return nil, fmt.Errorf("unknown network: %s", rc.Network)
	}

	return plug, nil
}
1205854
func (m *localVolumeMounter) filterPodMounts(refs []string) []string {
	filtered := []string{}
	for _, r := range refs {
		if strings.HasPrefix(r, m.plugin.host.GetPodsDir()+string(os.PathSeparator)) {
			filtered = append(filtered, r)
		}
	}
	return filtered
}
452568
func (c *PluginCatalog) UpgradePlugins(ctx context.Context, logger log.Logger) error {
	c.lock.Lock()
	defer c.lock.Unlock()

	// If the directory isn't set we can skip the upgrade attempt
	if c.directory == "" {
		return nil
	}

	// List plugins from old location
	pluginsRaw, err := c.catalogView.List(ctx, "")
	if err != nil {
		return err
	}
	plugins := make([]string, 0, len(pluginsRaw))
	for _, p := range pluginsRaw {
		if !strings.HasSuffix(p, "/") {
			plugins = append(plugins, p)
		}
	}

	logger.Info("upgrading plugin information", "plugins", plugins)

	var retErr error
	for _, pluginName := range plugins {
		pluginRaw, err := c.catalogView.Get(ctx, pluginName)
		if err != nil {
			retErr = multierror.Append(errwrap.Wrapf("failed to load plugin entry: {{err}}", err))
			continue
		}

		plugin := new(pluginutil.PluginRunner)
		if err := jsonutil.DecodeJSON(pluginRaw.Value, plugin); err != nil {
			retErr = multierror.Append(errwrap.Wrapf("failed to decode plugin entry: {{err}}", err))
			continue
		}

		// prepend the plugin directory to the command
		cmdOld := plugin.Command
		plugin.Command = filepath.Join(c.directory, plugin.Command)

		pluginType, err := c.getPluginTypeFromUnknown(ctx, logger, plugin)
		if err != nil {
			retErr = multierror.Append(retErr, fmt.Errorf("could not upgrade plugin %s: %s", pluginName, err))
			continue
		}
		if pluginType == consts.PluginTypeUnknown {
			retErr = multierror.Append(retErr, fmt.Errorf("could not upgrade plugin %s: plugin of unknown type", pluginName))
			continue
		}

		// Upgrade the storage
		err = c.setInternal(ctx, pluginName, pluginType, cmdOld, plugin.Args, plugin.Env, plugin.Sha256)
		if err != nil {
			retErr = multierror.Append(retErr, fmt.Errorf("could not upgrade plugin %s: %s", pluginName, err))
			continue
		}

		err = c.catalogView.Delete(ctx, pluginName)
		if err != nil {
			logger.Error("could not remove plugin", "plugin", pluginName, "error", err)
		}

		logger.Info("upgraded plugin type", "plugin", pluginName, "type", pluginType.String())
	}

	return retErr
}
742124
func (r *registry) loadPlugin(pluginPath string, handlerType HandlerType, extraArgs ...string) {
	if _, err := os.Stat(pluginPath); err != nil {
		logger.Panicf(fmt.Sprintf("Could not find plugin at path %s: %s", pluginPath, err))
	}
	p, err := plugin.Open(pluginPath)
	if err != nil {
		logger.Panicf(fmt.Sprintf("Error opening plugin at path %s: %s", pluginPath, err))
	}

	if handlerType == Auth {
		r.initAuthPlugin(p)
	} else if handlerType == Decoration {
		r.initDecoratorPlugin(p)
	} else if handlerType == Endorsement {
		r.initEndorsementPlugin(p, extraArgs...)
	} else if handlerType == Validation {
		r.initValidationPlugin(p, extraArgs...)
	}
}
1274753
func (s *SingletonLoader) reattach(f *future, name, pluginType string, config *plugin.ReattachConfig) {
	i, err := s.loader.Reattach(name, pluginType, config)
	f.set(i, err)
}
594381
func (p *Plugin) ScopedPath(s string) string {
	if p.PluginObj.Config.PropagatedMount != "" && strings.HasPrefix(s, p.PluginObj.Config.PropagatedMount) {
		// re-scope to the propagated mount path on the host
		return filepath.Join(filepath.Dir(p.Rootfs), "propagated-mount", strings.TrimPrefix(s, p.PluginObj.Config.PropagatedMount))
	}
	return filepath.Join(p.Rootfs, s)
}
1168112
func LoadDir(dirname string) (*Plugin, error) {
	data, err := ioutil.ReadFile(filepath.Join(dirname, pluginFileName))
	if err != nil {
		return nil, err
	}

	plug := &Plugin{Dir: dirname}
	if err := yaml.Unmarshal(data, &plug.Metadata); err != nil {
		return nil, err
	}
	return plug, nil
}
1272311
func (c *Core) setupMounts(ctx context.Context) error {
	c.mountsLock.Lock()
	defer c.mountsLock.Unlock()

	for _, entry := range c.mounts.sortEntriesByPathDepth().Entries {
		// Initialize the backend, special casing for system
		barrierPath := entry.ViewPath()

		// Create a barrier view using the UUID
		view := NewBarrierView(c.barrier, barrierPath)

		// Singleton mounts cannot be filtered on a per-secondary basis
		// from replication
		if strutil.StrListContains(singletonMounts, entry.Type) {
			addFilterablePath(c, barrierPath)
		}

		// Determining the replicated state of the mount
		nilMount, err := preprocessMount(c, entry, view)
		if err != nil {
			return err
		}
		origReadOnlyErr := view.getReadOnlyErr()

		// Mark the view as read-only until the mounting is complete and
		// ensure that it is reset after. This ensures that there will be no
		// writes during the construction of the backend.
		view.setReadOnlyErr(logical.ErrSetupReadOnly)
		if strutil.StrListContains(singletonMounts, entry.Type) {
			defer view.setReadOnlyErr(origReadOnlyErr)
		} else {
			c.postUnsealFuncs = append(c.postUnsealFuncs, func() {
				view.setReadOnlyErr(origReadOnlyErr)
			})
		}

		var backend logical.Backend
		// Create the new backend
		sysView := c.mountEntrySysView(entry)
		backend, err = c.newLogicalBackend(ctx, entry, sysView, view)
		if err != nil {
			c.logger.Error("failed to create mount entry", "path", entry.Path, "error", err)
			if !c.builtinRegistry.Contains(entry.Type, consts.PluginTypeSecrets) {
				// If we encounter an error instantiating the backend due to an error,
				// skip backend initialization but register the entry to the mount table
				// to preserve storage and path.
				c.logger.Warn("skipping plugin-based mount entry", "path", entry.Path)
				goto ROUTER_MOUNT
			}
			return errLoadMountsFailed
		}
		if backend == nil {
			return fmt.Errorf("created mount entry of type %q is nil", entry.Type)
		}

		{
			// Check for the correct backend type
			backendType := backend.Type()

			if backendType != logical.TypeLogical {
				if entry.Type != "kv" && entry.Type != "system" && entry.Type != "cubbyhole" {
					return fmt.Errorf(`unknown backend type: "%s"`, entry.Type)
				}
			}

			addPathCheckers(c, entry, backend, barrierPath)

			c.setCoreBackend(entry, backend, view)
		}

		// If the mount is filtered or we are on a DR secondary we don't want to
		// keep the actual backend running, so we clean it up and set it to nil
		// so the router does not have a pointer to the object.
		if nilMount {
			backend.Cleanup(ctx)
			backend = nil
		}

	ROUTER_MOUNT:
		// Mount the backend
		err = c.router.Mount(backend, entry.Path, entry, view)
		if err != nil {
			c.logger.Error("failed to mount entry", "path", entry.Path, "error", err)
			return errLoadMountsFailed
		}

		if c.logger.IsInfo() {
			c.logger.Info("successfully mounted backend", "type", entry.Type, "path", entry.Path)
		}

		// Ensure the path is tainted if set in the mount table
		if entry.Tainted {
			c.router.Taint(ctx, entry.Path)
		}

		// Ensure the cache is populated, don't need the result
		NamespaceByID(ctx, entry.NamespaceID, c)
	}
	return nil
}
116603
func (mod *SimplepushBee) ReloadOptions(options bees.BeeOptions) {
	mod.SetOptions(options)

	options.Bind("key", &mod.key)
	options.Bind("password", &mod.password)
	options.Bind("salt", &mod.salt)
}