Пример #1
0
        private ProgressEventDispatcher(IEventHandlers eventHandlers, Allocation allocation)
        {
            this.eventHandlers = eventHandlers;
            this.allocation    = allocation;

            remainingAllocationUnits = allocation.GetAllocationUnits();
        }
Пример #2
0
 public Factory(
     IEventHandlers eventHandlers,
     RegistryEndpointRequestProperties registryEndpointRequestProperties)
 {
     this.eventHandlers = eventHandlers;
     this.registryEndpointRequestProperties = registryEndpointRequestProperties;
 }
Пример #3
0
        /**
         * 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;
                }
            }
        }
Пример #4
0
 /** 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;
 }
Пример #5
0
        /// <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
        }
Пример #9
0
 /// <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);
 }
Пример #10
0
        /**
         * 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);
        }
Пример #11
0
        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);
        }
Пример #12
0
 /// <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;
 }
Пример #13
0
 public ManifestPusher(
     RegistryEndpointRequestProperties registryEndpointRequestProperties,
     IBuildableManifestTemplate manifestTemplate,
     string imageTag,
     IEventHandlers eventHandlers)
 {
     this.registryEndpointRequestProperties = registryEndpointRequestProperties;
     this.manifestTemplate = manifestTemplate;
     this.imageTag         = imageTag;
     this.eventHandlers    = eventHandlers;
 }
Пример #14
0
 /**
  * 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));
 }
Пример #15
0
 /**
  * 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;
 }
Пример #16
0
        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);
        }
Пример #17
0
        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")
            };
        }
Пример #19
0
    /// <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;
    }
Пример #20
0
    /// <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();
        }
    }
Пример #21
0
        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()));
        }
Пример #22
0
 /// <summary>
 /// Adds the IEventReceiver functions to the delegates in order to be called from MetaManager
 /// </summary>
 public void Init(IEventHandlers eventHandlers)
 {
     eventHandlers.SubscribeOnUpdate(Update);
 }
Пример #23
0
 /**
  * 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));
 }
Пример #24
0
        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;
                        }
                    }
                }
        }
Пример #25
0
        /**
         * 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;
            }
        }
Пример #26
0
 /**
  * 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);
 }
Пример #28
0
 /**
  * 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)));
 }
Пример #29
0
        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()),
                    });
                }
            }
        }
Пример #30
0
 public void Init(IEventHandlers eventHandlers)
 {
     eventHandlers.SubscribeOnAwake(Awake);
     eventHandlers.SubscribeOnDestroy(OnDestroy);
 }
Пример #31
0
 /**
  * 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)
 {
 }