public static async Task Main(string[] args)
        {
            var configuration = GetConfiguration(args);

            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(configuration)
                         .CreateLogger();

            try
            {
                DockerHelpers.ApplyDockerConfiguration(configuration);

                var host = CreateHostBuilder(args).Build();

                await ApplyDbMigrationsWithDataSeedAsync(args, configuration, host);

                host.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Example #2
0
        private static async Task <int> RunDocker(IDockerClient client, RunDockerCommand command, string callingContainerId, IOutputObserver outputObserver, CancellationToken cancellationToken)
        {
            var allowedMounts = await GetMounts(client, callingContainerId, cancellationToken);

            if (!(ValidateDockerCommand(command) && ValidateMounts(command.BindMounts, allowedMounts) is {} mounts))
            {
                await Console.Error.WriteLineAsync("Could not validate docker command.");

                return(1);
            }



            var response = await client.Containers.CreateContainerAsync(
                new Docker.DotNet.Models.CreateContainerParameters {
                Image        = command.ImageName,
                Env          = command.Environment.Select(env => $"{env.Key}={env.Value}").ToList(),
                AttachStderr = true,
                AttachStdout = true,
                ArgsEscaped  = false,
                Cmd          = command.Command.ToList(),
                WorkingDir   = command.CurrentDirectory,

                HostConfig = new Docker.DotNet.Models.HostConfig {
                    AutoRemove  = true,
                    NetworkMode = "none",
                    Isolation   = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "process" : null,

                    Mounts = mounts,
                },
            },
                cancellationToken
                );

            using var stream = await client.Containers.AttachContainerAsync(
                      response.ID,
                      tty : false,
                      new Docker.DotNet.Models.ContainerAttachParameters {
                Stream = true,
                Stderr = true,
                Stdout = true,
            },
                      cancellationToken
                      );

            await client.Containers.StartContainerAsync(
                response.ID,
                new Docker.DotNet.Models.ContainerStartParameters {
            },
                cancellationToken
                );

            await DockerHelpers.PipeContainerOutput(outputObserver, stream, cancellationToken);

            var waitResponse = await client.Containers.WaitContainerAsync(response.ID, cancellationToken);

            return((int)waitResponse.StatusCode);
        }
        public override async Task RunAsync()
        {
            if (!string.IsNullOrEmpty(FolderName))
            {
                var folderPath = Path.Combine(Environment.CurrentDirectory, FolderName);
                FileSystemHelpers.EnsureDirectory(folderPath);
                Environment.CurrentDirectory = folderPath;
            }

            if (!Platforms.Contains(Platform))
            {
                ColoredConsole.Error.WriteLine(ErrorColor($"platform {Platform} is not supported. Valid options are: {String.Join(",", Platforms)}"));
                return;
            }

            if (!CommandChecker.CommandExists("kubectl"))
            {
                ColoredConsole.Error.WriteLine(ErrorColor($"kubectl is required for deploying to kubernetes. Please make sure to install kubectl and try again."));
                return;
            }

            var dockerFilePath = Path.Combine(Environment.CurrentDirectory, "Dockerfile");

            if (!FileSystemHelpers.FileExists(dockerFilePath))
            {
                ColoredConsole.Error.WriteLine(ErrorColor($"Dockerfile not found in directory {Environment.CurrentDirectory}"));
                return;
            }

            var image = $"{Registry}/{Name.SanitizeImageName()}";

            ColoredConsole.WriteLine("Building Docker image...");
            await DockerHelpers.DockerBuild(image, Environment.CurrentDirectory);

            ColoredConsole.WriteLine("Pushing function image to registry...");
            await DockerHelpers.DockerPush(image);

            var platform = PlatformFactory.CreatePlatform(Platform, ConfigPath);

            if (platform == null)
            {
                ColoredConsole.Error.WriteLine(ErrorColor($"Platform {Platform} is not supported"));
                return;
            }

            await platform.DeployContainerizedFunction(Name, image, MinInstances, MaxInstances);
        }
Example #4
0
        public static void Main(string[] args)
        {
            var configuration = GetConfiguration(args);

            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(configuration)
                         .CreateLogger();
            Log.Information("Start Host");
            try
            {
                DockerHelpers.ApplyDockerConfiguration(configuration);
                var isService = !(Debugger.IsAttached || args.Contains("--console"));
                if (isService)
                {
                    Log.Information("Start WS1");
                    var host = CreateHostBuilder(args).UseWindowsService().Build();
                    //await ApplyDbMigrationsWithDataSeedAsync(args, configuration, host);
                    Log.Information("Start WS2");
                    host.Run();
                    Log.Information("Start WS3");
                }
                else
                {
                    Log.Information("Start Web");
                    var host = CreateHostBuilder(args).Build();

                    //await ApplyDbMigrationsWithDataSeedAsync(args, configuration, host);

                    host.Run();
                }
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Example #5
0
        public static void Main(string[] args)
        {
            var configuration = GetConfiguration(args);

            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(configuration)
                         .CreateLogger();
            try
            {
                DockerHelpers.ApplyDockerConfiguration(configuration);

                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Example #6
0
        public static async Task Main(string[] args)
        {
            var configuration = GetConfiguration(args);

            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(configuration)
                         .CreateLogger();

            try
            {
                DockerHelpers.ApplyDockerConfiguration(configuration);

                var host = CreateHostBuilder(args).Build();

                var migrationComplete = await ApplyDbMigrationsWithDataSeedAsync(args, configuration, host);

                if (args.Any(x => x == MigrateOnlyArgs))
                {
                    await host.StopAsync();

                    if (!migrationComplete)
                    {
                        Environment.ExitCode = -1;
                    }

                    return;
                }
                await host.RunAsync();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
        public override async Task RunAsync()
        {
            (var resolvedImageName, var shouldBuild) = ResolveImageName();
            TriggersPayload triggers = null;

            if (DryRun)
            {
                if (shouldBuild)
                {
                    // don't build on a --dry-run.
                    // read files from the local dir
                    triggers = await GetTriggersLocalFiles();
                }
                else
                {
                    triggers = await DockerHelpers.GetTriggersFromDockerImage(resolvedImageName);
                }
            }
            else
            {
                if (shouldBuild)
                {
                    await DockerHelpers.DockerBuild(resolvedImageName, Environment.CurrentDirectory);
                }
                triggers = await DockerHelpers.GetTriggersFromDockerImage(resolvedImageName);
            }

            (var resources, var funcKeys) = await KubernetesHelper.GetFunctionsDeploymentResources(
                Name,
                resolvedImageName,
                Namespace,
                triggers,
                _secretsManager.GetSecrets(),
                PullSecret,
                SecretsCollectionName,
                ConfigMapName,
                UseConfigMap,
                PollingInterval,
                CooldownPeriod,
                ServiceType,
                MinReplicaCount,
                MaxReplicaCount,
                KeysSecretCollectionName,
                MountFuncKeysAsContainerVolume);

            if (DryRun)
            {
                ColoredConsole.WriteLine(KubernetesHelper.SerializeResources(resources, OutputSerializationOptions.Yaml));
            }
            else
            {
                if (!await KubernetesHelper.NamespaceExists(Namespace))
                {
                    await KubernetesHelper.CreateNamespace(Namespace);
                }

                if (shouldBuild)
                {
                    await DockerHelpers.DockerPush(resolvedImageName);
                }

                foreach (var resource in resources)
                {
                    await KubectlHelper.KubectlApply(resource, showOutput : true, ignoreError : IgnoreErrors, @namespace : Namespace);
                }

                //Print the function keys message to the console
                await KubernetesHelper.PrintFunctionsInfo($"{Name}-http", Namespace, funcKeys, triggers);
            }
        }
Example #8
0
        private async Task <string> HandleRunCommandCommon(BuildState state, string proxyNetworkId, ReadOnlyDictionary <string, string> buildArgs, IReadOnlyList <string> command, IOutputObserver outputObserver, CancellationToken cancellationToken)
        {
            var nonEnvArgs = buildArgs.Where(arg => !state.Environment.ContainsKey(arg.Key)).ToList();

            var response = await docker.Containers.CreateContainerAsync(
                new Docker.DotNet.Models.CreateContainerParameters {
                Image        = state.Id,
                Env          = nonEnvArgs.Select(env => $"{env.Key}={env.Value}").Concat(proxyEnv).ToList(),
                AttachStderr = true,
                AttachStdout = true,
                Cmd          = command.ToList(),

                HostConfig = new Docker.DotNet.Models.HostConfig {
                    NetworkMode = proxyNetworkId,
                    Isolation   = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "process" : null,
                },
            },
                cancellationToken
                );

            try {
                using var stream = await docker.Containers.AttachContainerAsync(
                          response.ID,
                          tty : false,
                          new Docker.DotNet.Models.ContainerAttachParameters {
                    Stream = true,
                    Stderr = true,
                    Stdout = true,
                },
                          cancellationToken
                          );

                await docker.Containers.StartContainerAsync(
                    response.ID,
                    new Docker.DotNet.Models.ContainerStartParameters {
                },
                    cancellationToken
                    );

                await DockerHelpers.PipeContainerOutput(outputObserver, stream, cancellationToken);

                var waitResponse = await docker.Containers.WaitContainerAsync(response.ID, cancellationToken);

                int exitCode = (int)waitResponse.StatusCode;
                if (exitCode != 0)
                {
                    throw new RunCommandFailedException($"Command failed with exit code {exitCode}.", exitCode);
                }

                var image = await docker.Images.CommitContainerChangesAsync(new CommitContainerChangesParameters {
                    ContainerID = response.ID,
                    Config      = new Config {
                        Env = nonEnvArgs.Select(env => env.Key).ToList(),
                    },
                }, cancellationToken);

                return(image.ID);
            }
            finally {
                await docker.Containers.RemoveContainerAsync(response.ID, new Docker.DotNet.Models.ContainerRemoveParameters(), cancellationToken);
            }
        }