<commit_before>﻿using Docker.DotNet;
using Docker.DotNet.Models;
using Microsoft.AspNetCore.SignalR.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace DockerDash
{
    public class DockerService
    {
        private Task monitorContainersTask;
        private DockerClient docker;
        private readonly IConnectionManager _signalManager;
        private readonly ILogger<DockerService> _logger;

        public string Host { get; set; }
        public DockerService(IOptions<DockerHost> options, IConnectionManager signalManager, ILogger<DockerService> logger)
        {
            _logger = logger;
            Host = options.Value.Uri;
            _signalManager = signalManager;
            docker = new DockerClientConfiguration(new Uri(Host)).CreateClient();
        }

        public async Task<HostModel> GetHostInfo()
        {
            try
            {
                var info = await docker.Miscellaneous.GetSystemInfoAsync();
                return new HostModel
                {
                    Architecture = info.Architecture,
                    Containers = info.Containers,
                    ContainersPaused = info.ContainersPaused,
                    ContainersRunning = info.ContainersRunning,
                    ContainersStopped = info.ContainersStopped,
                    DefaultRuntime = info.DefaultRuntime,
                    Driver = info.Driver,
                    Id = info.ID,
                    Images = info.Images,
                    KernelVersion = info.KernelVersion,
                    LoggingDriver = info.LoggingDriver,
                    MemTotal = FormatBytes((ulong)info.MemTotal),
                    NCPU = info.NCPU,
                    Name = info.Name,
                    OperatingSystem = info.OperatingSystem,
                    OSType = info.OSType,
                    ServerVersion = info.ServerVersion,
                    ExecutionDriver = info.ExecutionDriver,
                    CgroupDriver = info.CgroupDriver,
                    NGoroutines = info.NGoroutines,
                    SwarmMode = info.Swarm.LocalNodeState,
                    SwarmManagers = info.Swarm.Managers,
                    SwarmNodes = info.Swarm.Nodes
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(1001, ex, ex.Message);
                throw;
            }
        }

        public async Task<List<ContainerModel>> GetContainerList()
        {
            try
            {
                var containers = await docker.Containers.ListContainersAsync(new ContainersListParameters()
                {
                    All = true
                });

                return containers.Select(c =>
                {
                    var cont = new ContainerModel
                    {
                        Id = c.ID,
                        Name = c.Names.First().StartsWith("/") ? c.Names.First().Remove(0, 1) : c.Names.First(),
                        Image = c.Image,
                        State = c.State,
                        Status = c.Status,
                        Command = c.Command,
                        Created = c.Created.ToString("dd-MM-yy HH:mm")
                    };

                    if (cont.State.ToLowerInvariant() == "running")
                    {
                        //var stats = GetContainerStats(c.ID);
                        //cont.MemoryUsage = FormatBytes(stats.MemoryStats.Usage);

                        if (c.NetworkSettings != null && c.NetworkSettings.Networks.Any())
                        {
                            cont.IpAddress = c.NetworkSettings.Networks.Select(n => n.Value.IPAddress).Aggregate((current, next) => current + ", " + next);
                        }

                        if (c.Ports.Any())
                        {
                            cont.Ports = c.Ports.Select(n => n.PrivatePort.ToString() + "/" + n.Type).Aggregate((current, next) => current + ", " + next);
                        }

                        dynamic stat = this.GetContainerStats(c.ID);
                        cont.MemoryUsage = stat.memory.label;
                    }

                    return cont;

                }).ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(1001, ex, ex.Message);
                throw;<commit_msg>Fix issue with pulling stat<commit_after>﻿using Docker.DotNet;
using Docker.DotNet.Models;
using Microsoft.AspNetCore.SignalR.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace DockerDash
{
    public class DockerService
    {
        private Task monitorContainersTask;
        private DockerClient docker;
        private readonly IConnectionManager _signalManager;
        private readonly ILogger<DockerService> _logger;

        public string Host { get; set; }
        public DockerService(IOptions<DockerHost> options, IConnectionManager signalManager, ILogger<DockerService> logger)
        {
            _logger = logger;
            Host = options.Value.Uri;
            _signalManager = signalManager;
            docker = new DockerClientConfiguration(new Uri(Host)).CreateClient();
        }

        public async Task<HostModel> GetHostInfo()
        {
            try
            {
                var info = await docker.Miscellaneous.GetSystemInfoAsync();
                return new HostModel
                {
                    Architecture = info.Architecture,
                    Containers = info.Containers,
                    ContainersPaused = info.ContainersPaused,
                    ContainersRunning = info.ContainersRunning,
                    ContainersStopped = info.ContainersStopped,
                    DefaultRuntime = info.DefaultRuntime,
                    Driver = info.Driver,
                    Id = info.ID,
                    Images = info.Images,
                    KernelVersion = info.KernelVersion,
                    LoggingDriver = info.LoggingDriver,
                    MemTotal = FormatBytes((ulong)info.MemTotal),
                    NCPU = info.NCPU,
                    Name = info.Name,
                    OperatingSystem = info.OperatingSystem,
                    OSType = info.OSType,
                    ServerVersion = info.ServerVersion,
                    ExecutionDriver = info.ExecutionDriver,
                    CgroupDriver = info.CgroupDriver,
                    NGoroutines = info.NGoroutines,
                    SwarmMode = info.Swarm.LocalNodeState,
                    SwarmManagers = info.Swarm.Managers,
                    SwarmNodes = info.Swarm.Nodes
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(1001, ex, ex.Message);
                throw;
            }
        }

        public async Task<List<ContainerModel>> GetContainerList()
        {
            try
            {
                var containers = await docker.Containers.ListContainersAsync(new ContainersListParameters()
                {
                    All = true
                });

                return containers.Select(c =>
                {
                    var cont = new ContainerModel
                    {
                        Id = c.ID,
                        Name = c.Names.First().StartsWith("/") ? c.Names.First().Remove(0, 1) : c.Names.First(),
                        Image = c.Image,
                        State = c.State,
                        Status = c.Status,
                        Command = c.Command,
                        Created = c.Created.ToString("dd-MM-yy HH:mm")
                    };

                    if (cont.State.ToLowerInvariant() == "running")
                    {
                        //var stats = GetContainerStats(c.ID);
                        //cont.MemoryUsage = FormatBytes(stats.MemoryStats.Usage);

                        if (c.NetworkSettings != null && c.NetworkSettings.Networks.Any())
                        {
                            cont.IpAddress = c.NetworkSettings.Networks.Select(n => n.Value.IPAddress).Aggregate((current, next) => current + ", " + next);
                        }

                        if (c.Ports.Any())
                        {
                            cont.Ports = c.Ports.Select(n => n.PrivatePort.ToString() + "/" + n.Type).Aggregate((current, next) => current + ", " + next);
                        }

                        var getStatTask = this.GetContainerStats(c.ID);
                        if(getStatTask.Wait(10000) && getStatTask.IsCompleted && !getStatTask.IsFaulted)
                        {
                            dynamic stat = getStatTask.Result;
                            cont.MemoryUsage = stat.memory.label;
                        }
                    }
                    return cont;

                }).ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(1001, ex, ex.Message);
                throw;
{'fraction_non_alphanumeric': 0.08511306532663317, 'fraction_numerical': 0.0026172529313232833, 'mean_word_length': 1.2837676308869232, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4317737', 'n_tokens_mistral': 2359, 'n_tokens_neox': 2170, 'n_words': 433}