// NewWorkitemsController creates a workitems controller.
322100
func NewWorkitemsController(service *goa.Service, db application.DB, config WorkItemControllerConfig) *WorkitemsController {
	return NewNotifyingWorkitemsController(service, db, &notification.DevNullChannel{}, config)
}
751726
func NewController(config ControllerConfig) (*Controller, error) {
	c, err := newController(config, newResidentManager(config.Changes))
	return c, errors.Trace(err)
}
865517
func NewWorkItemLabelsController(service *goa.Service, db application.DB, config WorkItemLabelsControllerConfiguration) *WorkItemLabelsController {
	return &WorkItemLabelsController{
		Controller: service.NewController("WorkItemLabelsController"),
		db:         db,
		config:     config,
	}
}
137910
func NewWorkitemtypeController(service *goa.Service, db application.DB, config workItemTypeControllerConfiguration) *WorkitemtypeController {
	return &WorkitemtypeController{
		Controller: service.NewController("WorkitemtypeController"),
		db:         db,
		config:     config,
	}
}
493923
func NewWorker(config Config) (worker.Worker, error) {
	if err := config.Validate(); err != nil {
		return nil, errors.Trace(err)
	}

	w := &Worker{
		logger: config.Logger,
		update: config.UpdateControllerAPIPort,
	}

	servingInfo, ok := config.AgentConfig.StateServingInfo()
	if !ok {
		return nil, errors.New("missing state serving info")
	}
	w.controllerAPIPort = servingInfo.ControllerAPIPort
	// We need to make sure that update the agent config with
	// the potentially new controller api port from the database
	// before we start any other workers that need to connect
	// to the controller over the controller port.
	w.updateControllerPort(config.ControllerAPIPort)

	unsub, err := config.Hub.Subscribe(controller.ConfigChanged,
		func(topic string, data controller.ConfigChangedMessage, err error) {
			if w.updateControllerPort(data.Config.ControllerAPIPort()) {
				w.tomb.Kill(dependency.ErrBounce)
			}
		})
	if err != nil {
		return nil, errors.Annotate(err, "unable to subscribe to details topic")
	}

	w.tomb.Go(func() error {
		defer unsub()
		<-w.tomb.Dying()
		return nil
	})
	return w, nil
}
80159
func (c *DiscoveryController) processNextWorkItem() bool {
	key, quit := c.queue.Get()
	if quit {
		return false
	}
	defer c.queue.Done(key)

	err := c.syncFn(key.(schema.GroupVersion))
	if err == nil {
		c.queue.Forget(key)
		return true
	}

	utilruntime.HandleError(fmt.Errorf("%v failed with: %v", key, err))
	c.queue.AddRateLimited(key)

	return true
}
1315588
func NewDbWorker(db *DbGorp, workInfo DbWorkInfo, numWorkers int) (container *DbWorkerContainer) {

	container = &DbWorkerContainer{
		SharedWorker: SharedWorker{
			InputChannel:   make(chan interface{}, numWorkers),
			OutputChannel:  make(chan interface{}, numWorkers),
			ControlChannel: make(chan func() (WorkerPhase, *DbWorker), numWorkers),
			workInfo:       workInfo,
		},
		NumWorkers:       numWorkers,
		Db:               db,
		StartWorkTimeout: 0,
		LongWorkTimeout:  0,
	}
	return
}
1230292
func (c *Controller) processNextWorkItem() bool {
	obj, shutdown := c.releaseWorkqueue.Get()
	if shutdown {
		return false
	}

	// wrapping block in a func to defer c.workqueue.Done
	err := func(obj interface{}) error {
		// We call Done here so the workqueue knows we have finished
		// processing this item. We must call Forget if we do not want
		// this work item being re-queued. If a transient error
		// occurs, we do not call Forget. Instead the item is put back
		// on the workqueue and attempted again after a back-off
		// period.
		defer c.releaseWorkqueue.Done(obj)

		var key string
		var ok bool
		// We expect strings to come off the workqueue. These are of the
		// form "namespace/fhr(custom resource) name". We do this as the delayed nature of the
		// workqueue means the items in the informer cache may actually be
		// more up to date than when the item was initially put onto the
		// workqueue.
		if key, ok = obj.(string); !ok {
			// As the item in the workqueue is actually invalid, we call
			// Forget not to get into a loop of attempting to
			// process a work item that is invalid.
			c.releaseWorkqueue.Forget(obj)
			runtime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))

			return nil
		}
		// Run the syncHandler, passing it the namespace/name string of the
		// HelmRelease resource to sync the corresponding Chart release.
		// If the sync failed, then we return while the item will get requeued
		if err := c.syncHandler(key); err != nil {
			return fmt.Errorf("errored syncing HelmRelease '%s': %s", key, err.Error())
		}
		// If no error occurs we Forget this item so it does not
		// get queued again until another change happens.
		c.releaseWorkqueue.Forget(obj)
		return nil
	}(obj)

	if err != nil {
		runtime.HandleError(err)
		return true
	}
	return true
}
750248
func NewWorker(config FlagConfig) (worker.Worker, error) {
	worker, err := NewFlagWorker(config)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return worker, nil
}
1252591
func (cc *CertificateController) processNextWorkItem() bool {
	cKey, quit := cc.queue.Get()
	if quit {
		return false
	}
	defer cc.queue.Done(cKey)

	if err := cc.syncFunc(cKey.(string)); err != nil {
		cc.queue.AddRateLimited(cKey)
		if _, ignorable := err.(ignorableError); !ignorable {
			utilruntime.HandleError(fmt.Errorf("Sync %v failed with : %v", cKey, err))
		} else {
			klog.V(4).Infof("Sync %v failed with : %v", cKey, err)
		}
		return true
	}

	cc.queue.Forget(cKey)
	return true

}
354970
func newController(config ControllerConfig, manager *residentManager) (*Controller, error) {
	if err := config.Validate(); err != nil {
		return nil, errors.Trace(err)
	}

	c := &Controller{
		manager: manager,
		changes: config.Changes,
		notify:  config.Notify,
		models:  make(map[string]*Model),
		hub: pubsub.NewSimpleHub(&pubsub.SimpleHubConfig{
			// TODO: (thumper) add a get child method to loggers.
			Logger: loggo.GetLogger("juju.core.cache.hub"),
		}),
		metrics: createControllerGauges(),
	}

	manager.dying = c.tomb.Dying()
	c.tomb.Go(c.loop)
	return c, nil
}
327621
func NewWorker(config Config) (worker.Worker, error) {
	if err := config.Validate(); err != nil {
		return nil, errors.Trace(err)
	}

	rateLimitConfig, err := getRateLimitConfig(config.AgentConfig)
	if err != nil {
		return nil, errors.Annotate(err, "getting rate limit config")
	}

	logSinkConfig, err := getLogSinkConfig(config.AgentConfig)
	if err != nil {
		return nil, errors.Annotate(err, "getting log sink config")
	}

	controllerConfig, err := config.StatePool.SystemState().ControllerConfig()
	if err != nil {
		return nil, errors.Annotate(err, "cannot fetch the controller config")
	}

	observerFactory, err := newObserverFn(
		config.AgentConfig,
		controllerConfig,
		config.Clock,
		config.Hub,
		config.MetricsCollector,
	)
	if err != nil {
		return nil, errors.Annotate(err, "cannot create RPC observer factory")
	}

	serverConfig := apiserver.ServerConfig{
		StatePool:                     config.StatePool,
		Controller:                    config.Controller,
		Clock:                         config.Clock,
		Tag:                           config.AgentConfig.Tag(),
		DataDir:                       config.AgentConfig.DataDir(),
		LogDir:                        config.AgentConfig.LogDir(),
		Hub:                           config.Hub,
		Presence:                      config.Presence,
		Mux:                           config.Mux,
		Authenticator:                 config.Authenticator,
		RestoreStatus:                 config.RestoreStatus,
		UpgradeComplete:               config.UpgradeComplete,
		PublicDNSName:                 controllerConfig.AutocertDNSName(),
		AllowModelAccess:              controllerConfig.AllowModelAccess(),
		NewObserver:                   observerFactory,
		RegisterIntrospectionHandlers: config.RegisterIntrospectionHTTPHandlers,
		MetricsCollector:              config.MetricsCollector,
		RateLimitConfig:               rateLimitConfig,
		LogSinkConfig:                 &logSinkConfig,
		GetAuditConfig:                config.GetAuditConfig,
		LeaseManager:                  config.LeaseManager,
	}
	return config.NewServer(serverConfig)
}
1081547
func (c *SearchController) WorkitemsCSV(ctx *app.WorkitemsCSVSearchContext) error {
	if ctx.FilterExpression == nil {
		return goa.ErrBadRequest(fmt.Sprintf("bad parameter error exporting work items as CSV: param 'filter[expression]' missing"))
	}
	if ctx.PageLimit != nil && *(ctx.PageLimit) > 1000 {
		// the window size is too large
		return goa.ErrBadRequest("maximum limit value is 1000")
	}
	// set page size from query or use default
	limit := 100
	if ctx.PageLimit != nil {
		// we add an overflow indicator element
		limit = *(ctx.PageLimit) + 1
	}
	offset := 0
	if ctx.PageOffset != nil {
		offset = *(ctx.PageOffset)
	}
	// retrieve the first work item window to get a reference for the WITs
	wiResult, childsResult, parentsResult, err := getWorkItemsByFilterExpression(*ctx, c.db, *ctx.FilterExpression, ctx.FilterParentexists, &offset, &limit)
	if err != nil {
		return goa.ErrBadRequest(fmt.Sprintf("error searching work items for expression '%s': %s", *ctx.FilterExpression, err))
	}
	// set header data, adding timestamp to the filename
	currentTime := time.Now().UTC()
	timeStr := currentTime.Format(time.RFC3339)
	ctx.ResponseData.Header().Set("Content-Disposition", "attachment; filename='workitems-"+timeStr+".csv'")
	// see if we have a non-empty result set
	if len(wiResult) == 0 {
		// empty result, nothing matched the filter expression, we're done
		return ctx.OK([]byte(""))
	}
	// retrieve the spaceID from the returned first result entry
	spaceID := wiResult[0].SpaceID
	// retieve all WITs for this space
	var wits []workitem.WorkItemType
	err = application.Transactional(c.db, func(appl application.Application) error {
		var err error
		thisSpace, err := appl.Spaces().Load(ctx.Context, spaceID)
		if err != nil {
			log.Error(ctx, map[string]interface{}{
				"err":     err,
				"spaceID": spaceID,
			}, "unable to retrieve space")
			return errs.Wrapf(err, "error retrieving space for spaceID: %s", spaceID.String())
		}
		spaceTemplateID := thisSpace.SpaceTemplateID
		wits, err = appl.WorkItemTypes().List(ctx.Context, spaceTemplateID)
		if err != nil {
			log.Error(ctx, map[string]interface{}{
				"err":     err,
				"spaceID": spaceID,
			}, "unable to retrieve work item types")
			return errs.Wrapf(err, "error retrieving work item types for spaceID: %s", spaceID.String())
		}
		return nil
	})
	if err != nil {
		return goa.ErrBadRequest(fmt.Sprintf("error retrieving work item types for expression '%s': %s", *ctx.FilterExpression, err))
	}
	// the cache used for caching id to number resolve results
	idNumberCache := make(map[string]string)
	if ctx.PageLimit != nil {
		// if the overflow entry is in the result set, then there is more than this window, add a note to the bottom of the returned list
		moreMessage := ""
		if len(wiResult) >= limit {
			// there is an overflow, slice off the overflow item and add the message
			wiResult = wiResult[:len(wiResult)-1]
			moreMessage = "\nWIT_NOTE_MORE: There are more result entries. You may want to narrow down your query or use paging to retrieve more results."
		}
		// Convert them to CSV format the return value contains the final CSV
		wisCSV, _, err := ConvertWorkItemsToCSV(ctx.Context, c.db, wits, wiResult, childsResult, parentsResult, idNumberCache, true)
		if err != nil {
			return goa.ErrBadRequest(fmt.Sprintf("error converting work items to output format for expression '%s': %s", *ctx.FilterExpression, err))
		}
		// add the note to the bottom of the result csv (if there is a note)
		wisCSV = wisCSV + moreMessage
		// return to client
		return ctx.OK([]byte(wisCSV))
	}
	// we want to retrieve everything, first serialize the work items we already got
	wisCSV, _, err := ConvertWorkItemsToCSV(ctx.Context, c.db, wits, wiResult, childsResult, parentsResult, idNumberCache, true)
	if err != nil {
		return goa.ErrBadRequest(fmt.Sprintf("error converting work items to output format for expression '%s': %s", *ctx.FilterExpression, err))
	}
	// write them out to the client
	ctx.ResponseWriter.Write([]byte(wisCSV))
	// page over the database, convert and send in chunks to the client
	var wiResultWindow []workitem.WorkItem
	var childLinksWindow link.WorkItemLinkList
	var parentWindow link.AncestorList
	// we already fetched limit entries, so set offset
	offset = offset + limit
	// now iterate as long as the returned item count reaches the limit
	for {
		wiResultWindow, childLinksWindow, parentWindow, err = getWorkItemsByFilterExpression(ctx.Context, c.db, *ctx.FilterExpression, ctx.FilterParentexists, ptr.Int(offset), ptr.Int(limit))
		if err != nil {
			return goa.ErrBadRequest(fmt.Sprintf("error retrieving work item types for expression '%s': %s", *ctx.FilterExpression, err))
		}
		wisCSV, _, err = ConvertWorkItemsToCSV(ctx.Context, c.db, wits, wiResultWindow, childLinksWindow, parentWindow, idNumberCache, false)
		if err != nil {
			return goa.ErrBadRequest(fmt.Sprintf("error converting work items to output format for expression '%s': %s", *ctx.FilterExpression, err))
		}
		ctx.ResponseWriter.Write([]byte(wisCSV))
		if len(wiResultWindow) < limit {
			break
		}
		offset = offset + len(wiResultWindow)
	}
	// finally, return the result
	return ctx.OK(nil)
}
1244037
func NewWorker(config Config) (worker.Worker, error) {
	if err := config.Validate(); err != nil {
		return nil, errors.Trace(err)
	}
	w := &revisionUpdateWorker{
		config: config,
	}
	w.tomb.Go(w.loop)
	return w, nil
}
211632
func (c *NamedWorkItemsController) Show(ctx *app.ShowNamedWorkItemsContext) error {
	err := application.Transactional(c.db, func(appl application.Application) error {
		wiID, _, err := appl.WorkItems().LookupIDByNamedSpaceAndNumber(ctx, ctx.UserName, ctx.SpaceName, ctx.WiNumber)
		if err != nil {
			return errs.Wrapf(err, "Fail to load work item with number %v in %s/%s", ctx.WiNumber, ctx.UserName, ctx.SpaceName)
		}
		ctx.ResponseData.Header().Set("Location", rest.AbsoluteURL(ctx.Request, app.WorkitemHref(wiID)))
		return ctx.TemporaryRedirect()
	})
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	return nil
}
912823
func NewEndpointsController(service *goa.Service) *EndpointsController {
	return &EndpointsController{
		Controller:  service.NewController("EndpointsController"),
		FileHandler: workingFileFetcher{},
	}
}
482062
func NewWorker(config Config) (worker.Worker, error) {
	if err := config.Validate(); err != nil {
		return nil, errors.Annotate(err, "validating config")
	}
	updater, err := config.NewUpdater()
	if err != nil {
		return nil, errors.Annotate(err, "getting new updater")
	}
	w := &updaterWorker{
		config:  config,
		updater: updater,
	}
	w.tomb.Go(w.loop)
	return w, nil
}