// StartPlugins starts all plugins in the correct order.
58
func (co *Coordinator) StartPlugins() {
	// Launch routers
	for _, router := range co.routers {
		logrus.Debug("Starting ", reflect.TypeOf(router))
		if err := router.Start(); err != nil {
			logrus.WithError(err).Errorf("Failed to start router of type '%s'", reflect.TypeOf(router))
		}
	}

	// Launch producers
	co.state = coordinatorStateStartProducers
	for _, producer := range co.producers {
		producer := producer
		go tgo.WithRecoverShutdown(func() {
			logrus.Debug("Starting ", reflect.TypeOf(producer))
			producer.Produce(co.producerWorker)
		})
	}

	// Set final log target and purge the intermediate buffer
	if core.StreamRegistry.IsStreamRegistered(core.LogInternalStreamID) {
		// The _GOLLUM_ stream has listeners, so use LogConsumer to write to it
		if *flagLogColors == "always" {
			logrus.SetFormatter(logger.NewConsoleFormatter())
		}
		logrusHookBuffer.SetTargetHook(co.logConsumer)
		logrusHookBuffer.Purge()

	} else {
		logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice)
		logrusHookBuffer.Purge()
	}

	// Launch consumers
	co.state = coordinatorStateStartConsumers
	for _, consumer := range co.consumers {
		consumer := consumer
		go tgo.WithRecoverShutdown(func() {
			logrus.Debug("Starting ", reflect.TypeOf(consumer))
			consumer.Consume(co.consumerWorker)
		})
	}
}
705552
func ListPlugins() map[string][]string {
	p := make(map[string][]string)

	// server type plugins
	for name := range serverTypes {
		p["server_types"] = append(p["server_types"], name)
	}

	// caddyfile loaders in registration order
	for _, loader := range caddyfileLoaders {
		p["caddyfile_loaders"] = append(p["caddyfile_loaders"], loader.name)
	}
	if defaultCaddyfileLoader.name != "" {
		p["caddyfile_loaders"] = append(p["caddyfile_loaders"], defaultCaddyfileLoader.name)
	}

	// List the event hook plugins
	eventHooks.Range(func(k, _ interface{}) bool {
		p["event_hooks"] = append(p["event_hooks"], k.(string))
		return true
	})

	// alphabetize the rest of the plugins
	var others []string
	for stype, stypePlugins := range plugins {
		for name := range stypePlugins {
			var s string
			if stype != "" {
				s = stype + "."
			}
			s += name
			others = append(others, s)
		}
	}

	sort.Strings(others)
	for _, name := range others {
		p["others"] = append(p["others"], name)
	}

	return p
}
411554
func (a *authorizationPlugin) initPlugin() error {
	// Lazy loading of plugins
	a.once.Do(func() {
		if a.plugin == nil {
			var plugin plugingetter.CompatPlugin
			var e error

			if pg := GetPluginGetter(); pg != nil {
				plugin, e = pg.Get(a.name, AuthZApiImplements, plugingetter.Lookup)
				a.SetName(plugin.Name())
			} else {
				plugin, e = plugins.Get(a.name, AuthZApiImplements)
			}
			if e != nil {
				a.initErr = e
				return
			}
			a.plugin = plugin.Client()
		}
	})
	return a.initErr
}
916704
func Start(cmd Plugin) {
	if len(os.Args) < 2 {
		fmt.Printf("This cf CLI plugin is not intended to be run on its own\n\n")
		os.Exit(1)
	}

	cliConnection := NewCliConnection(os.Args[1])
	cliConnection.pingCLI()
	if isMetadataRequest(os.Args) {
		cliConnection.sendPluginMetadataToCliServer(cmd.GetMetadata())
	} else {
		if version := MinCliVersionStr(cmd.GetMetadata().MinCliVersion); version != "" {
			ok := cliConnection.isMinCliVersion(version)
			if !ok {
				fmt.Printf("Minimum CLI version %s is required to run this plugin command\n\n", version)
				os.Exit(0)
			}
		}

		cmd.Run(cliConnection, os.Args[2:])
	}
}
1052563
func (c *Client) InstallPlugins(opts InstallPluginOptions) error {
	path := "/plugins/pull?" + queryString(opts)
	resp, err := c.do("POST", path, doOptions{
		data:    opts.Plugins,
		context: opts.Context,
	})
	defer resp.Body.Close()
	if err != nil {
		return err
	}
	return nil
}
893781
func NewPlugin() plugin.Plugin {
	return &allowedCors{
		allowedHeaders: []string{},
		allowedOrigins: []string{},
		allowedMethods: []string{},
	}
}
1372349
func hapiPlugins(w http.ResponseWriter, r *http.Request) {
	if os.Getenv("ABOT_ENV") != "test" {
		if !isAdmin(w, r) {
			return
		}
		if !isLoggedIn(w, r) {
			return
		}
	}
	var settings []struct {
		Name       string
		Value      string
		PluginName string
	}
	q := `SELECT name, value, pluginname FROM settings`
	if err := db.Select(&settings, q); err != nil {
		writeErrorInternal(w, err)
		return
	}
	type respT struct {
		ID         uint64
		Name       string
		Icon       string
		Maintainer string
		Settings   map[string]string
	}
	var resp []respT
	for _, plugin := range PluginsGo {
		data := respT{
			ID:         plugin.ID,
			Name:       plugin.Name,
			Icon:       plugin.Icon,
			Maintainer: plugin.Maintainer,
			Settings:   map[string]string{},
		}
		for k, v := range plugin.Settings {
			data.Settings[k] = v.Default
		}
		for _, setting := range settings {
			if setting.PluginName != plugin.Name {
				continue
			}
			data.Settings[setting.Name] = setting.Value
		}
		resp = append(resp, data)
	}
	writeBytes(w, resp)
}
658779
func AllPlugins(plugins ...infra.Plugin) Option {
	return func(o *Options) {
		infraLogger.Debugf("AllPlugins with %d plugins", len(plugins))

		for _, plugin := range plugins {
			typ := reflect.TypeOf(plugin)
			infraLogger.Debugf("searching for all deps in: %v (type: %v)", plugin, typ)

			foundPlugins, err := findPlugins(reflect.ValueOf(plugin), o.pluginMap)
			if err != nil {
				panic(err)
			}

			infraLogger.Debugf("found %d plugins in: %v (type: %v)", len(foundPlugins), plugin, typ)
			for _, plug := range foundPlugins {
				infraLogger.Debugf(" - plugin: %v (%v)", plug, reflect.TypeOf(plug))

				if _, ok := o.pluginNames[plug.String()]; ok {
					infraLogger.Fatalf("plugin with name %q already registered", plug.String())
				}
				o.pluginNames[plug.String()] = struct{}{}
			}
			o.Plugins = append(o.Plugins, foundPlugins...)

			// TODO: perhaps set plugin name to typ.String() if it's empty
			/*p, ok := plugin.(core.PluginNamed)
			if !ok {
				p = core.NamePlugin(typ.String(), plugin)
			}*/

			if _, ok := o.pluginNames[plugin.String()]; ok {
				infraLogger.Fatalf("plugin with name %q already registered, custom name should be used", plugin.String())
			}
			o.pluginNames[plugin.String()] = struct{}{}
			o.Plugins = append(o.Plugins, plugin)
		}
	}
}
362618
func (bldr *fooBarQueryBuilder) Start(cur datastore.Cursor) *fooBarQueryBuilder {
	bldr.q = bldr.q.Start(cur)
	if bldr.plugin != nil {
		bldr.plugin.Start(cur)
	}
	return bldr
}
1329905
func MsgToCorePlugins(msg []*Plugin) []core.Plugin {
	plugins := make([]core.Plugin, len(msg))
	for i, v := range msg {
		plugins[i] = MsgToCorePlugin(v)
	}
	return plugins
}
115258
func (p *ExamplePlugin) Init() error {
	p.Log.Info("Init plugin..")
	// Initialize plugin fields.
	p.resyncChannel = make(chan datasync.ResyncEvent)
	p.changeChannel = make(chan datasync.ChangeEvent)

	p.context, p.cancel = context.WithCancel(context.Background())

	// Start the consumer (ETCD watcher).
	p.wg.Add(1)
	go p.consumer()

	// Subscribe watcher to be able to watch on data changes and resync events.
	err := p.subscribeWatcher()
	if err != nil {
		return err
	}

	p.Log.Info("Plugin Init for datasync example done")

	return nil
}
243781
func (p *pluginControl) AvailablePlugins() []core.AvailablePlugin {
	var caps []core.AvailablePlugin
	for _, ap := range p.pluginRunner.AvailablePlugins().all() {
		caps = append(caps, ap)
	}
	return caps
}
1023853
func Start(ctx context.Context, rootDir, stateDir string, opts ...DaemonOpt) (Daemon, error) {
	r := &remote{
		rootDir:  rootDir,
		stateDir: stateDir,
		Config: config.Config{
			Root:  filepath.Join(rootDir, "daemon"),
			State: filepath.Join(stateDir, "daemon"),
		},
		pluginConfs:   pluginConfigs{make(map[string]interface{})},
		daemonPid:     -1,
		logger:        logrus.WithField("module", "libcontainerd"),
		daemonStartCh: make(chan error, 1),
		daemonStopCh:  make(chan struct{}),
	}

	for _, opt := range opts {
		if err := opt(r); err != nil {
			return nil, err
		}
	}
	r.setDefaults()

	if err := system.MkdirAll(stateDir, 0700, ""); err != nil {
		return nil, err
	}

	go r.monitorDaemon(ctx)

	select {
	case <-time.After(startupTimeout):
		return nil, errors.New("timeout waiting for containerd to start")
	case err := <-r.daemonStartCh:
		if err != nil {
			return nil, err
		}
	}

	return r, nil
}
665198
func (pm PluginManager) Plugins(t Type) []interface{} {
	if plugins, exists := pm.pluginsByType[t]; exists {
		plugin_ifaces := make([]interface{}, 0, len(plugins))
		for _, p := range plugins {
			plugin_ifaces = append(plugin_ifaces, p.instance.Interface())
		}
		return plugin_ifaces
	} else {
		return make([]interface{}, 0) // empty array
	}
}
615220
func LoadPlugins(ctx context.Context, config *srvconfig.Config) ([]*plugin.Registration, error) {
	// load all plugins into containerd
	path := config.PluginDir
	if path == "" {
		path = filepath.Join(config.Root, "plugins")
	}
	if err := plugin.Load(path); err != nil {
		return nil, err
	}
	// load additional plugins that don't automatically register themselves
	plugin.Register(&plugin.Registration{
		Type: plugin.ContentPlugin,
		ID:   "content",
		InitFn: func(ic *plugin.InitContext) (interface{}, error) {
			ic.Meta.Exports["root"] = ic.Root
			return local.NewStore(ic.Root)
		},
	})
	plugin.Register(&plugin.Registration{
		Type: plugin.MetadataPlugin,
		ID:   "bolt",
		Requires: []plugin.Type{
			plugin.ContentPlugin,
			plugin.SnapshotPlugin,
		},
		Config: &srvconfig.BoltConfig{
			ContentSharingPolicy: srvconfig.SharingPolicyShared,
		},
		InitFn: func(ic *plugin.InitContext) (interface{}, error) {
			if err := os.MkdirAll(ic.Root, 0711); err != nil {
				return nil, err
			}
			cs, err := ic.Get(plugin.ContentPlugin)
			if err != nil {
				return nil, err
			}

			snapshottersRaw, err := ic.GetByType(plugin.SnapshotPlugin)
			if err != nil {
				return nil, err
			}

			snapshotters := make(map[string]snapshots.Snapshotter)
			for name, sn := range snapshottersRaw {
				sn, err := sn.Instance()
				if err != nil {
					if !plugin.IsSkipPlugin(err) {
						log.G(ic.Context).WithError(err).
							Warnf("could not use snapshotter %v in metadata plugin", name)
					}
					continue
				}
				snapshotters[name] = sn.(snapshots.Snapshotter)
			}

			shared := true
			ic.Meta.Exports["policy"] = srvconfig.SharingPolicyShared
			if cfg, ok := ic.Config.(*srvconfig.BoltConfig); ok {
				if cfg.ContentSharingPolicy != "" {
					if err := cfg.Validate(); err != nil {
						return nil, err
					}
					if cfg.ContentSharingPolicy == srvconfig.SharingPolicyIsolated {
						ic.Meta.Exports["policy"] = srvconfig.SharingPolicyIsolated
						shared = false
					}

					log.L.WithField("policy", cfg.ContentSharingPolicy).Info("metadata content store policy set")
				}
			}

			path := filepath.Join(ic.Root, "meta.db")
			ic.Meta.Exports["path"] = path

			db, err := bolt.Open(path, 0644, nil)
			if err != nil {
				return nil, err
			}

			var dbopts []metadata.DBOpt
			if !shared {
				dbopts = append(dbopts, metadata.WithPolicyIsolated)
			}
			mdb := metadata.NewDB(db, cs.(content.Store), snapshotters, dbopts...)
			if err := mdb.Init(ic.Context); err != nil {
				return nil, err
			}
			return mdb, nil
		},
	})

	clients := &proxyClients{}
	for name, pp := range config.ProxyPlugins {
		var (
			t plugin.Type
			f func(*grpc.ClientConn) interface{}

			address = pp.Address
		)

		switch pp.Type {
		case string(plugin.SnapshotPlugin), "snapshot":
			t = plugin.SnapshotPlugin
			ssname := name
			f = func(conn *grpc.ClientConn) interface{} {
				return ssproxy.NewSnapshotter(ssapi.NewSnapshotsClient(conn), ssname)
			}

		case string(plugin.ContentPlugin), "content":
			t = plugin.ContentPlugin
			f = func(conn *grpc.ClientConn) interface{} {
				return csproxy.NewContentStore(csapi.NewContentClient(conn))
			}
		default:
			log.G(ctx).WithField("type", pp.Type).Warn("unknown proxy plugin type")
		}

		plugin.Register(&plugin.Registration{
			Type: t,
			ID:   name,
			InitFn: func(ic *plugin.InitContext) (interface{}, error) {
				ic.Meta.Exports["address"] = address
				conn, err := clients.getClient(address)
				if err != nil {
					return nil, err
				}
				return f(conn), nil
			},
		})

	}

	// return the ordered graph for plugins
	return plugin.Graph(config.DisabledPlugins), nil
}
1232623
func (p *Predict) VaultPlugins(pluginTypes ...consts.PluginType) complete.Predictor {
	filterFunc := func() []string {
		return p.plugins(pluginTypes...)
	}
	return p.filterFunc(filterFunc)
}
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)
	}
}