Compare commits

...

5 Commits
dev ... main

Author SHA1 Message Date
b1c6c6cb44 (feature): readme contact info update 2024-11-02 16:11:12 +01:00
Maksym Sadovnychyy
87c27b6e8d (feature): add separate license file 2024-09-21 13:16:40 +02:00
Maksym Sadovnychyy
03b71068bb (bugfix): empty string json parse issue, code review 2024-08-18 18:52:24 +02:00
Maksym Sadovnychyy
6bcb99c40f (bugfix): package readme 2024-08-18 16:10:15 +02:00
Maksym Sadovnychyy
1252afe0d8 (refactor): redundant readme 2024-08-18 15:43:46 +02:00
7 changed files with 191 additions and 211 deletions

120
README.md
View File

@ -1,15 +1,12 @@
Sure! Here's how your README file would look in Markdown format:
```markdown
# PodmanClientDotNet
# PodmanClient.DotNet
## Description
`PodmanClientDotNet` is a .NET library designed to provide seamless interaction with the Podman API, allowing developers to manage and control containers directly from their .NET applications. This client library wraps the Podman API endpoints, offering a .NET-friendly interface to perform common container operations such as creating, starting, stopping, deleting containers, and more.
`PodmanClient.DotNet` is a .NET library designed to provide seamless interaction with the Podman API, allowing developers to manage and control containers directly from their .NET applications. This client library wraps the Podman API endpoints, offering a .NET-friendly interface to perform common container operations such as creating, starting, stopping, deleting containers, and more.
## Purpose
The primary goal of `PodmanClientDotNet` is to simplify the integration of Podman into .NET applications by providing a comprehensive, easy-to-use client library. Whether you're managing container lifecycles, executing commands inside containers, or manipulating container images, this library allows developers to interface with Podman using the familiar .NET development environment.
The primary goal of `PodmanClient.DotNet` is to simplify the integration of Podman into .NET applications by providing a comprehensive, easy-to-use client library. Whether you're managing container lifecycles, executing commands inside containers, or manipulating container images, this library allows developers to interface with Podman using the familiar .NET development environment.
## Key Features
@ -18,14 +15,32 @@ The primary goal of `PodmanClientDotNet` is to simplify the integration of Podma
- **Exec Support:** Execute commands inside running containers, with support for attaching input/output streams.
- **Volume and Network Management:** Manage container volumes and networks as needed.
- **Streamlined Error Handling:** Provides detailed error handling, with informative responses based on HTTP status codes.
- **Customizable HTTP Client:** Easily configure and inject your own `HttpClient` instance for extended control and customization.
- **Logging Support:** Integrated logging support via `Microsoft.Extensions.Logging` for better observability.
## Usage Example
## Installation
To include `PodmanClient.DotNet` in your .NET project, you can add the package via NuGet:
```shell
dotnet add package PodmanClient.DotNet
```
## Usage Examples
### Initialize the PodmanClient
```csharp
// Initialize the PodmanClient with base URL and timeout
var podmanClient = new PodmanClient("http://localhost:8080", 5);
using Microsoft.Extensions.Logging;
using MaksIT.PodmanClient.DotNet;
// Create a new container
var logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger<PodmanClient>();
var podmanClient = new PodmanClient(logger, "http://localhost:8080", 5);
```
### Create and Start a Container
```csharp
var createResponse = await podmanClient.CreateContainerAsync(
name: "my-container",
image: "alpine:latest",
@ -34,23 +49,52 @@ var createResponse = await podmanClient.CreateContainerAsync(
remove: true
);
// Start the container
await podmanClient.StartContainerAsync(createResponse.Id);
```
// Execute a command inside the container
### Execute a Command in a Container
```csharp
var execResponse = await podmanClient.CreateExecAsync(createResponse.Id, new[] { "echo", "Hello, World!" });
await podmanClient.StartExecAsync(execResponse.Id);
```
## Installation
### Pull an Image
To include `PodmanClientDotNet` in your .NET project, you can add the package via NuGet:
```shell
dotnet add package PodmanClient.DotNet --version 1.0.2
```csharp
await podmanClient.PullImageAsync("alpine:latest");
```
## Documentation
### Tag an Image
```csharp
await podmanClient.TagImageAsync("alpine:latest", "myrepo", "mytag");
```
## Available Methods
### `PodmanClient`
- **Container Management**
- `Task<CreateContainerResponse> CreateContainerAsync(...)`: Creates a new container.
- `Task StartContainerAsync(string containerId, string detachKeys = "ctrl-p,ctrl-q")`: Starts an existing container.
- `Task StopContainerAsync(string containerId, int timeout = 10, bool ignoreAlreadyStopped = false)`: Stops a running container.
- `Task DeleteContainerAsync(string containerId, bool depend = false, bool ignore = false, int timeout = 10)`: Deletes a container.
- `Task ForceDeleteContainerAsync(string containerId, bool deleteVolumes = false, int timeout = 10)`: Forcefully deletes a container, optionally removing associated volumes.
- **Exec Management**
- `Task<CreateExecResponse> CreateExecAsync(...)`: Creates an exec instance in a running container.
- `Task StartExecAsync(string execId, bool detach = false, bool tty = false, int? height = null, int? width = null)`: Starts an exec instance.
- `Task<InspectExecResponse?> InspectExecAsync(string execId)`: Inspects an exec instance to retrieve its details.
- **Image Operations**
- `Task PullImageAsync(...)`: Pulls an image from a container registry.
- `Task TagImageAsync(string image, string repo, string tag)`: Tags an existing image with a new repository and tag.
- **File Operations**
- `Task ExtractArchiveToContainerAsync(string containerId, Stream tarStream, string path, bool pause = true)`: Extracts files from a tar stream into a container.
## Documentation (TODO: Agile)
For detailed documentation on each method, including parameter descriptions and example usage, please refer to the official documentation (link to be provided).
@ -58,13 +102,45 @@ For detailed documentation on each method, including parameter descriptions and
Contributions to this project are welcome! Please fork the repository and submit a pull request with your changes. If you encounter any issues or have feature requests, feel free to open an issue on GitHub.
## Contact
If you have any questions or need further assistance, feel free to reach out:
- **Email**: [maksym.sadovnychyy@gmail.com](mailto:maksym.sadovnychyy@gmail.com)
- **Reddit**: [PodmanClient.DotNet: A .NET Library for Streamlined Podman API Integration](https://www.reddit.com/r/MaksIT/comments/1evel9z/podmanclientdotnet_a_net_library_for_streamlined/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button)
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE.md) file for details.
This project is licensed under the MIT License. See the full license text below.
---
### MIT License
```
MIT License
Copyright (c) 2024 Maksym Sadovnychyy (MAKS-IT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
## Contact
For any questions or inquiries, please reach out via GitHub or [email](mailto:maksym.sadovnychyy@gmail.com).
```
This Markdown file is structured to provide a clear and informative README for your GitHub repository, offering essential details about your `PodmanClientDotNet` library.

View File

@ -6,11 +6,12 @@ using Microsoft.Extensions.Logging;
using MaksIT.PodmanClientDotNet.Models;
using MaksIT.PodmanClientDotNet.Models.Container;
using MaksIT.PodmanClientDotNet.Extensions;
using MaksIT.PodmanClientDotNet.Models.Exec;
namespace MaksIT.PodmanClientDotNet {
public partial class PodmanClient {
public async Task<CreateContainerResponse> CreateContainerAsync(
public async Task<CreateContainerResponse?> CreateContainerAsync(
string name,
string image,
List<string> command = null,
@ -252,7 +253,9 @@ namespace MaksIT.PodmanClientDotNet {
if (response.IsSuccessStatusCode) {
var jsonResponse = await response.Content.ReadAsStringAsync();
return jsonResponse.ToObject<CreateContainerResponse>();
return !string.IsNullOrWhiteSpace(jsonResponse)
? jsonResponse.ToObject<CreateContainerResponse>()
: null;
}
else {
var errorContent = await response.Content.ReadAsStringAsync();
@ -277,7 +280,6 @@ namespace MaksIT.PodmanClientDotNet {
}
response.EnsureSuccessStatusCode();
return null;
}
}
@ -288,6 +290,14 @@ namespace MaksIT.PodmanClientDotNet {
var response = await _httpClient.PostAsync(
$"/{_apiVersion}/libpod/containers/{containerId}/start?detachKeys={Uri.EscapeDataString(detachKeys)}", null);
if (response.IsSuccessStatusCode) {
var jsonResponse = await response.Content.ReadAsStringAsync();
}
else {
}
switch (response.StatusCode) {
case System.Net.HttpStatusCode.NoContent:
_logger.LogInformation("Container started successfully.");
@ -326,6 +336,8 @@ namespace MaksIT.PodmanClientDotNet {
var response = await _httpClient.PostAsync($"/{_apiVersion}/libpod/containers/{containerId}/stop{queryParams}", null);
if (response.IsSuccessStatusCode) {
var jsonResponse = await response.Content.ReadAsStringAsync();
if (response.StatusCode == System.Net.HttpStatusCode.NoContent) {
_logger.LogInformation("Container stopped successfully.");
}
@ -355,27 +367,15 @@ namespace MaksIT.PodmanClientDotNet {
}
}
public async Task ForceDeleteContainerAsync(string containerId, bool deleteVolumes = false, int timeout = 10) {
public async Task<DeleteContainerResponse[]?> ForceDeleteContainerAsync(string containerId, bool deleteVolumes = false, int timeout = 10) {
var queryParams = $"?force=true&v={deleteVolumes.ToString().ToLower()}&timeout={timeout}";
var response = await _httpClient.DeleteAsync($"/{_apiVersion}/libpod/containers/{containerId}{queryParams}");
if (response.IsSuccessStatusCode) {
if (response.StatusCode == System.Net.HttpStatusCode.NoContent) {
_logger.LogInformation("Container force deleted successfully.");
}
else if (response.StatusCode == System.Net.HttpStatusCode.OK) {
var responseContent = await response.Content.ReadAsStringAsync();
var deleteResponses = responseContent.ToObject<DeleteContainerResponse[]>();
foreach (var deleteResponse in deleteResponses) {
if (string.IsNullOrEmpty(deleteResponse.Err)) {
_logger.LogInformation($"Container {deleteResponse.Id} deleted successfully.");
}
else {
_logger.LogError($"Error deleting container {deleteResponse.Id}: {deleteResponse.Err}");
}
}
}
var jsonResponse = await response.Content.ReadAsStringAsync();
return !string.IsNullOrWhiteSpace(jsonResponse)
? jsonResponse.ToObject<DeleteContainerResponse[]>()
: null;
}
else {
var errorContent = await response.Content.ReadAsStringAsync();
@ -404,34 +404,23 @@ namespace MaksIT.PodmanClientDotNet {
}
response.EnsureSuccessStatusCode();
return null;
}
}
public async Task DeleteContainerAsync(string containerId, bool depend = false, bool ignore = false, int timeout = 10) {
public async Task<DeleteContainerResponse[]?> DeleteContainerAsync(string containerId, bool depend = false, bool ignore = false, int timeout = 10) {
var queryParams = $"?depend={depend.ToString().ToLower()}&ignore={ignore.ToString().ToLower()}&timeout={timeout}";
var response = await _httpClient.DeleteAsync($"/libpod/containers/{containerId}{queryParams}");
var response = await _httpClient.DeleteAsync($"/{_apiVersion}/containers/{containerId}{queryParams}");
if (response.IsSuccessStatusCode) {
if (response.StatusCode == System.Net.HttpStatusCode.NoContent) {
_logger.LogInformation("Container deleted successfully.");
}
else if (response.StatusCode == System.Net.HttpStatusCode.OK) {
var responseContent = await response.Content.ReadAsStringAsync();
var deleteResponses = JsonSerializer.Deserialize<DeleteContainerResponse[]>(responseContent);
foreach (var deleteResponse in deleteResponses) {
if (string.IsNullOrEmpty(deleteResponse.Err)) {
_logger.LogInformation($"Container {deleteResponse.Id} deleted successfully.");
}
else {
_logger.LogInformation($"Error deleting container {deleteResponse.Id}: {deleteResponse.Err}");
}
}
}
var jsonResponse = await response.Content.ReadAsStringAsync();
return !string.IsNullOrWhiteSpace(jsonResponse)
? jsonResponse.ToObject<DeleteContainerResponse []>()
: null;
}
else {
var errorContent = await response.Content.ReadAsStringAsync();
var errorDetails = JsonSerializer.Deserialize<ErrorResponse>(errorContent);
var errorDetails = errorContent.ToObject<ErrorResponse>();
switch (response.StatusCode) {
case System.Net.HttpStatusCode.BadRequest:
@ -455,7 +444,8 @@ namespace MaksIT.PodmanClientDotNet {
break;
}
response.EnsureSuccessStatusCode(); // Throws an exception if the response indicates an error
response.EnsureSuccessStatusCode();
return null;
}
}
@ -469,7 +459,8 @@ namespace MaksIT.PodmanClientDotNet {
var response = await _httpClient.PutAsync($"/{_apiVersion}/libpod/containers/{containerId}/archive{queryParams}", content);
if (response.IsSuccessStatusCode) {
_logger.LogInformation("Files copied successfully to the container.");
var stringResponse = await response.Content.ReadAsStringAsync();
_logger.LogInformation($"Files copied successfully to the container.\n\n{stringResponse}".Trim());
}
else {
var errorContent = await response.Content.ReadAsStringAsync();

View File

@ -8,7 +8,7 @@
<!-- NuGet package metadata -->
<PackageId>PodmanClient.DotNet</PackageId>
<Version>1.0.3</Version>
<Version>1.0.4</Version>
<Authors>Maksym Sadovnychyy</Authors>
<Company>MAKS-IT</Company>
<Product>PodmanClient.DotNet</Product>
@ -22,7 +22,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<None Include="README.md" Pack="true" />
<None Include="../../README.md" Pack="true" PackagePath="" />
</ItemGroup>
</Project>

View File

@ -10,7 +10,7 @@ using MaksIT.PodmanClientDotNet.Extensions;
namespace MaksIT.PodmanClientDotNet {
public partial class PodmanClient {
public async Task<CreateExecResponse> CreateExecAsync(
public async Task<CreateExecResponse?> CreateExecAsync(
string containerName,
string[] cmd,
bool attachStderr = true,
@ -49,7 +49,9 @@ namespace MaksIT.PodmanClientDotNet {
if (response.IsSuccessStatusCode) {
var jsonResponse = await response.Content.ReadAsStringAsync();
return jsonResponse.ToObject<CreateExecResponse>();
return !string.IsNullOrWhiteSpace(jsonResponse)
? jsonResponse.ToObject<CreateExecResponse>()
: null;
}
else {
var jsonResponse = await response.Content.ReadAsStringAsync();
@ -103,8 +105,7 @@ namespace MaksIT.PodmanClientDotNet {
if (response.IsSuccessStatusCode) {
var stringResponse = await response.Content.ReadAsStringAsync();
_logger.LogInformation(stringResponse);
_logger.LogInformation($"Command executed successfully.\n\n{stringResponse}".Trim());
}
else {
var jsonResponse = await response.Content.ReadAsStringAsync();
@ -137,7 +138,9 @@ namespace MaksIT.PodmanClientDotNet {
if (response.IsSuccessStatusCode) {
var jsonResponse = await response.Content.ReadAsStringAsync();
return jsonResponse.ToObject<InspectExecResponse>();
return !string.IsNullOrWhiteSpace(jsonResponse)
? jsonResponse.ToObject<InspectExecResponse>()
: null;
}
else {
var jsonResponse = await response.Content.ReadAsStringAsync();

View File

@ -1,139 +0,0 @@
# PodmanClient.DotNet
## Description
`PodmanClient.DotNet` is a .NET library designed to provide seamless interaction with the Podman API, allowing developers to manage and control containers directly from their .NET applications. This client library wraps the Podman API endpoints, offering a .NET-friendly interface to perform common container operations such as creating, starting, stopping, deleting containers, and more.
## Purpose
The primary goal of `PodmanClient.DotNet` is to simplify the integration of Podman into .NET applications by providing a comprehensive, easy-to-use client library. Whether you're managing container lifecycles, executing commands inside containers, or manipulating container images, this library allows developers to interface with Podman using the familiar .NET development environment.
## Key Features
- **Container Management:** Create, start, stop, and delete containers with straightforward methods.
- **Image Operations:** Pull, tag, and manage images using the Podman API.
- **Exec Support:** Execute commands inside running containers, with support for attaching input/output streams.
- **Volume and Network Management:** Manage container volumes and networks as needed.
- **Streamlined Error Handling:** Provides detailed error handling, with informative responses based on HTTP status codes.
- **Customizable HTTP Client:** Easily configure and inject your own `HttpClient` instance for extended control and customization.
- **Logging Support:** Integrated logging support via `Microsoft.Extensions.Logging` for better observability.
## Installation
To include `PodmanClient.DotNet` in your .NET project, you can add the package via NuGet:
```shell
dotnet add package PodmanClient.DotNet
```
## Usage Examples
### Initialize the PodmanClient
```csharp
using Microsoft.Extensions.Logging;
using MaksIT.PodmanClient.DotNet;
var logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger<PodmanClient>();
var podmanClient = new PodmanClient(logger, "http://localhost:8080", 5);
```
### Create and Start a Container
```csharp
var createResponse = await podmanClient.CreateContainerAsync(
name: "my-container",
image: "alpine:latest",
command: new List<string> { "/bin/sh" },
env: new Dictionary<string, string> { { "ENV_VAR", "value" } },
remove: true
);
await podmanClient.StartContainerAsync(createResponse.Id);
```
### Execute a Command in a Container
```csharp
var execResponse = await podmanClient.CreateExecAsync(createResponse.Id, new[] { "echo", "Hello, World!" });
await podmanClient.StartExecAsync(execResponse.Id);
```
### Pull an Image
```csharp
await podmanClient.PullImageAsync("alpine:latest");
```
### Tag an Image
```csharp
await podmanClient.TagImageAsync("alpine:latest", "myrepo", "mytag");
```
## Available Methods
### `PodmanClient`
- **Container Management**
- `Task<CreateContainerResponse> CreateContainerAsync(...)`: Creates a new container.
- `Task StartContainerAsync(string containerId, string detachKeys = "ctrl-p,ctrl-q")`: Starts an existing container.
- `Task StopContainerAsync(string containerId, int timeout = 10, bool ignoreAlreadyStopped = false)`: Stops a running container.
- `Task DeleteContainerAsync(string containerId, bool depend = false, bool ignore = false, int timeout = 10)`: Deletes a container.
- `Task ForceDeleteContainerAsync(string containerId, bool deleteVolumes = false, int timeout = 10)`: Forcefully deletes a container, optionally removing associated volumes.
- **Exec Management**
- `Task<CreateExecResponse> CreateExecAsync(...)`: Creates an exec instance in a running container.
- `Task StartExecAsync(string execId, bool detach = false, bool tty = false, int? height = null, int? width = null)`: Starts an exec instance.
- `Task<InspectExecResponse?> InspectExecAsync(string execId)`: Inspects an exec instance to retrieve its details.
- **Image Operations**
- `Task PullImageAsync(...)`: Pulls an image from a container registry.
- `Task TagImageAsync(string image, string repo, string tag)`: Tags an existing image with a new repository and tag.
- **File Operations**
- `Task ExtractArchiveToContainerAsync(string containerId, Stream tarStream, string path, bool pause = true)`: Extracts files from a tar stream into a container.
## Documentation (TODO: Agile)
For detailed documentation on each method, including parameter descriptions and example usage, please refer to the official documentation (link to be provided).
## Contribution
Contributions to this project are welcome! Please fork the repository and submit a pull request with your changes. If you encounter any issues or have feature requests, feel free to open an issue on GitHub.
## License
This project is licensed under the MIT License. See the full license text below.
---
### MIT License
```
MIT License
Copyright (c) 2024 Maksym Sadovnychyy (MAKS-IT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
## Contact
For any questions or inquiries, please reach out via GitHub or [email](mailto:maksym.sadovnychyy@gmail.com).

View File

@ -0,0 +1,49 @@
#!/bin/sh
# Retrieve the API key from the environment variable
apiKey=$NUGET_MAKS_IT
if [ -z "$apiKey" ]; then
echo "Error: API key not found in environment variable NUGET_MAKS_IT."
exit 1
fi
# NuGet source
nugetSource="https://api.nuget.org/v3/index.json"
# Define paths
scriptDir=$(dirname "$0")
solutionDir=$(realpath "$scriptDir")
projectDir="$solutionDir/PodmanClient"
outputDir="$projectDir/bin/Release"
# Clean previous builds
echo "Cleaning previous builds..."
dotnet clean "$projectDir" -c Release
# Build the project
echo "Building the project..."
dotnet build "$projectDir" -c Release
# Pack the NuGet package
echo "Packing the project..."
dotnet pack "$projectDir" -c Release --no-build
# Look for the .nupkg file
packageFile=$(find "$outputDir" -name "*.nupkg" -print0 | xargs -0 ls -t | head -n 1)
if [ -n "$packageFile" ]; then
echo "Package created successfully: $packageFile"
# Push the package to NuGet
echo "Pushing the package to NuGet..."
dotnet nuget push "$packageFile" -k "$apiKey" -s "$nugetSource" --skip-duplicate
if [ $? -eq 0 ]; then
echo "Package pushed successfully."
else
echo "Failed to push the package."
fi
else
echo "Package creation failed. No .nupkg file found."
exit 1
fi