メインコンテンツへスキップ

動画の分散エンコードクラスタを自作・運用している話・82

    目次

    マネージャの解説2 

    ここは分けた2個目です。


    Class OPERATION 

    public abstract partial class OPERATION
    {
        public abstract bool CheckFinish(APPLICATION AppData, Dictionary<string, string> recieve_data);
        public virtual double GetEstimateTime(APPLICATION AppData, double speed) => 0;
        public virtual double GetOperationSpeed(APPLICATION AppData, double time_sec) => 0;
        public virtual double GetRemainFrame(APPLICATION AppData) => 0;
    
        public string Type;
    
        public Dictionary<string, string> Arg;
        public string DstPath;
        public bool finish;
        public int OperationSize;
        public DateTime StartTime;
        public DateTime EndTime;
        public double Progress;
        public Dictionary<string, int> ErrorHistory;
    
        public OPERATION(string op_type, Dictionary<string,string> data, int op_size)
        {
            Type = op_type;
            Arg = data;
            OperationSize = op_size;
    
            DstPath = data[JOB_DATA.OUTPUT];
            StartTime = DateTime.MinValue;
            EndTime = DateTime.MinValue;
    
            finish = false;
            Progress = 0;
            ErrorHistory = new Dictionary<string, int>();
        }
    }
    
    public partial class OPERATION
    {
        public double GetLimitTime(APPLICATION AppData, double speed)
            => GetEstimateTime(AppData, speed) * AppData.TimeLimitRate;
    
        public int ErrorCountUp(string server_name)
        {
            if (ErrorHistory.Keys.Contains(server_name) == true)
                ErrorHistory[server_name]++;
            else
                ErrorHistory[server_name] = 1;
    
            return ErrorHistory[server_name];
        }
    
        public int ErrorCount(string server_name)
        {
            int ans = 0;
            if (ErrorHistory.Keys.Contains(server_name) == true)
                ans = ErrorHistory[server_name];
    
            return ans;
        }
    
        public void FinishOperation()
        {
            this.EndTime = DateTime.Now;
            this.finish = true;
        }
    
        public void ResetOperation()
        {
            while (File.Exists(this.DstPath) == true)
            {
                File.Delete(this.DstPath);
                Thread.Sleep(100);
            }
    
            this.StartTime = DateTime.MinValue;
        }
    
        public double GetPassedSecond()
        {
            if (this.StartTime == DateTime.MinValue)
                return -1;
    
            if (this.EndTime > this.StartTime)
                return (this.EndTime - this.StartTime).TotalSeconds;
    
            return (DateTime.Now - this.StartTime).TotalSeconds;
        }
    }
    
    public partial class OPERATION
    {
        public static string CreateJsonString(Dictionary<string, string> data)
        {
            return JsonSerializer.Serialize(data);
        }
    }
    
    public struct OPERATION_TYPE
    {
        public const string VIDEO = "VIDEO";
        public const string AUDIO = "AUDIO";
    }
    
    public class OPERATION_CREATER
    {
        public static OPERATION CreateOperation(Dictionary<string, string> data, int op_size)
        {
            OPERATION op = null;
    
            switch (data[JOB_DATA.TYPE])
            {
                case OPERATION_TYPE.VIDEO:
                    op = new OPERATION_VIDEO(data, op_size);
                    break;
    
                case OPERATION_TYPE.AUDIO:
                    op = new OPERATION_AUDIO(data, op_size);
                    break;
            }
    
            return op;
        }
    }

    ジョブを管理するための基底クラスです。各ジョブに必要な共通機能とメソッドを提供します。


    Class OPERATION_VIDEO / OPERATION_AUDIO

    public partial class OPERATION_VIDEO : OPERATION
    {
        public OPERATION_VIDEO(Dictionary<string, string> data, int frame_length) : base(OPERATION_TYPE.VIDEO, data, frame_length)
        {
            OperationSize = data[JOB_DATA.END].ToInt() - data[JOB_DATA.START].ToInt();
        }
    
        public override bool CheckFinish(APPLICATION AppData, Dictionary<string, string> recieve_data)
        {
            if (recieve_data.Keys.Contains(JOB_DATA.PROGRESS) == true)
                this.Progress = recieve_data[JOB_DATA.PROGRESS].ToDouble(0);
    
            if (File.Exists(this.DstPath) == false)
                return false;
    
            var result_length = APPLICATION.GetFileFrame(AppData, this.DstPath);
            var job_length = this.OperationSize;
    
            if (result_length != job_length)
                return false;
    
            return true;
        }
    
        public override double GetRemainFrame(APPLICATION AppData)
            => this.OperationSize * (100 - this.Progress) / 100;
    
        public override double GetEstimateTime(APPLICATION AppData, double speed)
            => this.OperationSize / speed;
    
        public override double GetOperationSpeed(APPLICATION AppData, double time)
            => this.OperationSize / time;
    }
    public partial class OPERATION_AUDIO : OPERATION
    {
        public OPERATION_AUDIO(Dictionary<string, string> data, int frame_length) : base(OPERATION_TYPE.AUDIO, data, frame_length) { }
    
        public override bool CheckFinish(APPLICATION AppData, Dictionary<string, string> recieve_data)
        {
            if (File.Exists(this.DstPath) == false)
                return false;
    
            return true;
        }
    }

    OPERATIONクラスの派生クラスです。個別の処理を担います。ここでは特に、ジョブの完了後の処理(フレーム数の確認の有無)が異なるので、違うメソッドになっています。


    Class REMOTE

    public partial class REMOTE
    {
        public string Name;
        public string Address;
        public int Port;
        public string MACAddress;
        public string State;
    
        public DateTime LastConnectTime;
    
        uint SpeedHistory;
        public List<double> SpeedList;
        public double Speed
        {
            get { return SpeedList.Average(); }
            set
            {
                SpeedList.Add(value);
                while (SpeedList.Count > SpeedHistory)
                    SpeedList.RemoveAt(0);
            }
        }
    
        public Task<string> Task;
        public OPERATION Operation;
    
        public REMOTE(string name, string address, int port, string mac, uint speed_history)
        {
            Name = name;
            Address = address;
            Port = port;
            MACAddress = mac;
            SpeedHistory = speed_history;
            SpeedList = new List<double>();
            Speed = 1.0;
            Task = null;
            Operation = null;
            LastConnectTime = DateTime.MinValue;
            State = REMOTE_STATE.NULL;
        }
    }
    
    public partial class REMOTE
    {
        public string CheckState(APPLICATION AppData, Dictionary<string, string> recieve_data)
        {
            var task_status = "";
    
            var is_job_finish = false;
            if (this.Operation != null)
                is_job_finish = this.Operation.CheckFinish(AppData, recieve_data);
    
            switch (recieve_data[JOB_DATA.STATUS])
            {
                // 処理完了
                case JOB_STATUS.FINISH:
                    if (this.Operation != null)
                    {
                        if (is_job_finish == true)
                        {
                            this.Operation.FinishOperation();
                            task_status = this.FinishOperation(AppData);
                        }
                        else
                        {
                            task_status = this.TerminetedOperation(AppData);
                        }
    
                        APPLICATION.RecordLog(task_status);
                    }
                    this.LastConnectTime = DateTime.Now;
                    this.Operation = null;
                    this.State = REMOTE_STATE.NULL;
                    break;
    
                // ジョブのリセット
                case JOB_STATUS.TERMINATED:
                    if (this.Operation != null)
                    {
                        task_status = this.TerminetedOperation(AppData);
                        APPLICATION.RecordLog(task_status);
                    }
    
                    this.LastConnectTime = DateTime.Now;
                    this.Operation = null;
                    this.State = REMOTE_STATE.NULL;
                    break;
    
                // 処理中
                case JOB_STATUS.OPERATING:
                    task_status = OperatingOperation(AppData);
                    this.LastConnectTime = DateTime.Now;
                    this.State = REMOTE_STATE.OPERATING;
                    break;
    
                // 処理開始
                case JOB_STATUS.START:
                    task_status = StartOperation(AppData);
                    APPLICATION.RecordLog(task_status);
                    this.LastConnectTime = DateTime.Now;
                    this.State = REMOTE_STATE.START;
                    break;
    
                // 処理なし
                case REMOTE_STATE.NULL:
                    task_status = $"{this.Name} : NULL";
                    this.State = REMOTE_STATE.NULL;
                    break;
    
                // サーバー不在
                case REMOTE_STATE.NO_SERVER:
                    task_status = $"{this.Name} : Waiting...";
                    this.State = REMOTE_STATE.NO_SERVER;
                    break;
    
                // サーバー接続確認
                case REMOTE_STATE.READY:
                    task_status = $"{this.Name} : READY";
                    this.LastConnectTime = DateTime.Now;
                    this.State = REMOTE_STATE.READY;
                    break;
            }
    
            return task_status;
        }
    
        public string FinishOperation(APPLICATION AppData)
        {
            var passed_time = this.Operation.GetPassedSecond();
            var dst_file_name = $@"{Path.GetFileName(this.Operation.DstPath)}";
    
            var task_status = new List<string>()
            {
                $"{this.Name} :"
            };
    
            switch (this.Operation.Type)
            {
                case OPERATION_TYPE.VIDEO:
                    this.Speed = this.Operation.OperationSize / passed_time;
                    task_status.Add($"{this.Operation.Progress:0.0}%");
                    task_status.Add($"{dst_file_name} Compelete.");
                    task_status.Add($"{this.Operation.OperationSize}frames");
                    task_status.Add($"{passed_time:0.0}s");
                    task_status.Add($"{this.Speed:0.0}fps");
                    break;
    
                case OPERATION_TYPE.AUDIO:
                    task_status.Add($"{dst_file_name} Compelete.");
                    task_status.Add($"{passed_time:0.0}s");
                    break;
            }
    
            return task_status.ToList().Aggregate((a, b) => $"{a} {b}");
        }
    
        public string TerminetedOperation(APPLICATION AppData)
        {
            var passed_time = this.Operation.GetPassedSecond();
            var dst_file_name = $@"{Path.GetFileName(this.Operation.DstPath)}";
    
            int error_count = this.Operation.ErrorCountUp(this.Name);
    
            var task_status = new List<string>()
            {
                $"{this.Name} :",
                $"{dst_file_name} Error.",
                $"Count:{error_count}",
                $"{passed_time:0.0}s",
    
            }.ToList().Aggregate((a, b) => $"{a} {b}");
    
            this.Operation.ResetOperation();
    
            return task_status;
        }
    
        public string OperatingOperation(APPLICATION AppData)
        {
            var passed_time = this.Operation.GetPassedSecond();
            var dst_file_name = $@"{Path.GetFileName(this.Operation.DstPath)}";
    
            var task_status = new List<string>()
            {
                $"{this.Name} :",
            };
    
            switch (this.Operation.Type)
            {
                case OPERATION_TYPE.VIDEO:
                    task_status.Add($"{this.Operation.Progress:0.0}%");
                    task_status.Add($"{dst_file_name} Operating.");
                    task_status.Add($"{passed_time:0.0}s/{this.Operation.OperationSize / this.Speed:0.0}s");
                    break;
    
                case OPERATION_TYPE.AUDIO:
                    task_status.Add($"{dst_file_name} Operating.");
                    task_status.Add($"{passed_time:0.0}s");
                    break;
            }
    
            return task_status.ToList().Aggregate((a, b) => $"{a} {b}");
        }
    
        public string StartOperation(APPLICATION AppData)
        {
            var dst_file_name = $@"{Path.GetFileName(this.Operation.DstPath)}";
    
            this.Operation.StartTime = DateTime.Now;
    
            var task_status = $"{this.Name} : {dst_file_name} Start.";
            
            return task_status;
        }
    }
    
    public partial class REMOTE
    {
        public string Connect(string send_msg)
        {
            if (IsExists() == false)
                return Wakeup();
    
            string ans = "";
            try
            {
                ans = TransportData(this.Address, this.Port, send_msg);
            }
            catch (SocketException e)
            {
                ans = $@"{{""{JOB_DATA.STATUS}"":""{REMOTE_STATE.NO_SERVER}""}}";
            }
    
            return ans;
        }
    
        public string TransportData(string this_address, int this_port, string send_msg)
        {
            var socket = new TcpClient();
    
            socket.Connect(this_address, this_port);
    
            using (var ns = socket.GetStream())
            {
                var recv_msg = "";
    
                // メッセージのエンコード
                var codec = new CODEC();
                byte[] send_buffer = codec.Encode(send_msg);
    
                try
                {
                    // メッセージの送信
                    ns.Write(send_buffer, 0, send_buffer.Length);
    
                    // メッセージの受信
                    recv_msg = RecieveData(ns);
                }
                catch { }
    
                return recv_msg;
            }
        }
    
        public string RecieveData(NetworkStream ns)
        {
            var codec = new CODEC();
    
            var size = 1;
            var data = new byte[1] { 0 };
    
            for (int i = 0; i < 3; i++)
            {
                data = RecieveSingleData(ns, size);
                size = codec.Decode(data).Trim('\0').ToInt(-1);
    
                if (size < 1)
                    break;
            }
    
            if (IsDisconnect(data) == true)
                return null;
    
            // メッセージのデコード
            return codec.Decode(data);
        }
    
        byte[] RecieveSingleData(NetworkStream ns, int count)
        {
            if (count < 1)
                return null;
    
            var buf = new byte[count];
            var DataLength = count;
            var RecievedLength = 0;
    
            using (var ms = new MemoryStream())
            {
                do
                {
                    if (DataLength <= RecievedLength)
                        break;
    
                    int n = 0;
    
                    n = ns.Read(buf, 0, DataLength - RecievedLength);
    
                    if (n < 1)
                        return new byte[4] { 255, 255, 255, 255 };
    
                    ms.Write(buf, 0, n);
    
                    RecievedLength += n;
                }
                while (ns.DataAvailable);
            }
            return buf;
        }
    
        bool IsDisconnect(byte[] buf)
        {
            if (buf?.Length != 4)
                return false;
    
            var value = BitConverter.ToInt32(buf, 0);
    
            if (value != ~0)
                return false;
    
            return true;
        }
    }
    
    public partial class REMOTE
    {
        public bool IsExists()
        {
            var ans = false;
    
            var ping = new Ping();
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    var result = ping.Send(this.Address, 1000);
                    if (result.Status == IPStatus.Success)
                    {
                        ans = true;
                        break;
                    }
                }
                catch { }
            }
    
            return ans;
        }
    
        public string Wakeup()
        {
            var mac_byte = MACtoByteArray();
    
            var packet = new byte[6 + 16 * 6];
    
            for (int i = 0; i < 6; i++)
                packet[i] = 0xff;
    
            for (int i = 0; i < 16; i++)
                Buffer.BlockCopy(mac_byte, 0, packet, 6 + i * mac_byte.Length, mac_byte.Length);
    
            var broadcast_address = IPAddress.Broadcast;
            using (var client = new UdpClient())
            {
                client.EnableBroadcast = true;
                var endpoint = new IPEndPoint(broadcast_address, this.Port);
                client.Send(packet, packet.Length, endpoint);
            }
    
            return $@"{{""{JOB_DATA.STATUS}"":""{REMOTE_STATE.NO_SERVER}""}}";
        }
    
        byte[] MACtoByteArray()
        {
            var mac_string = this.MACAddress.Replace(":", "").Trim();
    
            if (mac_string.Length != 12)
                mac_string = "000000000000";
    
            var byte_array = Enumerable.Range(0, 6)
                                       .Select(i => mac_string.Substring(i * 2, 2))
                                       .Select(s => Convert.ToByte(s, 16))
                                       .ToArray();
            return byte_array;
        }
    }
    
    public partial class CODEC
    {
        public byte[] Encode(string str)
        {
            var enc = Encoding.UTF8;
    
            var main_data = enc.GetBytes(str);
            var second_data = enc.GetBytes(main_data.Length.ToString());
            var first_data = enc.GetBytes(second_data.Length.ToString());
    
            return first_data.Concat(second_data).Concat(main_data).ToArray();
        }
    }
    
    public partial class CODEC
    {
        public string Decode(byte[] data)
        {
            var enc = Encoding.UTF8;
            return enc.GetString(data);
        }
    }

    ノードの管理を行います。ここでの役割は、ノードとの実際の通信、ノードへのマジックパケットの送出、ノードの応答の解釈などです。


    おまけ2

    まだ長いので分けます。次がラストです。

     
     
    私は自宅で動画エンコードクラスタを運用している日曜プログラマです。13年以上にわたる運用での気付きや自作クラスタへのフィードバックをまとめていきたいと思います。

    あなたへのおすすめ