private ProgressEventDispatcher(IEventHandlers eventHandlers, Allocation allocation) { this.eventHandlers = eventHandlers; this.allocation = allocation; remainingAllocationUnits = allocation.GetAllocationUnits(); }
public Factory( IEventHandlers eventHandlers, RegistryEndpointRequestProperties registryEndpointRequestProperties) { this.eventHandlers = eventHandlers; this.registryEndpointRequestProperties = registryEndpointRequestProperties; }
/** * Builds the container. * * @param containerizer the {@link Containerizer} that configures how to containerize * @return the built container * @throws IOException if an I/O exception occurs * @throws CacheDirectoryCreationException if a directory to be used for the cache could not be * created * @throws HttpHostConnectException if fib failed to connect to a registry * @throws RegistryUnauthorizedException if a registry request is unauthorized and needs * authentication * @throws RegistryAuthenticationFailedException if registry authentication failed * @throws UnknownHostException if the registry does not exist * @throws InsecureRegistryException if a server could not be verified due to an insecure * connection * @throws RegistryException if some other error occurred while interacting with a registry * @throws ExecutionException if some other exception occurred during execution * @throws InterruptedException if the execution was interrupted */ public async Task <FibContainer> ContainerizeAsync(IContainerizer containerizer) { containerizer = containerizer ?? throw new ArgumentNullException(nameof(containerizer)); BuildConfiguration buildConfiguration = ToBuildConfiguration(containerizer); IEventHandlers eventHandlers = buildConfiguration.GetEventHandlers(); LogSources(eventHandlers); using (new TimerEventDispatcher(eventHandlers, containerizer.GetDescription())) { try { IBuildResult result = await containerizer.CreateStepsRunner(buildConfiguration).RunAsync().ConfigureAwait(false); return(new FibContainer(result.GetImageDigest(), result.GetImageId())); } catch (Exception ex) { eventHandlers.Dispatch(LogEvent.Error(ex.Message)); // If an ExecutionException occurs, re-throw the cause to be more easily handled by the user if (ex.InnerException is RegistryException) { throw (RegistryException)ex.InnerException; } throw; } } }
/** Instantiate with {@link #builder}. */ private BuildConfiguration( ImageConfiguration baseImageConfiguration, ImageConfiguration targetImageConfiguration, ImmutableHashSet <string> additionalTargetImageTags, ContainerConfiguration containerConfiguration, LayersCache baseImageLayersCache, LayersCache applicationLayersCache, ManifestFormat targetFormat, bool allowInsecureRegistries, bool offline, ImmutableArray <ILayerConfiguration> layerConfigurations, string toolName, string toolVersion, IEventHandlers eventHandlers) { this.baseImageConfiguration = baseImageConfiguration; this.targetImageConfiguration = targetImageConfiguration; this.additionalTargetImageTags = additionalTargetImageTags; this.containerConfiguration = containerConfiguration; this.baseImageLayersCache = baseImageLayersCache; this.applicationLayersCache = applicationLayersCache; this.targetFormat = targetFormat; this.allowInsecureRegistries = allowInsecureRegistries; this.offline = offline; this.layerConfigurations = layerConfigurations; this.toolName = toolName; this.toolVersion = toolVersion; this.eventHandlers = eventHandlers; }
/// <summary> /// Set up the file system watcher, add to the delegate 'changed' an anonymous function which /// loads the updates and updates AlignmentUpdateListeners. /// </summary> /// <param name="eventHandlers"></param> public void Init(IEventHandlers eventHandlers) { eventHandlers.SubscribeOnStart(OnStart); //Allow for the delegates to be deleted. eventHandlers.SubscribeOnApplicationQuit(OnApplicationQuit); }
public void Init(IEventHandlers eventHandlers) { eventHandlers.SubscribeOnUpdate(Update); eventHandlers.SubscribeOnReady(() => { Initialized = true; }); }
/// <summary> /// /// </summary> /// <param name="protocolName"></param> /// <param name="factory"></param> /// <param name="handlers"></param> /// <param name="dOManager"></param> /// <param name="logger"></param> public ProtocolProcessor(string protocolName, IEventFactory factory, IEventHandlers handlers, IDOManager dOManager, ILogger logger) { this.protocolName = protocolName; this.factory = factory; this.handlers = handlers; this.logger = logger; this.dOManager = dOManager; }
public void Init(IEventHandlers eventHandlers) { #if !NET_2_0_SUBSET eventHandlers.SubscribeOnAwake(SceneStartAnalytics); eventHandlers.SubscribeOnApplicationQuit(SceneStopAnalytics); eventHandlers.SubscribeOnStart(InitSlamLocalizerAnalytics); #endif }
/// <summary> Initialises this object. </summary> /// <param name="eventHandlers"> The event handlers. </param> public void Init(IEventHandlers eventHandlers) { eventHandlers.SubscribeOnAwake(Awake); eventHandlers.SubscribeOnStart(Start); eventHandlers.SubscribeOnUpdate(Update); eventHandlers.SubscribeOnLateUpdate(LateUpdate); eventHandlers.SubscribeOnDestroy(OnDestroy); }
/** * Creates a new {@link ProgressEventDispatcher} and dispatches a new {@link ProgressEvent} with * progress 0 for {@code allocation}. * * @param eventHandlers the {@link EventHandlers} * @param allocation the {@link Allocation} to manage * @return a new {@link ProgressEventDispatcher} */ private static ProgressEventDispatcher NewProgressEventDispatcher( IEventHandlers eventHandlers, Allocation allocation) { ProgressEventDispatcher progressEventDispatcher = new ProgressEventDispatcher(eventHandlers, allocation); progressEventDispatcher.DispatchProgress(0); return(progressEventDispatcher); }
public TimerEventDispatcher( IEventHandlers eventHandlers, string description, IClock clock, Timer parentTimer) { this.eventHandlers = eventHandlers; this.description = description; this.clock = clock; timer = new Timer(clock, parentTimer); DispatchTimerEvent(State.START, Duration.Zero, description); }
/// <summary> /// Initializes a new instance of the <see cref="EventHandlersService"/> class. /// </summary> /// <param name="eventHandlers">The <see cref="IEventHandlers"/> to use to perform operations on Event Handlers.</param> /// <param name="exceptionToFailureConverter">The <see cref="IExceptionToFailureConverter"/> to use to convert exceptions to failures.</param> /// <param name="streamProcessorStatusConverter">The <see cref="IConvertStreamProcessorStatuses"/> to use to convert stream processor states.</param> /// <param name="logger">The logger to use for logging.</param> public EventHandlersService( IEventHandlers eventHandlers, IExceptionToFailureConverter exceptionToFailureConverter, IConvertStreamProcessorStatuses streamProcessorStatusConverter, ILogger logger) { _eventHandlers = eventHandlers; _exceptionToFailureConverter = exceptionToFailureConverter; _streamProcessorStatusConverter = streamProcessorStatusConverter; _logger = logger; }
public ManifestPusher( RegistryEndpointRequestProperties registryEndpointRequestProperties, IBuildableManifestTemplate manifestTemplate, string imageTag, IEventHandlers eventHandlers) { this.registryEndpointRequestProperties = registryEndpointRequestProperties; this.manifestTemplate = manifestTemplate; this.imageTag = imageTag; this.eventHandlers = eventHandlers; }
/** * Returns a factory for {@link Connection}. * * @return {@link Connection} factory, a function that generates a {@link Connection} to a Uri */ public static Func <Uri, Connection> GetConnectionFactory(IEventHandlers eventHandlers = null) { /* * Do not use {@link NetHttpTransport}. It does not process response errors properly. A new * {@link ApacheHttpTransport} needs to be created for each connection because otherwise HTTP * connection persistence causes the connection to throw {@link NoHttpResponseException}. * * @see <a * href="https://github.com/google/google-http-java-client/issues/39">https://github.com/google/google-http-java-client/issues/39</a> */ return(url => new Connection(url, eventHandlers)); }
/** * Instantiate with {@link #factory}. * * @param eventHandlers the event handlers used for dispatching log events * @param authorization the {@link Authorization} to access the registry/repository * @param registryEndpointRequestProperties properties of registry endpoint requests * @param allowInsecureRegistries if {@code true}, insecure connections will be allowed */ private RegistryClient( IEventHandlers eventHandlers, Authorization authorization, RegistryEndpointRequestProperties registryEndpointRequestProperties, bool allowInsecureRegistries, IEnumerable <ProductInfoHeaderValue> userAgent) { this.eventHandlers = eventHandlers; this.authorization = authorization; this.registryEndpointRequestProperties = registryEndpointRequestProperties; this.allowInsecureRegistries = allowInsecureRegistries; this.userAgent = userAgent; }
public void SetUp() { mockEventHandlers = Mock.Of <IEventHandlers>(); v22manifestJsonFile = Paths.Get(TestResources.GetResource("core/json/v22manifest.json").ToURI()); fakeManifestTemplate = JsonTemplateMapper.ReadJsonFromFile <V22ManifestTemplate>(v22manifestJsonFile); testManifestPusher = new ManifestPusher( new RegistryEndpointRequestProperties("someServerUrl", "someImageName"), fakeManifestTemplate, "test-image-tag", mockEventHandlers); }
private async Task <BaseImageWithAuthorization> GetOauthBaseImage(IEventHandlers eventHandlers, ProgressEventDispatcher progressEventDispatcher) { try { RetrieveRegistryCredentialsStep retrieveBaseRegistryCredentialsStep = RetrieveRegistryCredentialsStep.ForBaseImage( buildConfiguration, progressEventDispatcher.NewChildProducer(), this.Index); Credential registryCredential = await retrieveBaseRegistryCredentialsStep.GetFuture().ConfigureAwait(false); Authorization registryAuthorization = registryCredential?.IsOAuth2RefreshToken() != false ? null : Authorization.FromBasicCredentials( registryCredential.GetUsername(), registryCredential.GetPassword()); RegistryAuthenticator registryAuthenticator = await buildConfiguration .NewBaseImageRegistryClientFactory() .NewRegistryClient() .GetRegistryAuthenticatorAsync().ConfigureAwait(false); if (registryAuthenticator != null) { Authorization pullAuthorization = await registryAuthenticator.AuthenticatePullAsync(registryCredential, eventHandlers) .ConfigureAwait(false); return(new BaseImageWithAuthorization( await PullBaseImageAsync(pullAuthorization, progressEventDispatcher) .ConfigureAwait(false), pullAuthorization)); } } catch (Exception e) { // Cannot skip certificate validation or use HTTP; fall through. eventHandlers.Dispatch(LogEvent.Error(Resources.PullBaseImageStepAuthenticationErrorMessage + ",err:" + e.Message)); throw; } eventHandlers.Dispatch(LogEvent.Error(Resources.PullBaseImageStepAuthenticationErrorMessage + ",err:BaseImageCredential not config ")); throw new Exception("BaseImageCredential not config"); }
public void SetUp() { mockEventHandlers = Mock.Of <IEventHandlers>(); mockConnection = Mock.Of <IConnection>(); mockInsecureConnection = Mock.Of <IConnection>(); mockConnectionFactory = Mock.Of <Func <Uri, IConnection> >(); mockInsecureConnectionFactory = Mock.Of <Func <Uri, IConnection> >(); secureEndpointCaller = CreateRegistryEndpointCaller(false, -1); Mock.Get(mockConnectionFactory).Setup(m => m(It.IsAny <Uri>())).Returns(mockConnection); Mock.Get(mockInsecureConnectionFactory).Setup(m => m(It.IsAny <Uri>())).Returns(mockInsecureConnection); mockResponse = new HttpResponseMessage { Content = new StringContent("body") }; }
/// <summary> /// Initializes a new instance of the <see cref="EventHandlersService"/> class. /// </summary> /// <param name="hostApplicationLifetime">The <see cref="IHostApplicationLifetime" />.</param> /// <param name="reverseCallServices">The <see cref="IInitiateReverseCallServices" />.</param> /// <param name="eventHandlersProtocol">The <see cref="IEventHandlersProtocol" />.</param> /// <param name="eventHandlers">The <see cref="IEventHandlers" />.</param> /// <param name="eventHandlerFactory">The <see cref="IEventHandlerFactory"/>.</param> /// <param name="configuration">The <see cref="EventHandlersConfiguration"/></param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param> public EventHandlersService( IHostApplicationLifetime hostApplicationLifetime, IInitiateReverseCallServices reverseCallServices, IEventHandlersProtocol eventHandlersProtocol, IEventHandlers eventHandlers, IEventHandlerFactory eventHandlerFactory, IOptions <EventHandlersConfiguration> configuration, ILoggerFactory loggerFactory) { _reverseCallServices = reverseCallServices; _eventHandlersProtocol = eventHandlersProtocol; _eventHandlers = eventHandlers; _eventHandlerFactory = eventHandlerFactory; _configuration = configuration; _logger = loggerFactory.CreateLogger <EventHandlersService>(); _hostApplicationLifetime = hostApplicationLifetime; }
/// <inheritdoc /> protected override void Setup(IServiceProvider services) { _eventStore = services.GetRequiredService <IEventStore>(); _eventHandlers = services.GetRequiredService <IEventHandlers>(); _eventHandlerFactory = services.GetRequiredService <IEventHandlerFactory>(); _eventTypes = Enumerable.Range(0, EventTypes).Select(_ => new ArtifactId(Guid.NewGuid())).ToArray(); var uncommittedEvents = new List <UncommittedEvent>(); foreach (var eventType in _eventTypes) { foreach (var _ in Enumerable.Range(0, Events)) { uncommittedEvents.Add(new UncommittedEvent("some event source", new Artifact(eventType, ArtifactGeneration.First), false, "{\"hello\": 42}")); } } foreach (var tenant in ConfiguredTenants) { _eventStore.Commit(new UncommittedEvents(uncommittedEvents), Runtime.CreateExecutionContextFor(tenant)).GetAwaiter().GetResult(); } }
private void LogSources(IEventHandlers eventHandlers) { // Logs the different source files used. var message = new StringBuilder(Resources.ContainerBuilderLogSourcesHeader); message.Append(":"); foreach (LayerConfiguration layerConfiguration in layerConfigurations) { if (layerConfiguration.LayerEntries.Length == 0) { continue; } message.Append(layerConfiguration.Name).Append(":file Counts:").Append(layerConfiguration.LayerEntries.Length); // // foreach (LayerEntry layerEntry in layerConfiguration.LayerEntries) // { // message.AppendLine("\t\t").Append(layerEntry.SourceFile); // } } eventHandlers.Dispatch(LogEvent.Info(message.ToString())); }
/// <summary> /// Adds the IEventReceiver functions to the delegates in order to be called from MetaManager /// </summary> public void Init(IEventHandlers eventHandlers) { eventHandlers.SubscribeOnUpdate(Update); }
/** * Authenticates permission to pull and push. * * @param credential the credential used to authenticate * @return an {@code Authorization} authenticating the push * @throws RegistryAuthenticationFailedException if authentication fails */ public async Task <Authorization> AuthenticatePushAsync(Credential credential, IEventHandlers eventHandlers) { return(await AuthenticateAsync(credential, "pull,push", eventHandlers).ConfigureAwait(false)); }
public async Task <BaseImageWithAuthorization> CallAsync() { IEventHandlers eventHandlers = buildConfiguration.GetEventHandlers(); // Skip this step if this is a scratch image ImageConfiguration baseImageConfiguration = buildConfiguration.GetBaseImageConfiguration(); string description = string.Format( CultureInfo.CurrentCulture, Resources.PullBaseImageStepDescriptionFormat, buildConfiguration.GetBaseImageConfiguration().GetImage()); eventHandlers.Dispatch(LogEvent.Progress(description)); if (baseImageConfiguration.GetImage().IsScratch()) { return(new BaseImageWithAuthorization( Image.CreateBuilder(buildConfiguration.GetTargetFormat()).Build(), null)); } if (buildConfiguration.IsOffline()) { return(new BaseImageWithAuthorization(PullBaseImageOffline(), null)); } using (ProgressEventDispatcher progressEventDispatcher = progressEventDispatcherFactory.Create(description, 2)) using (new TimerEventDispatcher(buildConfiguration.GetEventHandlers(), description)) { // First, try with no credentials. try { return(new BaseImageWithAuthorization(await PullBaseImageAsync(null, progressEventDispatcher).ConfigureAwait(false), null)); } catch (RegistryUnauthorizedException) { eventHandlers.Dispatch( LogEvent.Lifecycle( "The base image requires auth. Trying again for " + buildConfiguration.GetBaseImageConfiguration().GetImage() + "...")); // If failed, then, retrieve base registry credentials and try with retrieved credentials. // TODO: Refactor the logic in RetrieveRegistryCredentialsStep out to // registry.credentials.RegistryCredentialsRetriever to avoid this direct executor hack. RetrieveRegistryCredentialsStep retrieveBaseRegistryCredentialsStep = RetrieveRegistryCredentialsStep.ForBaseImage( buildConfiguration, progressEventDispatcher.NewChildProducer()); Credential registryCredential = await retrieveBaseRegistryCredentialsStep.GetFuture().ConfigureAwait(false); Authorization registryAuthorization = registryCredential?.IsOAuth2RefreshToken() != false ? null : Authorization.FromBasicCredentials( registryCredential.GetUsername(), registryCredential.GetPassword()); try { return(new BaseImageWithAuthorization( await PullBaseImageAsync(registryAuthorization, progressEventDispatcher).ConfigureAwait(false), registryAuthorization)); } catch (RegistryUnauthorizedException) { // The registry requires us to authenticate using the Docker Token Authentication. // See https://docs.docker.com/registry/spec/auth/token try { RegistryAuthenticator registryAuthenticator = await buildConfiguration .NewBaseImageRegistryClientFactory() .NewRegistryClient() .GetRegistryAuthenticatorAsync().ConfigureAwait(false); if (registryAuthenticator != null) { Authorization pullAuthorization = await registryAuthenticator.AuthenticatePullAsync(registryCredential).ConfigureAwait(false); return(new BaseImageWithAuthorization( await PullBaseImageAsync(pullAuthorization, progressEventDispatcher).ConfigureAwait(false), pullAuthorization)); } } catch (InsecureRegistryException) { // Cannot skip certificate validation or use HTTP; fall through. } eventHandlers.Dispatch(LogEvent.Error(Resources.PullBaseImageStepAuthenticationErrorMessage)); throw; } } } }
/** * Sends the authentication request and retrieves the Bearer authorization token. * * @param credential the credential used to authenticate * @param scope the scope of permissions to authenticate for * @return the {@link Authorization} response * @throws RegistryAuthenticationFailedException if authentication fails * @see <a * href="https://docs.docker.com/registry/spec/auth/token/#how-to-authenticate">https://docs.docker.com/registry/spec/auth/token/#how-to-authenticate</a> */ private async Task <Authorization> AuthenticateAsync(Credential credential, string scope, IEventHandlers eventHandlers) { try { using (Connection connection = Connection.GetConnectionFactory(eventHandlers)(GetAuthenticationUrl(credential, scope))) using (var request = new HttpRequestMessage()) { foreach (var value in userAgent) { request.Headers.UserAgent.Add(value); } if (IsOAuth2Auth(credential)) { string parameters = GetAuthRequestParameters(credential, scope); request.Content = new BlobHttpContent(Blobs.From(parameters), MediaType.FormData); } else if (credential != null) { Authorization authorization = Authorization.FromBasicCredentials(credential.GetUsername(), credential.GetPassword()); request.Headers.Authorization = new AuthenticationHeaderValue(authorization.GetScheme(), authorization.GetToken()); } if (IsOAuth2Auth(credential)) { request.Method = HttpMethod.Post; } else { request.Method = HttpMethod.Get; } string responseString; using (HttpResponseMessage response = await connection.SendAsync(request).ConfigureAwait(false)) using (StreamReader reader = new StreamReader(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), Encoding.UTF8)) { responseString = await reader.ReadToEndAsync().ConfigureAwait(false); } AuthenticationResponseTemplate responseJson = JsonTemplateMapper.ReadJson <AuthenticationResponseTemplate>(responseString); if (responseJson.GetTokenOrAccessToken() == null) { var err = new RegistryAuthenticationFailedException( registryEndpointRequestProperties.GetRegistry(), registryEndpointRequestProperties.GetImageName(), "Did not get token in authentication response from " + GetAuthenticationUrl(credential, scope) + "; parameters: " + GetAuthRequestParameters(credential, scope)); eventHandlers?.Dispatch(LogEvent.Error(err.Message)); throw err; } return(Authorization.FromBearerToken(responseJson.GetTokenOrAccessToken())); } } catch (Exception ex) when(ex is IOException || ex is JsonException) { var eee = new RegistryAuthenticationFailedException( registryEndpointRequestProperties.GetRegistry(), registryEndpointRequestProperties.GetImageName(), ex); eventHandlers?.Dispatch(LogEvent.Error(eee.Message)); throw eee; } }
/** * Creates a new {@link TimerEventDispatcher}. * * @param eventHandlers the {@link EventHandlers} used to dispatch the {@link TimerEvent}s * @param description the default description for the {@link TimerEvent}s */ public TimerEventDispatcher(IEventHandlers eventHandlers, string description) : this(eventHandlers, description, DEFAULT_CLOCK, null) { }
void IEventReceiver.Init(IEventHandlers eventHandlers) { eventHandlers.SubscribeOnUpdate(Update); eventHandlers.SubscribeOnApplicationQuit(OnApplicationQuit); }
/** * Creates a new {@link ProgressEventDispatcher} with a root {@link Allocation}. * * @param eventHandlers the {@link EventHandlers} * @param description user-facing description of what the allocation represents * @param allocationUnits number of allocation units * @return a new {@link ProgressEventDispatcher} */ public static ProgressEventDispatcher NewRoot( IEventHandlers eventHandlers, string description, long allocationUnits) { return(NewProgressEventDispatcher( eventHandlers, Allocation.NewRoot(description, allocationUnits))); }
public Connection(Uri url, bool insecure, IEventHandlers eventHandlers = null) { _eventHandlers = eventHandlers; var proxy = FibSystemProperties.GetHttpProxy(); WebProxy proxy1 = null; if (!string.IsNullOrEmpty(proxy)) { proxyLog = $"use proxy:{proxy}"; if (proxy.Contains("@_@")) { //127.0.0.1:8080@_@username&pass var arr = proxy.Split(new string[] { "@_@" }, StringSplitOptions.None); proxy1 = new WebProxy { Address = new Uri($"http://{arr}"), BypassProxyOnLocal = false, UseDefaultCredentials = false, // *** These creds are given to the proxy server, not the web server *** Credentials = new NetworkCredential( userName: arr[1].Split('&')[0], password: arr[1].Split('&')[1]) }; } else { proxy1 = new WebProxy { Address = new Uri($"http://{proxy}"), BypassProxyOnLocal = false, UseDefaultCredentials = false, }; } } if (insecure) { if (proxy1 != null) { client = insecureClients.GetOrAdd(url, _ => { var httpClientHandler = new HttpClientHandler { Proxy = proxy1, ServerCertificateCustomValidationCallback = (_____, __, ___, ____) => true }; var c = new HttpClient(httpClientHandler) { BaseAddress = url, Timeout = TimeSpan.FromMilliseconds(FibSystemProperties.GetHttpTimeout()), }; return(c); }); } else { client = insecureClients.GetOrAdd(url, _ => new HttpClient(insecureHandler) { BaseAddress = url, Timeout = TimeSpan.FromMilliseconds(FibSystemProperties.GetHttpTimeout()), }); } } else { if (proxy1 != null) { client = clients.GetOrAdd(url, _ => { var httpClientHandler = new HttpClientHandler { Proxy = proxy1, }; var c = new HttpClient(httpClientHandler) { BaseAddress = url, Timeout = TimeSpan.FromMilliseconds(FibSystemProperties.GetHttpTimeout()), }; return(c); }); } else { client = clients.GetOrAdd(url, _ => new HttpClient { BaseAddress = url, Timeout = TimeSpan.FromMilliseconds(FibSystemProperties.GetHttpTimeout()), }); } } }
public void Init(IEventHandlers eventHandlers) { eventHandlers.SubscribeOnAwake(Awake); eventHandlers.SubscribeOnDestroy(OnDestroy); }
/** * Make sure to wrap with a try-with-resource to ensure that the connection is closed after usage. * * @param url the url to send the request to */ public Connection(Uri url, IEventHandlers eventHandlers = null) : this(url, false, eventHandlers) { }