Пример #1
0
 /// <summary>
 /// Outputs container objects for each container matching the provided parameters.
 /// </summary>
 protected override async Task ProcessRecordAsync()
 {
     if (Id != null)
     {
         foreach (var id in Id)
         {
             WriteObject(await ContainerOperations.GetContainersById(id, DkrClient));
         }
     }
     else if (Name != null)
     {
         foreach (var name in Name)
         {
             WriteObject(await ContainerOperations.GetContainersByName(name, DkrClient));
         }
     }
     else
     {
         foreach (var c in await DkrClient.Containers.ListContainersAsync(
                      new ContainersListParameters()
         {
             All = true
         }))
         {
             WriteObject(c);
         }
     }
 }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            foreach (var id in ParameterResolvers.GetContainerIds(Container, Id))
            {
                if (Force.ToBool())
                {
                    DkrClient.Containers.KillContainerAsync(
                        id,
                        new ContainerKillParameters()).WaitUnwrap();
                }
                else
                {
                    if (!DkrClient.Containers.StopContainerAsync(
                            id,
                            new ContainerStopParameters(),
                            CancelSignal.Token).AwaitResult())
                    {
                        throw new ApplicationFailedException("The container has already stopped.");
                    }
                }

                if (PassThru.ToBool())
                {
                    WriteObject(ContainerOperations.GetContainerById(id, DkrClient));
                }
            }
        }
