Ошибка активации пакета Service Fabric

Получение следующей ошибки

Error event: SourceId='System.Hosting', 

Property='CodePackageActivation:Code:EntryPoint'.
There was an error during CodePackage activation.Service host failed to activate. Error:0x800700c1`

Если я попытаюсь сделать это в кластере сервисной фабрики Linux, ошибка немного изменится. Итак, я думаю, что кластер Windows не работает в сценарии entyPoint.sh, поскольку в Windows нет bash. Кластер Linux, очевидно, преодолевает это и дает сбой где-то внутри кода инициализации, но до сих пор не может найти, где. я добавил

 <ConsoleRedirection FileRetentionCount="5" FileMaxSizeInKb="2048"/>

И загрузил все журналы из окна Linux, но ничего не увидел там из консоли.

Error event: SourceId='System.Hosting', 

Property='CodePackageActivation:Code:EntryPoint'.
There was an error during CodePackage activation.The service host terminated with exit code:134

Стартовый класс выглядит так

namespace MyApp
{
    using System.Collections.Generic;
    using System.Fabric;
    using System.IO;
    using System.Net.Http;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.ServiceFabric.Services.Communication.AspNetCore;
    using Microsoft.ServiceFabric.Services.Communication.Runtime;
    using Microsoft.ServiceFabric.Services.Runtime;
/// <summary>
/// The FabricRuntime creates an instance of this class for each service type instance. 
/// </summary>
internal sealed class MyApp : StatelessService
{
    public MyApp(StatelessServiceContext context)
        : base(context)
    {
    }

    /// <summary>
    /// Optional override to create listeners (like tcp, http) for this service instance.
    /// </summary>
    /// <returns>The collection of listeners.</returns>
    protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
    {
        return new ServiceInstanceListener[]
        {
            new ServiceInstanceListener(
                serviceContext =>
                    new KestrelCommunicationListener(
                        serviceContext,
                        "ServiceEndpoint",
                        (url, listener) =>
                        {
                            ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting WebListener on {url}");

                            return new WebHostBuilder()
                                .UseKestrel()
                                .ConfigureServices(
                                    services => services
                                        .AddSingleton<ConfigSettings>(new ConfigSettings(serviceContext))
                                        .AddSingleton<HttpClient>(new HttpClient())
                                        .AddSingleton<FabricClient>(new FabricClient())
                                        .AddSingleton<StatelessServiceContext>(serviceContext))
                                .UseContentRoot(Directory.GetCurrentDirectory())
                                .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
                                .UseStartup<Startup>()
                                .UseUrls(url)
                                .Build();
                        }))
        };
    }
}

Программа.cs

namespace MyApp
{
    using System;
    using System.Diagnostics;
    using System.Threading;
    using CommandLine;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.ServiceFabric.Services.Runtime;

internal static class Program
{
    /// <summary>
    /// This is the entry point of the service host process.
    /// </summary>
    private static void Main(string[] args)
    {
        var parser = new Parser(with =>
        {
            with.HelpWriter = Console.Out;
        });

        var options = new Options();
        var result = parser.ParseArguments(args, options);


        if (options.Host.ToLower() == MyAppConstants.ServiceFabricHost)
        {
            try
            {
                // The ServiceManifest.XML file defines one or more service type names.
                // Registering a service maps a service type name to a .NET type.
                // When Service Fabric creates an instance of this service type,
                // an instance of the class is created in this host process.

                ServiceRuntime.RegisterServiceAsync(
                    "WebServiceType",
                    context => new MyApp(context)).GetAwaiter().GetResult();

                ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(SnapNurse).Name);

                // Prevents this host process from terminating so services keeps running. 
                Thread.Sleep(Timeout.Infinite);
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
                throw;
            }
        }
        else if (options.Host.ToLower() == MyAppConstants.SelfHost)
        {
            using (var host = WebHostBuilderHelper.GetWebHost(new WebHostBuilder(), options.Protocol, options.Port))
            {
                host.Run();
            }
        }
    }
}

Я не смог найти подробностей об ошибке и не могу отладить что-либо в среде Service Fabric, потому что они не запускаются. Любая помощь приветствуется!

Я запустил PerfView и нашел события, связанные с активацией пакета, но там нет намеков на то, в чем заключается настоящая проблема. Даже если никто не знает, в чем проблема, было бы здорово просто помочь с методами получения дополнительной информации!

Еще одна вещь, которая кажется странной, заключается в том, что даже если я закомментирую весь код в методе Main(), я все равно получаю точно такую ​​же ошибку. Почти как будто он выходит из строя еще до того, как он попадет туда на DLL-библиотеках фреймворка или что-то в этом роде, но все это .netcore2, и у меня есть среда выполнения, установленная на машине с сервисной тканью.


comment
Что содержит ваш сценарий запуска?   -  person Dismissile    schedule 21.09.2017
comment
Что такое options.Host. попробуйте запустить ветку сервисной фабрики   -  person Mardoxx    schedule 25.09.2017


Ответы (1)


По-видимому, это происходит из-за разных концов строк в Linux и Windows. Системы Windows используют CR+LF, в то время как Unix и Unix-подобные системы используют LF.

Чтобы решить вашу проблему, выполните

sed -i -e 's/\r$//' entrypoint.sh

Вам может понадобиться сделать это, если есть другие .sh файлы, где sed -i -e 's/\r$//' *.sh помогает.

Тогда приступайте к материалам Service Fabric Cluster!

Люди также играют с unix2dos и dos2unix вещами по таким вопросам, для которых достаточно альтернатив, перечисленных здесь .

person Shridhar R Kulkarni    schedule 25.09.2017