示例#1
0
        public IActionResult DownloadDockerfiles(UserConfiguration config)
        {
            var hs = new HomeControllerService();

            this.UploadFile(config);

            hs.CreateGamsDockerfile(config);
            //hs.CreateModelDockerfile(config);

            var dlFile = hs.CreateDockerZipFile();

            return(hs.DownloadFile(dlFile, "dockerfile.zip"));
        }
示例#2
0
        public IActionResult BuildImage(UserConfiguration config, string imageName = "")
        {
            // https://docs.docker.com/engine/reference/builder/

            var hs = new HomeControllerService();

            hs.CreateGamsDockerfile(config);

            if (imageName == string.Empty)
            {
                imageName = config.SelectedProgram + config.SelectedGithubRepository +
                            DateTime.Now.ToShortDateString().Replace(".", string.Empty);
            }

            imageName = imageName.ToLower() + Guid.NewGuid().ToString().Substring(0, 4);

            var outputPath = Path.GetFullPath(HomeControllerService.OutputFilePath); //"./Output/");

            var files = Directory.GetFiles(outputPath);

            var dockerfile = Path.GetFileName(files.FirstOrDefault(file => file.ToLower().Contains("docker")));

            if (!string.IsNullOrEmpty(dockerfile))
            {
                var process   = new Process();
                var startInfo = new ProcessStartInfo
                {
                    //WindowStyle = ProcessWindowStyle.Hidden,
                    FileName  = "/bin/bash",
                    Arguments =
                        $@"docker build -t webinterface/{imageName} - < /app/Output/{
                                HomeControllerService.OutputFolderName
                            }/{dockerfile}",
                    //Arguments = $@"docker build -t test/{imageName} Dockerfile-model",
                    RedirectStandardOutput = true
                };

                process.StartInfo = startInfo;
                process.Start(); // no such file or directory

                Logger.Log(process.StandardOutput.ReadToEnd());

                process.WaitForExit();
            }

            return(this.View("Index", config));

            // Todo: Get user info: dockerfile not available
        }
示例#3
0
        public async Task <bool> RunScriptAsync(UserConfiguration config)
        {
            var hs = new HomeControllerService();

            // https://stackoverflow.com/questions/43387693/build-docker-in-asp-net-core-no-such-file-or-directory-error
            // https://stackoverflow.com/questions/2849341/there-is-no-viewdata-item-of-type-ienumerableselectlistitem-that-has-the-key

            // Upload License if provided
            this.UploadFile(config);

            // Upload model input data if provided
            this.UploadModelInputData(config);

            // Generate Dockerfile
            var programDockerfilePath = hs.CreateGamsDockerfile(config);
            var fullpat = Path.GetFullPath(programDockerfilePath);

            // ------- CREATE IMAGE FROM DOCKERFILE
            try
            {
                //// https://github.com/Microsoft/Docker.DotNet/issues/197
                var path = fullpat;

                const string tarFile = "Dockerfile.tar";

                if (!System.IO.File.Exists(tarFile))
                {
                    System.IO.File.Delete(tarFile);
                }

                hs.CreateTarGz(tarFile, path);

                Logger.Log("\n\n\n\n======== DOCKERFILE START =======================================");
                using (var sr = new StreamReader(path))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        Logger.Log(line);
                    }
                }
                Logger.Log("========= DOCKERFILE END ======================================\n\n\n\n\n");

                //hs.DownloadZipDataToFolder("http://geonode_geonode_1/documents/3/download/", @"./OutputZip/data.zip");

                var networks = await Client.Networks.ListNetworksAsync();

                var network = networks.First(x => x.Name.Contains("webinterface_default")); //networks.First(x => x.Name.Contains("geonode"));

                var imageName = "gams/iiasa";
                var tag       = "latest";

                // https://docs.docker.com/edge/engine/reference/commandline/build/
                // https://docs.docker.com/engine/api/v1.25/#operation/ImageList
                var imageBuildParameters = new ImageBuildParameters()
                {
                    Remove      = true,
                    ForceRemove = true,
                    Tags        = new List <string> {
                        imageName + ":" + tag
                    },
                    NetworkMode = network.Name,
                    NoCache     = true
                };

                var errorDetected = false;
                using (var fs = new FileStream(tarFile, FileMode.Open))
                {
                    // https://stackoverflow.com/questions/33997089/how-can-i-create-a-stream-for-dockerdotnet-buildimagefromdockerfile-method
                    var statusUpdate = await Client.Images.BuildImageFromDockerfileAsync(
                        fs,
                        imageBuildParameters,
                        CancellationToken.None);

                    using (var streamReader = new StreamReader(statusUpdate))
                    {
                        string line;
                        while ((line = streamReader.ReadLine()) != null)
                        {
                            Logger.Log(line);
                            if (line.ToLower().Contains("error"))
                            {
                                errorDetected = true;
                            }
                        }
                    }

                    fs.Dispose();
                }

                if (errorDetected)
                {
                    Logger.Log("!!! ERRORS DETECTED!!!\nContainer Creation Aborted!");
                    return(false);
                }

                var containerName = imageName.Replace("/", "_") + "_container";

                var containers =
                    await Client.Containers.ListContainersAsync(new ContainersListParameters
                {
                    All = true,
                },
                                                                CancellationToken.None);

                var containerList = containers.ToList();

                foreach (var container in containerList)
                {
                    foreach (var name in container.Names)
                    {
                        if (name.Contains(containerName))
                        {
                            await Client.Containers.RemoveContainerAsync(container.ID,
                                                                         new ContainerRemoveParameters { Force = true });
                        }
                    }
                }

                var containerResponse = await Client.Containers.CreateContainerAsync(new CreateContainerParameters
                {
                    AttachStderr = true,
                    AttachStdin  = true,
                    AttachStdout = true,
                    Image        = imageName,
                    Name         = containerName,
                },
                                                                                     CancellationToken.None);

                var res = await Client.Containers.StartContainerAsync(containerResponse.ID, new ContainerStartParameters(),
                                                                      CancellationToken.None);

                if (res)
                {
                    Logger.Log("=== Container Created and Started ===");

                    var outputResponse = await Client.Containers.GetArchiveFromContainerAsync(containerResponse.ID,
                                                                                              new GetArchiveFromContainerParameters
                    {
                        Path = "/output"
                    },
                                                                                              false,
                                                                                              CancellationToken.None);

                    using (Stream s = System.IO.File.Create("./Result/result.tar"))
                    {
                        outputResponse.Stream.CopyTo(s);
                    }

                    Logger.Log("output finished!");

                    return(true);
                }

                Logger.Log("ERROR\n=== Container Could Not Be Created! ===");
                return(false);
            }
            catch (Exception ex)
            {
                Logger.Log(
                    "=================== ERROR ===========================================================================");
                Logger.Log(ex.Message); //ex.FullMessage());

                if (ex.InnerException != null)
                {
                    Logger.Log(ex.InnerException.Message);
                }

                Logger.Log(
                    "=====================================================================================================");

                return(false);
            }
        }