Пример #3
0
        protected override async Task ProcessRecordAsync()
        {
            foreach (var id in ParameterResolvers.GetContainerIds(Container, ContainerIdOrName))
            {
                ContainerAttachParameters attachParams = null;
                if (this.Attach)
                {
                    attachParams = new ContainerAttachParameters
                    {
                        Stdin  = this.Input,
                        Stdout = true,
                        Stderr = true,
                        Stream = true
                    };
                }

                var cDetail = await DkrClient.Containers.InspectContainerAsync(id);

                await ContainerOperations.StartContainerAsync(
                    this.DkrClient,
                    id,
                    attachParams,
                    cDetail.Config.Tty,
                    null,
                    this.CmdletCancellationToken);

                if (PassThru)
                {
                    WriteObject((await ContainerOperations.GetContainersByIdOrName(id, DkrClient)).Single());
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Creates a new container and lists it to output.
        /// </summary>
        protected override async Task ProcessRecordAsync()
        {
            foreach (var id in ParameterResolvers.GetImageIds(Image, ImageIdOrName))
            {
                var createResult = await ContainerOperations.CreateContainer(
                    id,
                    this.MemberwiseClone() as CreateContainerCmdlet,
                    DkrClient);

                if (createResult.Warnings != null)
                {
                    foreach (var w in createResult.Warnings)
                    {
                        if (!String.IsNullOrEmpty(w))
                        {
                            WriteWarning(w);
                        }
                    }
                }

                if (!String.IsNullOrEmpty(createResult.ID))
                {
                    WriteObject((await ContainerOperations.GetContainersById(createResult.ID, DkrClient)).Single());
                }
            }
        }
        /// <summary>
        /// Creates a new container and lists it to output.
        /// </summary>
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            foreach (var id in ParameterResolvers.GetImageIds(Image, Id))
            {
                var createResult = ContainerOperations.CreateContainer(
                    id,
                    this.MemberwiseClone() as CreateContainerCmdlet,
                    DkrClient);

                if (createResult.Warnings != null)
                {
                    foreach (var w in createResult.Warnings)
                    {
                        if (!String.IsNullOrEmpty(w))
                        {
                            WriteWarning(w);
                        }
                    }
                }

                if (!String.IsNullOrEmpty(createResult.ID))
                {
                    WriteObject(ContainerOperations.GetContainerById(createResult.ID, DkrClient));
                }
            }
        }
Пример #6
0
        protected override async Task ProcessRecordAsync()
        {
            foreach (var id in ParameterResolvers.GetContainerIds(Container, ContainerIdOrName))
            {
                if (Force)
                {
                    await DkrClient.Containers.KillContainerAsync(
                        id,
                        new ContainerKillParameters());
                }
                else
                {
                    if (!await DkrClient.Containers.StopContainerAsync(
                            id,
                            new ContainerStopParameters(),
                            CmdletCancellationToken))
                    {
                        throw new ApplicationFailedException("The container has already stopped.");
                    }
                }

                if (PassThru)
                {
                    WriteObject((await ContainerOperations.GetContainersByIdOrName(id, DkrClient)).Single());
                }
            }
        }
Пример #7
0
        protected override async Task ProcessRecordAsync()
        {
            foreach (var item in FilePath)
            {
                var filePath = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, item);

                string imageId = null;
                bool   failed  = false;

                using (var file = File.OpenRead(filePath))
                {
                    var loadTask = DkrClient.Miscellaneous.LoadImageFromTarball(file, new ImageLoadParameters {
                        Quiet = false
                    }, CmdletCancellationToken);

                    var messageWriter = new JsonMessageWriter(this);

                    using (var pushStream = await loadTask)
                    {
                        // ReadLineAsync is not cancellable without closing the whole stream, so register a callback to do just that.
                        using (CmdletCancellationToken.Register(() => pushStream.Dispose()))
                            using (var pullReader = new StreamReader(pushStream, new UTF8Encoding(false)))
                            {
                                string line;
                                while ((line = await pullReader.ReadLineAsync()) != null)
                                {
                                    var message = JsonConvert.DeserializeObject <JsonMessage>(line);
                                    if (message.Stream != null && message.Stream.StartsWith(LoadedImage))
                                    {
                                        // This is probably the image ID.
                                        imageId = message.Stream.Substring(LoadedImage.Length).Trim();
                                    }

                                    if (message.Error != null)
                                    {
                                        failed = true;
                                    }

                                    messageWriter.WriteJsonMessage(JsonConvert.DeserializeObject <JsonMessage>(line));
                                }
                            }
                    }

                    messageWriter.ClearProgress();
                    if (imageId != null)
                    {
                        WriteObject((await ContainerOperations.GetImagesByRepoTag(imageId, DkrClient)).Single());
                    }
                    else if (!failed)
                    {
                        throw new Exception("Could not find image, but no error was returned");
                    }
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Creates a new container and lists it to output.
        /// </summary>
        protected override async Task ProcessRecordAsync()
        {
            foreach (var id in ParameterResolvers.GetImageIds(Image, ImageIdOrName))
            {
                var createResult = await ContainerOperations.CreateContainer(
                    id,
                    this.MemberwiseClone() as CreateContainerCmdlet,
                    DkrClient);

                if (createResult.Warnings != null)
                {
                    foreach (var w in createResult.Warnings)
                    {
                        if (!String.IsNullOrEmpty(w))
                        {
                            WriteWarning(w);
                        }
                    }
                }

                if (!String.IsNullOrEmpty(createResult.ID))
                {
                    ContainerAttachParameters attachParams = null;
                    if (!Detach)
                    {
                        attachParams = new ContainerAttachParameters
                        {
                            Stdin  = Input,
                            Stdout = true,
                            Stderr = true,
                            Stream = true
                        };
                    }

                    await ContainerOperations.StartContainerAsync(
                        this.DkrClient,
                        createResult.ID,
                        attachParams,
                        this.Terminal,
                        null,
                        this.CmdletCancellationToken);

                    if (RemoveAutomatically && !Detach)
                    {
                        await DkrClient.Containers.RemoveContainerAsync(createResult.ID,
                                                                        new ContainerRemoveParameters());
                    }
                    else if (PassThru)
                    {
                        WriteObject((await ContainerOperations.GetContainersById(createResult.ID, DkrClient)).Single());
                    }
                }
            }
        }
        protected override async Task ProcessRecordAsync()
        {
            string repoTag  = null;
            bool   failed   = false;
            var    pullTask = DkrClient.Images.PullImageAsync(new ImagesPullParameters()
            {
                All = All, Parent = Repository, Tag = Tag ?? "latest",
            }, Authorization);
            var messageWriter = new JsonMessageWriter(this);

            using (var pullStream = await pullTask)
            {
                // ReadLineAsync is not cancellable without closing the whole stream, so register a callback to do just that.
                using (CmdletCancellationToken.Register(() => pullStream.Dispose()))
                    using (var pullReader = new StreamReader(pullStream, new UTF8Encoding(false)))
                    {
                        string line;
                        while ((line = await pullReader.ReadLineAsync()) != null)
                        {
                            var message = JsonConvert.DeserializeObject <JsonMessage>(line);
                            if (message.Status != null)
                            {
                                if (message.Status.StartsWith(StatusUpToDate))
                                {
                                    // This is probably the image repository:tag.
                                    repoTag = message.Status.Substring(StatusUpToDate.Length).Trim();
                                }
                                else if (message.Status.StartsWith(StatusDownloadedNewer))
                                {
                                    // This is probably the image repository:tag.
                                    repoTag = message.Status.Substring(StatusDownloadedNewer.Length).Trim();
                                }
                            }

                            if (message.Error != null)
                            {
                                failed = true;
                            }

                            messageWriter.WriteJsonMessage(message);
                        }
                    }
            }

            messageWriter.ClearProgress();
            if (repoTag != null)
            {
                WriteObject((await ContainerOperations.GetImagesByRepoTag(repoTag, DkrClient)).Single());
            }
            else if (!failed)
            {
                throw new Exception("Could not find image, but no error was returned");
            }
        }
Пример #10
0
    public IEnumerable <CompletionResult> CompleteArgument(string commandName,
                                                           string parameterName,
                                                           string wordToComplete,
                                                           CommandAst commandAst,
                                                           IDictionary fakeBoundParameters)
    {
        var client = DockerFactory.CreateClient(fakeBoundParameters);
        IList <ContainerListResponse> result;

        if (wordToComplete == "")
        {
            result = client.Containers.ListContainersAsync(new ContainersListParameters
            {
                All = true
            }).Result;
        }
        else
        {
            result = ContainerOperations.GetContainersById(wordToComplete, client).Result;
            result = result.Concat(ContainerOperations.GetContainersByName(wordToComplete, client).Result).ToList();
        }

        return(result.SelectMany(container =>
        {
            // If the user has already typed part of the name, then include IDs that start
            // with that portion. Otherwise, just let the user tab through the names.

            // Special handling for Get-Container, where Id an Name are separate parameters.
            if (commandName == "Get-Container" && parameterName == "Id")
            {
                return new List <string> {
                    container.ID
                };
            }
            else if (wordToComplete == "" || parameterName == "Name")
            {
                return container.Names;
            }
            else
            {
                return container.Names.Concat(new List <string> {
                    container.ID
                });
            }
        })
               .Select(name => name.StartsWith("/") && !wordToComplete.StartsWith("/") ? name.Substring(1) : name)
               .Distinct()
               .Where(name => name.StartsWith(wordToComplete, StringComparison.CurrentCultureIgnoreCase))
               .OrderBy(name => name)
               .Select(name => new CompletionResult(name, name, CompletionResultType.Text, name)));
    }
Пример #11
0
        /// <summary>
        /// Creates a new container and lists it to output.
        /// </summary>
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            foreach (var id in ParameterResolvers.GetImageIds(Image, Id))
            {
                var createResult = ContainerOperations.CreateContainer(
                    id,
                    this.MemberwiseClone() as CreateContainerCmdlet,
                    DkrClient);

                if (createResult.Warnings != null)
                {
                    foreach (var w in createResult.Warnings)
                    {
                        if (!String.IsNullOrEmpty(w))
                        {
                            WriteWarning(w);
                        }
                    }
                }

                if (!String.IsNullOrEmpty(createResult.ID))
                {
                    if (!DkrClient.Containers.StartContainerAsync(
                            createResult.ID, HostConfiguration).AwaitResult())
                    {
                        throw new ApplicationFailedException("The container has already started.");
                    }

                    var waitResponse = DkrClient.Containers.WaitContainerAsync(
                        createResult.ID,
                        CancelSignal.Token).AwaitResult();

                    WriteVerbose("Status Code: " + waitResponse.StatusCode.ToString());
                    ContainerOperations.ThrowOnProcessExitCode(waitResponse.StatusCode);

                    if (RemoveAutomatically.ToBool())
                    {
                        DkrClient.Containers.RemoveContainerAsync(createResult.ID,
                                                                  new ContainerRemoveParameters()).WaitUnwrap();
                    }
                    else if (PassThru.ToBool())
                    {
                        WriteObject(ContainerOperations.GetContainerById(createResult.ID, DkrClient));
                    }
                }
            }
        }
Пример #12
0
        protected override async Task ProcessRecordAsync()
        {
            foreach (var id in ParameterResolvers.GetContainerIds(Container, Id))
            {
                if (!await DkrClient.Containers.StartContainerAsync(id, new ContainerStartParameters()))
                {
                    throw new ApplicationFailedException("The container has already started.");
                }

                if (PassThru)
                {
                    WriteObject((await ContainerOperations.GetContainersByIdOrName(id, DkrClient)).Single());
                }
            }
        }
Пример #13
0
        protected override async Task ProcessRecordAsync()
        {
            foreach (var id in ParameterResolvers.GetContainerIds(Container, Id))
            {
                var waitResponse = await DkrClient.Containers.WaitContainerAsync(
                    id,
                    CmdletCancellationToken);

                WriteVerbose("Status Code: " + waitResponse.StatusCode.ToString());
                ContainerOperations.ThrowOnProcessExitCode(waitResponse.StatusCode);

                if (PassThru.ToBool())
                {
                    WriteObject(await ContainerOperations.GetContainerById(id, DkrClient));
                }
            }
        }
        protected override async Task ProcessRecordAsync()
        {
            foreach (var id in ParameterResolvers.GetContainerIds(Container, Id))
            {
                var commitResult = await DkrClient.Miscellaneous.CommitContainerChangesAsync(
                    new CommitContainerChangesParameters()
                {
                    ContainerID    = id,
                    RepositoryName = Repository,
                    Tag            = Tag,
                    Comment        = Message,
                    Author         = Author,
                    Config         = Configuration
                });

                WriteObject(await ContainerOperations.GetImageById(commitResult.ID, DkrClient));
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            foreach (var id in ParameterResolvers.GetContainerIds(Container, Id))
            {
                if (!DkrClient.Containers.StartContainerAsync(
                        id, new HostConfig()).AwaitResult())
                {
                    throw new ApplicationFailedException("The container has already started.");
                }

                if (PassThru.ToBool())
                {
                    WriteObject(ContainerOperations.GetContainerById(id, DkrClient));
                }
            }
        }
Пример #16
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            foreach (var id in ParameterResolvers.GetContainerIds(Container, Id))
            {
                var waitResponse = DkrClient.Containers.WaitContainerAsync(
                    id,
                    CancelSignal.Token).AwaitResult();

                WriteVerbose("Status Code: " + waitResponse.StatusCode.ToString());
                ContainerOperations.ThrowOnProcessExitCode(waitResponse.StatusCode);

                if (PassThru.ToBool())
                {
                    WriteObject(ContainerOperations.GetContainerById(id, DkrClient));
                }
            }
        }
        protected override async Task ProcessRecordAsync()
        {
            string repoTag = null;

            if (Id != null)
            {
                repoTag = Id;
            }
            else if (Image.RepoTags.Count != 1)
            {
                throw new Exception("Ambiguous repository and tag: Supplied image must have only one repository:tag.");
            }
            else
            {
                repoTag = Image.RepoTags[0];
            }

            var pushTask      = DkrClient.Images.PushImageAsync(repoTag, new ImagePushParameters(), Authorization);
            var messageWriter = new JsonMessageWriter(this);

            using (var pushStream = await pushTask)
            {
                // ReadLineAsync is not cancellable without closing the whole stream, so register a callback to do just that.
                using (CmdletCancellationToken.Register(() => pushStream.Close()))
                    using (var pullReader = new StreamReader(pushStream, new UTF8Encoding(false)))
                    {
                        string line;
                        while ((line = await pullReader.ReadLineAsync()) != null)
                        {
                            messageWriter.WriteJsonMessage(JsonConvert.DeserializeObject <JsonMessage>(line));
                        }
                    }
            }

            messageWriter.ClearProgress();
            if (PassThru)
            {
                WriteObject((await ContainerOperations.GetImagesByRepoTag(repoTag, DkrClient)).Single());
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            using (var reader = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.None, 65536))
            {
                var tarTask = Task.Run(async() =>
                {
                    using (var writer = new AnonymousPipeClientStream(PipeDirection.Out, reader.ClientSafePipeHandle))
                    {
                        var tar = new TarWriter(writer);
                        await tar.CreateEntriesFromDirectoryAsync(string.IsNullOrEmpty(Path) ? "." : Path, ".");
                        await tar.CloseAsync();
                        writer.Close();
                    }
                });

                var parameters = new ImageBuildParameters
                {
                    NoCache     = SkipCache.ToBool(),
                    ForceRemove = ForceRemoveIntermediateContainers.ToBool(),
                    Remove      = !PreserveIntermediateContainers.ToBool(),
                };

                string repoTag = null;
                if (!string.IsNullOrEmpty(Repository))
                {
                    repoTag = Repository;
                    if (!string.IsNullOrEmpty(Tag))
                    {
                        repoTag += ":";
                        repoTag += Tag;
                    }
                    parameters.Tags.Add(repoTag);
                }
                else if (!string.IsNullOrEmpty(Tag))
                {
                    throw new Exception("tag without a repo???");
                }

                string imageId = null;
                bool   failed  = false;

                var buildTask = DkrClient.Miscellaneous.BuildImageFromDockerfileAsync(reader, parameters, CancelSignal.Token);
                using (var progress = buildTask.AwaitResult())
                    using (var progressReader = new StreamReader(progress, new UTF8Encoding(false)))
                    {
                        string line;
                        while ((line = progressReader.ReadLine()) != null)
                        {
                            var message = JsonConvert.DeserializeObject <JsonMessage>(line);
                            if (message.Stream != null)
                            {
                                if (message.Stream.StartsWith(_successfullyBuilt))
                                {
                                    // This is probably the image ID.
                                    imageId = message.Stream.Substring(_successfullyBuilt.Length).Trim();
                                }

                                var infoRecord = new HostInformationMessage();
                                infoRecord.Message = message.Stream;
                                WriteInformation(infoRecord, new string[] { "PSHOST" });
                            }

                            if (message.Error != null)
                            {
                                var error = new ErrorRecord(new Exception(message.Error.Message), null, ErrorCategory.OperationStopped, null);
                                WriteError(error);
                                failed = true;
                            }
                        }
                    }

                tarTask.WaitUnwrap();
                if (imageId == null && !failed)
                {
                    throw new Exception("Could not find image, but no error was returned");
                }

                WriteObject(ContainerOperations.GetImageById(imageId, DkrClient));
            }
        }
Пример #19
0
        protected override async Task ProcessRecordAsync()
        {
            var directory = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path ?? "");

            // Ensure the path is a directory.
            if (!Directory.Exists(directory))
            {
                throw new DirectoryNotFoundException(directory);
            }

            WriteVerbose(string.Format("Archiving the contents of {0}", directory));

            using (var reader = Archiver.CreateTarStream(new List <string> {
                directory
            }, CmdletCancellationToken))
            {
                var parameters = new ImageBuildParameters
                {
                    NoCache     = SkipCache,
                    ForceRemove = ForceRemoveIntermediateContainers,
                    Remove      = !PreserveIntermediateContainers,
                };

                if (this.Isolation != IsolationType.Default)
                {
                    parameters.Isolation = this.Isolation.ToString();
                }

                string repoTag = null;
                if (!string.IsNullOrEmpty(Repository))
                {
                    repoTag = Repository;
                    if (!string.IsNullOrEmpty(Tag))
                    {
                        repoTag += ":";
                        repoTag += Tag;
                    }

                    parameters.Tags = new List <string>
                    {
                        repoTag
                    };
                }
                else if (!string.IsNullOrEmpty(Tag))
                {
                    throw new Exception("You must specify a repository name in order to specify a tag.");
                }

                string imageId = null;
                bool   failed  = false;

                var progress       = new Progress <ProgressReader.Status>();
                var progressRecord = new ProgressRecord(0, "Dockerfile context", "Uploading");
                progress.ProgressChanged += (o, status) =>
                {
                    if (status.Complete)
                    {
                        progressRecord.CurrentOperation  = null;
                        progressRecord.StatusDescription = "Processing";
                    }
                    else
                    {
                        progressRecord.StatusDescription = string.Format("Uploaded {0} bytes", status.TotalBytesRead);
                    }

                    WriteProgress(progressRecord);
                };

                var progressReader = new ProgressReader(reader, progress, 512 * 1024);
                var buildTask      = DkrClient.Miscellaneous.BuildImageFromDockerfileAsync(progressReader, parameters, CmdletCancellationToken);
                var messageWriter  = new JsonMessageWriter(this);

                using (var buildStream = await buildTask)
                {
                    // Complete the upload progress bar.
                    progressRecord.RecordType = ProgressRecordType.Completed;
                    WriteProgress(progressRecord);

                    // ReadLineAsync is not cancellable without closing the whole stream, so register a callback to do just that.
                    using (CmdletCancellationToken.Register(() => buildStream.Dispose()))
                        using (var buildReader = new StreamReader(buildStream, new UTF8Encoding(false)))
                        {
                            string line;
                            while ((line = await buildReader.ReadLineAsync()) != null)
                            {
                                var message = JsonConvert.DeserializeObject <JsonMessage>(line);
                                if (message.Stream != null && message.Stream.StartsWith(SuccessfullyBuilt))
                                {
                                    // This is probably the image ID.
                                    imageId = message.Stream.Substring(SuccessfullyBuilt.Length).Trim();
                                }

                                if (message.Error != null)
                                {
                                    failed = true;
                                }

                                messageWriter.WriteJsonMessage(message);
                            }
                        }
                }

                messageWriter.ClearProgress();
                if (imageId != null)
                {
                    WriteObject(await ContainerOperations.GetImageById(imageId, DkrClient));
                }
                else if (!failed)
                {
                    throw new Exception("Could not find image, but no error was returned");
                }
            }
        }
        /// <summary>
        /// Creates a new container and lists it to output.
        /// </summary>
        protected override async Task ProcessRecordAsync()
        {
            foreach (var id in ParameterResolvers.GetImageIds(Image, Id))
            {
                var createResult = await ContainerOperations.CreateContainer(
                    id,
                    this.MemberwiseClone() as CreateContainerCmdlet,
                    DkrClient);

                if (createResult.Warnings != null)
                {
                    foreach (var w in createResult.Warnings)
                    {
                        if (!String.IsNullOrEmpty(w))
                        {
                            WriteWarning(w);
                        }
                    }
                }

                if (!String.IsNullOrEmpty(createResult.ID))
                {
                    MultiplexedStream stream = null;
                    Task streamTask          = null;
                    try
                    {
                        if (!Detach)
                        {
                            var parameters = new ContainerAttachParameters
                            {
                                Stdin  = Input,
                                Stdout = true,
                                Stderr = true,
                                Stream = true
                            };

                            stream = await DkrClient.Containers.AttachContainerAsync(createResult.ID, Terminal, parameters, CmdletCancellationToken);

                            streamTask = stream.CopyToConsoleAsync(Terminal, Input, CmdletCancellationToken);
                        }

                        if (!await DkrClient.Containers.StartContainerAsync(createResult.ID, new ContainerStartParameters()))
                        {
                            throw new ApplicationFailedException("The container has already started.");
                        }

                        if (!Detach)
                        {
                            await streamTask;
                        }
                    }
                    finally
                    {
                        stream?.Dispose();
                    }

                    if (RemoveAutomatically && !Detach)
                    {
                        await DkrClient.Containers.RemoveContainerAsync(createResult.ID,
                                                                        new ContainerRemoveParameters());
                    }
                    else if (PassThru)
                    {
                        WriteObject((await ContainerOperations.GetContainersById(createResult.ID, DkrClient)).Single());
                    }
                }
            }
        }