Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package fx is a framework that makes it easy to build applications out of reusable, composable modules. Fx applications use dependency injection to eliminate globals without the tedium of manually wiring together function calls. Unlike other approaches to dependency injection, Fx works with plain Go functions: you don't need to use struct tags or embed special types, so Fx automatically works well with most Go packages. Basic usage is explained in the package-level example below. If you're new to Fx, start there! Advanced features, including named instances, optional parameters, and value groups, are explained under the In and Out types. To test functions that use the Lifecycle type or to write end-to-end tests of your Fx application, use the helper functions and types provided by the go.uber.org/fx/fxtest package.
Package pg provides opinionated Postgres types and providers for setting up Postgres DB connections using dependency injection.
Package container provides 'dependency injection' functionality. A large part of this is done through the 'dependency injection container', which is reified through the 'container.Container' interface, and created by calling the 'container.New()' func. As in: You do 3 things with a 'dependency injection container'. (Although it is possible that in practice you might only do 2 of these 3 things. But if you end up doing all 3 of these things, that's OK too.) #1: You register things with the container, giving the thing you registed a (string) name when you register it. For example: Also, for example: #2: You manually get things out of the container. (Doing this is a bit involved, but #3 provides a better alternative to this method.) For example: Also, for example: #3: The container can inject dependencies into something. For example:
Package dig provides an opinionated way of resolving object dependencies. STABLE. No breaking changes will be made in this major version. Dig exposes type Container as an object capable of resolving a directed acyclic dependency graph. Use the New function to create one. Constructors for different types are added to the container by using the Provide method. A constructor can declare a dependency on another type by simply adding it as a function parameter. Dependencies for a type can be added to the graph both, before and after the type was added. Multiple constructors can rely on the same type. The container creates a singleton for each retained type, instantiating it at most once when requested directly or as a dependency of another type. Constructors can declare any number of dependencies as parameters and optionally, return errors. Constructors can also return multiple results to add multiple types to the container. Constructors that accept a variadic number of arguments are treated as if they don't have those arguments. That is, Is treated the same as, The constructor will be called with all other dependencies and no variadic arguments. Types added to to the container may be consumed by using the Invoke method. Invoke accepts any function that accepts one or more parameters and optionally, returns an error. Dig calls the function with the requested type, instantiating only those types that were requested by the function. The call fails if any type or its dependencies (both direct and transitive) were not available in the container. Any error returned by the invoked function is propagated back to the caller. Constructors declare their dependencies as function parameters. This can very quickly become unreadable if the constructor has a lot of dependencies. A pattern employed to improve readability in a situation like this is to create a struct that lists all the parameters of the function as fields and changing the function to accept that struct instead. This is referred to as a parameter object. Dig has first class support for parameter objects: any struct embedding inject.In gets treated as a parameter object. The following is equivalent to the constructor above. Handlers can receive any combination of parameter objects and parameters. Result objects are the flip side of parameter objects. These are structs that represent multiple outputs from a single function as fields in the struct. Structs embedding inject.Out get treated as result objects. The above is equivalent to, Constructors often don't have a hard dependency on some types and are able to operate in a degraded state when that dependency is missing. Dig supports declaring dependencies as optional by adding an `optional:"true"` tag to fields of a inject.In struct. Fields in a inject.In structs that have the `optional:"true"` tag are treated as optional by Dig. If an optional field is not available in the container, the constructor will receive a zero value for the field. Constructors that declare dependencies as optional MUST handle the case of those dependencies being absent. The optional tag also allows adding new dependencies without breaking existing consumers of the constructor. Some use cases call for multiple values of the same type. Dig allows adding multiple values of the same type to the container with the use of Named Values. Named Values can be produced by passing the inject.Name option when a constructor is provided. All values produced by that constructor will have the given name. Given the following constructors, You can provideWithConstructor *sql.DB into a Container under different names by passing the inject.Name option. Alternatively, you can produce a inject.Out struct and tag its fields with `name:".."` to have the corresponding value added to the graph under the specified name. Regardless of how a Named Value was produced, it can be consumed by another constructor by accepting a inject.In struct which has exported fields with the same name AND type that you provided. The name tag may be combined with the optional tag to declare the dependency optional. Added in Dig 1.2. Dig provides value groups to allow producing and consuming many values of the same type. Value groups allow constructors to send values to a named, unordered collection in the container. Other constructors can request all values in this collection as a slice. Constructors can send values into value groups by returning a inject.Out struct tagged with `group:".."`. Any number of constructors may provideWithConstructor values to this named collection. Other constructors can request all values for this collection by requesting a slice tagged with `group:".."`. This will execute all constructors that provideWithConstructor a value to that group in an unspecified order. Note that values in a value group are unordered. Dig makes no guarantees about the order in which these values will be produced.
Package depends is a small, versatile dependency injection library. The basic usage is that you create a Context to register different types again, and then you ask for things by type using the Inject or TryInject function. A global Context is provided by default for convenience. The main use case envisioned for this package is as an alternative for using global values. By using a Context instead, it is possible to provide mock or alternate values during testing or when certain code demands it. Check out the examples and tests to find out more about how this package can be used A word of warning: using this library trades a certain amount of compile time safety (accessing global variables for instance) for run time checks (checking that a dependency has actually been registered when we ask for it). This is an important tradeoff to consider. In cases wherein dependencies are injected and used early on, a fast failure will be easy to spot, and the advantage of being able to mock, adjust and easily access dependencies can outweigh the downsides. On the other hand, rarely-run functions making use of more obscure dependencies (that you could have forgotten to actually register) could lead to annoying and unnecesary failures.
Package echo provides dependency injection definitions.
Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Service Provider Interface used for dependency injection IOC. Service Descriptor used for dependency injection IOC. Service Provider used for dependency injection IOC. Service Scope used for dependency injection IOC. Service Type Enum used for dependency injection IOC.
https://github.com/google/guice/wiki/Motivation This project is in no way affiliated with the Guice project, but I recommend reading their docs to better understand the concepts. A Module is analogous to Guice's AbstractModule, used for setting up your dependencies. This allows you to bind structs, struct pointers, interfaces, and primitives to singletons, constructors, with or without tags. An interface can have a binding to another type, or to a singleton or constructor. An interface can also be bound to a singleton or constructor. A struct, struct pointer, or primitive must have a direct binding to a singleton or constructor. All errors from binding will be returned as one error when calling inject.NewInjector(...). An Injector is analogous to Guice's Injector, providing your dependencies. Given the binding: We are able to get a value for SayHello. See the Injector interface for other methods. A constructor is a function that takes injected values as parameters, and returns a value and an error. We can set up a constructor to take zero values, or values that require a binding in some module passed to NewInjector(). A singleton constructor will be called exactly once for the entire application. The simplest way of binding an interface to a constructor function is to use the `BindConstructor` or `BindSingletonConstructor` methods. They automatically determine the interface type that is bound to the constructor from the constructor's return value. The following examples are equivalent to the more verbose ones above: A singleton bound through a constructor function can be marked as _eager_, in which case it will be constructed automatically by the injector during the injector creation process. The advantage is that every time the singleton is injected it is already available, whereas a normal (_lazy_) singleton has to be created before injecting it the first time. Eager singletons also reveal initialization problems sooner - at the time of injector creation rather than the first time the singleton is used. In addition, an eager singleton can be combined with an additional arbitrary function call, that will also be performed by the injector on construction. This can be used, for example, to initialize a "traditional" singleton implemented with a global variable: Functions can be called from an injector using the Call function. These functions have the same parameter requirements as constructors, but can have any return types. See the methods on Module and Constructor for more details. A tag allows named multiple bindings of one type. As an example, let's consider if we want to have multiple ways to say hello. Structs can also be populated using the tag "inject". Constructors can be tagged using structs, either named or anonymous. A constructor can mix tagged values with untagged values in the input struct. The CallTagged function works similarly to Call, except can take parameters like a tagged constructor. Both Module and Injector implement fmt.Stringer for inspection, however this may be added to in the future to allow semantic inspection of bindings. For testing, production modules may be overridden with test bindings as follows:
Package iris implements the highest realistic performance, easy to learn Go web framework. Iris provides a beautifully expressive and easy to use foundation for your next website, API, or distributed app. Low-level handlers compatible with `net/http` and high-level fastest MVC implementation and handlers dependency injection. Easy to learn for new gophers and advanced features for experienced, it goes as far as you dive into it! Source code and other details for the project are available at GitHub: 12.2.0-beta4 The only requirement is the Go Programming Language, at least version 1.18. Wiki: Examples: Middleware: Home Page:
Package graph may be useful for developers tasked with storage, compute and network management for cloud microservices. The library provides types and functions that enable a modular, extensible programming model. Resource interface is a declarative abstraction of a storage, compute or network service. Resources may have a Dependency order of creation and deletion. Idiomatic resources may have a single backing structure for fulfilling the interface. The library utilizes this backing structure to locate and inject public properties of a resource during execution. The library manages a collection of related resources at a given time. The Sync() function provides a method for managing a collection of resources: The library tries to execute multiple resources concurrently. There is a handy ErrorMapper interface that allows developers to query resource specific errors. Use the following code snippet: This example shows basic resource synchronization. There are three different resources that we need to build: an AWS Kinesis stream, an Aws Dynamo DB table, and finally a Kubernetes deployment of a micro- service that depends on both of the other resources being created properly.
Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package inject provides utilities for mapping and injecting dependencies in various ways.
Package fx is a framework that makes it easy to build applications out of reusable, composable modules. Fx applications use dependency injection to eliminate globals without the tedium of manually wiring together function calls. Unlike other approaches to dependency injection, Fx works with plain Go functions: you don't need to use struct tags or embed special types, so Fx automatically works well with most Go packages. Basic usage is explained in the package-level example below. If you're new to Fx, start there! Advanced features, including named instances, optional parameters, and value groups, are explained under the In and Out types. To test functions that use the Lifecycle type or to write end-to-end tests of your Fx application, use the helper functions and types provided by the go.uber.org/fx/fxtest package.
Package fx is a framework that makes it easy to build applications out of reusable, composable modules. Fx applications use dependency injection to eliminate globals without the tedium of manually wiring together function calls. Unlike other approaches to dependency injection, Fx works with plain Go functions: you don't need to use struct tags or embed special types, so Fx automatically works well with most Go packages. Basic usage is explained in the package-level example below. If you're new to Fx, start there! Advanced features, including named instances, optional parameters, and value groups, are explained under the In and Out types. To test functions that use the Lifecycle type or to write end-to-end tests of your Fx application, use the helper functions and types provided by the go.uber.org/fx/fxtest package.
Dependency Injection by annotations for Golang https://github.com/lokstory/digo
Package di implements a dependency injection (DI) container.
Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package inject provides utilities for mapping and injecting dependencies in various ways.
Package xstats is a generic client for service instrumentation. xstats is inspired from Go-kit's metrics (https://github.com/go-kit/kit/tree/master/metrics) package but it takes a slightly different path. Instead of having to create an instance for each metric, xstats use a single instance to log every metrics you want. This reduces the boiler plate when you have a lot a metrics in your app. It's also easier in term of dependency injection. Talking about dependency injection, xstats comes with a xhandler.Handler integration so it can automatically inject the xstats client within the net/context of each request. Each request's xstats instance have its own tags storage ; This let you inject some per request contextual tags to be included with all observations sent within the lifespan of the request. xstats is pluggable and comes with integration for StatsD and DogStatsD, the Datadog (http://datadoghq.com) augmented version of StatsD with support for tags. More integration may come later (PR welcome).
Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package fx is a framework that makes it easy to build applications out of reusable, composable modules. Fx applications use dependency injection to eliminate globals without the tedium of manually wiring together function calls. Unlike other approaches to dependency injection, Fx works with plain Go functions: you don't need to use struct tags or embed special types, so Fx automatically works well with most Go packages. Basic usage is explained in the package-level example below. If you're new to Fx, start there! Advanced features, including named instances, optional parameters, and value groups, are explained under the In and Out types. To test functions that use the Lifecycle type or to write end-to-end tests of your Fx application, use the helper functions and types provided by the go.uber.org/fx/fxtest package.
Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package execstub provides stubbing for a usage of a command line api which is based on an executable discovered using the environment <PATH> or some sort of <HOME>+<Bin> configuration. What is a usage of a command line api? Its when you spawn a sub-process using a programming language API. Think go exec.Cmd.Run(..), java Runtime.exec(..), python subprocess.run(..). The sub-process execution will yield an outcome consisting of: side effects (e.g. a file created when executing touch). bytes or string in std-out and/or std-err. an exit code. The executed binary is typically specified using a path like argument. It can be: a absolute path a relative path the name of the binary Discovering the executable How the binary is discovered depends on the art the specified path like argument. The goal of the discovery process is to transform the path like specification into an absolute path, so that if the specification is done with: absolute path nothing is left to be done relative path it will be appended to the current directory to form an absolute path name of the binary a file with that name will be search in the directories specified by the PATH environment variable. The first found will be used. On some platforms known and specified file extensions (e.g. .exe) will be appended to the name during the search. Even when using absolute paths, you may decide to put a customization strategy using some process environment variable. We call this the home-bin-dir strategy. E.g. Java executed base on JAVA_HOME or JRE_HOME with the java executable located at ${JAVA_HOME}/bin/java Stubbing mechanism The aim os stubbing is to replace at execution time the actual executable with a fake one which will yield some kind of pre-defined known outcome. This can be done if there is step in the binary discovery which can be tweaked so that the stud-executable is discovered instead of the actual one. It is the case if binary is specified by name and discovered using PATH or when absolute path is used but with a customization layer in place based on defined environment home variable. The mechanism will just have to mutate the PATH or set the home variable accordingly. Stubbing become complicated if the specification is based on absolute (without customization layer) or relative path because it will require e.g.: a file overley to hide the original executable a change of the current directory an in the flight replacement of the original executable and a rollback. These are either not desirable, or too heavy especially in a unit-test-ish context. The execstub module will therefore only provide stubbing for PATH and Home-Bin-Dir based discovery. Design elements Modeling the command line usage We have basically 3 aspects to model: Starting the process It is modeled using StubRequest which hold the the command name and the execution argument so that the fake execution process can be function of them. Execution The outcome can be a static sum of known in advance stderr, stdout and exit code. This is referred to as static mode. It may also be desirale to have some side effects, e.g.: related to the execution itself like creating a file or related to the unit-test as counting the number of calls In other constellations the outocome may requires some computation to determine stderr/stdout/exicode as function of the request. We refer to these cases as dynamic mode. The execution is therefore modelled as function namely StubFunc. Thus, if required the StubFunc corresponding to the current stubbing will be looked-up and run. Outcome The stderr/stdout/exit-code part of the outcome is modeled as ExecOutcome. The execution the the stubfunc may result however in an error. Such error is not an actual sub-process execution erroneous outcome. It therefore must be modeled separately as opposed to be added to stderr and setting a non-zero exit code. Such and error can be communicated by using the ExecOutcome field InternalErrTxt. Stub-Executable It is the fake executable used to effectuate the overall outcome. It may release the outcome by itself. It may also cooperate with a test helper to achieve the outcome. The following command line is used: /tmp/go-build720053430/b001/xyz.test -test.run=TestHelperProcess -- arg1 arg2 arg3 It is not possible to use the test helper directly because we will need to inject the args test.run and -- at the actual execution call site. Two kinds of stub-executable are provided: bash based, which uses a bash script exec base, which used an go based executable Obviously the go based one is bound to support more platform than the bash based one. Both executable are genric and need context information about the stubbing for which they will be used. This context data is modeled as CmdConfig and saved as file alongside the executable. Inter process communication (IPC) to support dynamic outcomes The invocation of a StubFunc to produce a dynamic outcome is done in the unit test process. There is no means to access the stub function directly from the fake process execution. IPC is used here to allow the fake process to issue a StubRequest and receive an ExecOutcome. The Serialization/Deserialization mechanism needed for IPC must be understood by both parties (mind bash) and satisfy a domain specific requirement of been able to cope with multiline sterr and stdout. We choose a combination of : base64 to encode the discrete data (e.g. stderr, stdout) and comma separated value (easily encoded and decoded in bash) for envelope encoding Named pipes are used for the actual data transport, because they are file based and easily handle in different setups (e.g. in bash). Stubbing Setup An ExecStubber is provided to manage the stubbing setup. Its key feature is to setup an invokation of a StubFunc to replace the execution of a process, See ExecStubber.WhenExecDoStubFunc(...). It allows settings beyond the basic requirement of specifying the executable to be stubbed and a StubFunc replacement. This is modeled using Settings, which provides the following configuration options: Selecting and customizing the discovery mode (PATH vs. Home-Bin-Dir) Selecting the stub executable (Bash vs. Exec(go based)) Selecting the stubbing mode (static vs. dynamic) Specifying the test process helper method name specifying a timeout for a stub sub-process execution A stubbing setup is identified by a key. The key can be use to: unwind the setup(Unregister(..)) access the stubbing data basis of static requests (FindAllPersistedStubRequests, DeleteAllPersistedStubRequests ). Concurrency and parallelism The mutation of the process environment is the key enabling mechanism of Execstub. The process environment must therefore be guarded against issues of concurrency and parallelism. This also mean that is not possible to have a parallel stubbing setup for the same executable within a test process. The outcome will otherwise be non-deterministic because the setting will likely override each other. ExecStubber provides a locking mechanism to realize the serialization of the mutation of environment. For this to work correctly however there must only be one ExecStubber per unit test process. Note that the code under test can still execute its sub-processes concurrently or in parallel. The correctness of the outcome here dependents on the implementation of the StubFunc function being used. Static outcomes without side effect are of course always deterministic.
Package fx is a framework that makes it easy to build applications out of reusable, composable modules. Fx applications use dependency injection to eliminate globals without the tedium of manually wiring together function calls. Unlike other approaches to dependency injection, Fx works with plain Go functions: you don't need to use struct tags or embed special types, so Fx automatically works well with most Go packages. Basic usage is explained in the package-level example below. If you're new to Fx, start there! Advanced features, including named instances, optional parameters, and value groups, are explained under the In and Out types. To test functions that use the Lifecycle type or to write end-to-end tests of your Fx application, use the helper functions and types provided by the go.uber.org/fx/fxtest package.
Package inject provides utilities for mapping and injecting dependencies in various ways.
Package inject provides utilities for mapping and injecting dependencies. Package inject provides utilities for mapping and injecting dependencies in various ways.
Package inject provides a reflect based injector. A large application built with dependency injection in mind will typically involve the boring work of setting up the object graph. This library attempts to take care of this boring work by creating and connecting the various objects. Its use involves you seeding the object graph with some (possibly incomplete) objects, where the underlying types have been tagged for injection. Given this, the library will populate the objects creating new ones as necessary. It uses singletons by default, supports optional private instances as well as named instances. It works using Go's reflection package and is inherently limited in what it can do as opposed to a code-gen system with respect to private fields. The usage pattern for the library involves struct tags. It requires the tag format used by the various standard libraries, like json, xml etc. It involves tags in one of the three forms below: The first no value syntax is for the common case of a singleton dependency of the associated type. The second triggers creation of a private instance for the associated type. Finally the last form is asking for a named dependency called "dev logger".
Package hub implements a simple publish/subscribe API for application events. Different subsystems within an application can send notifications without having hard dependencies on each other. Dependency injection often benefits from this approach. Examples include sending server start and stop events to other components and service discovery events from libraries like consul. This package is an example of the Mediator design pattern (see https://en.wikipedia.org/wiki/Mediator_pattern). It is focused on managing application-layer events within a process. It is not intended as a general pub/sub library for distributed notifications, although it can serve as a basis for such an implementation. Rather than requiring a specific listener interface or approach to handling events, this package supports several kinds of listeners via the Subscriber interface: (1) A function with exactly one input argument and no outputs. The input argument cannot be an interface type. The sole input type is the event type that can be passed to Publish. (2) A bidrectional or send-only channel. The channel's element type cannot be an interface. The channel's element type can be passed to Publish, which will then place it onto the channel. NOTE: If a channel subscription is cancelled, the channel passed to Subscribe is NOT closed by default. Clients can explicitly close the channel in an afterCancel closure: (3) Any type (not just a struct) with a single method of the same signature described in (1). Any other type passed to Subscribe results in ErrInvalidListener.
Package linker provides Dependency Injection and Inversion of Control functionality. The core component is Injector, which allows to register Components. Component is an object, which can have any type, which requires some initialization, or can be used for initializing other components. Every component is registered in the Injector by the component name or anonymously (empty name). Same object can be registered by different names. This could be useful if the object implements different interfaces that can be used by different components. The package contains several interfaces: PostConstructor, Initializer and Shutdowner, which could be implemented by components with a purpose to be called by Injector on different initialization/de-initialization phases. Init() function of Injector allows to initialize registered components. The initialization process supposes that components with 'pointer to struct' type or interfaces, which contains a 'pointer to struct' will be initialized. The initialization supposes to inject (assign) the struct fields values using other registered components. Injector matches them by name or by type. Injector uses fail-fast strategy so any error is considered like misconfiguraion and a panic happens. When all components are initialized, the components, which implement PostConstructor interface will be notified via PostConsturct() function call. The order of PostConstruct() calls is not defined. After the construction phase, injector builds dependencies graph with a purpose to detect dependency loops and to establish components initialization order. If a dependency loop is found, Injector will panic. Components, which implement Initializer interface, will be notified in specific order by Init(ctx) function call. Less dependant components will be initialized before the components that have dependency on the first ones. Injector is supposed to be called from one go-routine and doesn't support calls from multiple go-routines. Initialization process could take significant time, so context is provided. If the context is cancelled or closed it will be detected either by appropriate component or by the Injector what will cause of de-intializing already initialized components using Shutdown() function call (if provided) in reverse of the initialization order. Panic will happen then.
Package container provides an IoC container for Go projects. It provides simple, fluent and easy-to-use interface to make dependency injection in GoLang easier.
Package controllerruntime provides tools to construct Kubernetes-style controllers that manipulate both Kubernetes CRDs and aggregated/built-in Kubernetes APIs. It defines easy helpers for the common use cases when building CRDs, built on top of customizable layers of abstraction. Common cases should be easy, and uncommon cases should be possible. In general, controller-runtime tries to guide users towards Kubernetes controller best-practices. The main entrypoint for controller-runtime is this root package, which contains all of the common types needed to get started building controllers: The examples in this package walk through a basic controller setup. The kubebuilder book (https://book.kubebuilder.io) has some more in-depth walkthroughs. controller-runtime favors structs with sane defaults over constructors, so it's fairly common to see structs being used directly in controller-runtime. A brief-ish walkthrough of the layout of this library can be found below. Each package contains more information about how to use it. Frequently asked questions about using controller-runtime and designing controllers can be found at https://github.com/kubernetes-sigs/controller-runtime/blob/master/FAQ.md. Every controller and webhook is ultimately run by a Manager (pkg/manager). A manager is responsible for running controllers and webhooks, and setting up common dependencies (pkg/runtime/inject), like shared caches and clients, as well as managing leader election (pkg/leaderelection). Managers are generally configured to gracefully shut down controllers on pod termination by wiring up a signal handler (pkg/manager/signals). Controllers (pkg/controller) use events (pkg/events) to eventually trigger reconcile requests. They may be constructed manually, but are often constructed with a Builder (pkg/builder), which eases the wiring of event sources (pkg/source), like Kubernetes API object changes, to event handlers (pkg/handler), like "enqueue a reconcile request for the object owner". Predicates (pkg/predicate) can be used to filter which events actually trigger reconciles. There are pre-written utilities for the common cases, and interfaces and helpers for advanced cases. Controller logic is implemented in terms of Reconcilers (pkg/reconcile). A Reconciler implements a function which takes a reconcile Request containing the name and namespace of the object to reconcile, reconciles the object, and returns a Response or an error indicating whether to requeue for a second round of processing. Reconcilers use Clients (pkg/client) to access API objects. The default client provided by the manager reads from a local shared cache (pkg/cache) and writes directly to the API server, but clients can be constructed that only talk to the API server, without a cache. The Cache will auto-populate with watched objects, as well as when other structured objects are requested. The default split client does not promise to invalidate the cache during writes (nor does it promise sequential create/get coherence), and code should not assume a get immediately following a create/update will return the updated resource. Caches may also have indexes, which can be created via a FieldIndexer (pkg/client) obtained from the manager. Indexes can used to quickly and easily look up all objects with certain fields set. Reconcilers may retrieve event recorders (pkg/recorder) to emit events using the manager. Clients, Caches, and many other things in Kubernetes use Schemes (pkg/scheme) to associate Go types to Kubernetes API Kinds (Group-Version-Kinds, to be specific). Similarly, webhooks (pkg/webhook/admission) may be implemented directly, but are often constructed using a builder (pkg/webhook/admission/builder). They are run via a server (pkg/webhook) which is managed by a Manager. Logging (pkg/log) in controller-runtime is done via structured logs, using a log set of interfaces called logr (https://godoc.org/github.com/go-logr/logr). While controller-runtime provides easy setup for using Zap (https://go.uber.org/zap, pkg/log/zap), you can provide any implementation of logr as the base logger for controller-runtime. Metrics (pkg/metrics) provided by controller-runtime are registered into a controller-runtime-specific Prometheus metrics registry. The manager can serve these by an HTTP endpoint, and additional metrics may be registered to this Registry as normal. You can easily build integration and unit tests for your controllers and webhooks using the test Environment (pkg/envtest). This will automatically stand up a copy of etcd and kube-apiserver, and provide the correct options to connect to the API server. It's designed to work well with the Ginkgo testing framework, but should work with any testing setup. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support This example creates a simple application Controller that is configured for ReplicaSets and Pods. This application controller will be running leader election with the provided configuration in the manager options. If leader election configuration is not provided, controller runs leader election with default values. Default values taken from: https://github.com/kubernetes/apiserver/blob/master/pkg/apis/config/v1alpha1/defaults.go * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package inject provides a reflect based injector. A large application built with dependency injection in mind will typically involve the boring work of setting up the object graph. This library attempts to take care of this boring work by creating and connecting the various objects. Its use involves you seeding the object graph with some (possibly incomplete) objects, where the underlying types have been tagged for injection. Given this, the library will populate the objects creating new ones as necessary. It uses singletons by default, supports optional private instances as well as named instances. It works using Go's reflection package and is inherently limited in what it can do as opposed to a code-gen system with respect to private fields. The usage pattern for the library involves struct tags. It requires the tag format used by the various standard libraries, like json, xml etc. It involves tags in one of the three forms below: The first no value syntax is for the common case of a singleton dependency of the associated type. The second triggers creation of a private instance for the associated type. Finally the last form is asking for a named dependency called "dev logger".
Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package inject provides utilities for mapping and injecting dependencies in various ways.
Package inject provides utilities for mapping and injecting dependencies in various ways.
Package xstats is a generic client for service instrumentation. xstats is inspired from Go-kit's metrics (https://github.com/go-kit/kit/tree/master/metrics) package but it takes a slightly different path. Instead of having to create an instance for each metric, xstats use a single instance to log every metrics you want. This reduces the boiler plate when you have a lot a metrics in your app. It's also easier in term of dependency injection. Talking about dependency injection, xstats comes with a xhandler.Handler integration so it can automatically inject the xstats client within the net/context of each request. Each request's xstats instance have its own tags storage ; This let you inject some per request contextual tags to be included with all observations sent within the lifespan of the request. xstats is pluggable and comes with integration for StatsD and DogStatsD, the Datadog (http://datadoghq.com) augmented version of StatsD with support for tags. More integration may come later (PR welcome).
Package controllerruntime alias' common functions and types to improve discoverability and reduce the number of imports for simple Controllers. This example creates a simple application Controller that is configured for ReplicaSets and Pods. * Create a new application for ReplicaSets that manages Pods owned by the ReplicaSet and calls into ReplicaSetReconciler. * Start the application. TODO(pwittrock): Update this example when we have better dependency injection support
Package `di` implements basic dependency injection (DI) container.
Package dinit performs Dependency Injection (DI) for initializer functions.