aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/embeddable-dll-service/csharp/TunnelDll/Ringlogger.cs
blob: 469927c1b7969c8edafa847d9e6ed4addb59abae (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/* SPDX-License-Identifier: MIT
 *
 * Copyright (C) 2019-2021 WireGuard LLC. All Rights Reserved.
 */

using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Text;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.CompilerServices;

namespace Tunnel
{
    public class Ringlogger
    {
        private struct UnixTimestamp
        {
            private Int64 _ns;
            public UnixTimestamp(Int64 ns) => _ns = ns;
            public bool IsEmpty => _ns == 0;
            public static UnixTimestamp Empty => new UnixTimestamp(0);
            public static UnixTimestamp Now
            {
                get
                {
                    var now = DateTimeOffset.UtcNow;
                    var ns = (now.Subtract(DateTimeOffset.FromUnixTimeSeconds(0)).Ticks * 100) % 1000000000;
                    return new UnixTimestamp(now.ToUnixTimeSeconds() * 1000000000 + ns);
                }
            }
            public Int64 Nanoseconds => _ns;
            public override string ToString()
            {
                return DateTimeOffset.FromUnixTimeSeconds(_ns / 1000000000).LocalDateTime.ToString("yyyy'-'MM'-'dd HH':'mm':'ss'.'") + ((_ns % 1000000000).ToString() + "00000").Substring(0, 6);
            }
        }
        private struct Line
        {
            private const int maxLineLength = 512;
            private const int offsetTimeNs = 0;
            private const int offsetLine = 8;

            private readonly MemoryMappedViewAccessor _view;
            private readonly int _start;
            public Line(MemoryMappedViewAccessor view, UInt32 index) => (_view, _start) = (view, (int)(Log.HeaderBytes + index * Bytes));

            public static int Bytes => maxLineLength + offsetLine;

            public UnixTimestamp Timestamp
            {
                get => new UnixTimestamp(_view.ReadInt64(_start + offsetTimeNs));
                set => _view.Write(_start + offsetTimeNs, value.Nanoseconds);
            }

            public string Text
            {
                get
                {
                    var textBytes = new byte[maxLineLength];
                    _view.ReadArray(_start + offsetLine, textBytes, 0, textBytes.Length);
                    var nullByte = Array.IndexOf<byte>(textBytes, 0);
                    if (nullByte <= 0)
                        return null;
                    return Encoding.UTF8.GetString(textBytes, 0, nullByte);
                }
                set
                {
                    if (value == null)
                    {
                        _view.WriteArray(_start + offsetLine, new byte[maxLineLength], 0, maxLineLength);
                        return;
                    }
                    var textBytes = Encoding.UTF8.GetBytes(value);
                    var bytesToWrite = Math.Min(maxLineLength - 1, textBytes.Length);
                    _view.Write(_start + offsetLine + bytesToWrite, (byte)0);
                    _view.WriteArray(_start + offsetLine, textBytes, 0, bytesToWrite);
                }
            }

            public override string ToString()
            {
                var time = Timestamp;
                if (time.IsEmpty)
                    return null;
                var text = Text;
                if (text == null)
                    return null;
                return string.Format("{0}: {1}", time, text);
            }
        }
        private struct Log
        {
            private const UInt32 maxLines = 2048;
            private const UInt32 magic = 0xbadbabe;
            private const int offsetMagic = 0;
            private const int offsetNextIndex = 4;
            private const int offsetLines = 8;

            private readonly MemoryMappedViewAccessor _view;
            public Log(MemoryMappedViewAccessor view) => _view = view;

            public static int HeaderBytes => offsetLines;
            public static int Bytes => (int)(HeaderBytes + Line.Bytes * maxLines);

            public UInt32 ExpectedMagic => magic;
            public UInt32 Magic
            {
                get => _view.ReadUInt32(offsetMagic);
                set => _view.Write(offsetMagic, value);
            }

            public UInt32 NextIndex
            {
                get => _view.ReadUInt32(offsetNextIndex);
                set => _view.Write(offsetNextIndex, value);
            }
            public unsafe UInt32 InsertNextIndex()
            {
                byte* pointer = null;
                _view.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);
                var ret = (UInt32)Interlocked.Increment(ref Unsafe.AsRef<Int32>(pointer + offsetNextIndex));
                _view.SafeMemoryMappedViewHandle.ReleasePointer();
                return ret;
            }

            public UInt32 LineCount => maxLines;
            public Line this[UInt32 i] => new Line(_view, i % maxLines);

            public void Clear() => _view.WriteArray(0, new byte[Bytes], 0, Bytes);
        }

        private readonly Log _log;
        private readonly string _tag;

        public Ringlogger(string filename, string tag)
        {
            var file = File.Open(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete);
            file.SetLength(Log.Bytes);
            var mmap = MemoryMappedFile.CreateFromFile(file, null, 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
            var view = mmap.CreateViewAccessor(0, Log.Bytes, MemoryMappedFileAccess.ReadWrite);
            _log = new Log(view);
            if (_log.Magic != _log.ExpectedMagic)
            {
                _log.Clear();
                _log.Magic = _log.ExpectedMagic;
            }
            _tag = tag;
        }

        public void Write(string line)
        {
            var time = UnixTimestamp.Now;
            var entry = _log[_log.InsertNextIndex() - 1];
            entry.Timestamp = UnixTimestamp.Empty;
            entry.Text = null;
            entry.Text = string.Format("[{0}] {1}", _tag, line.Trim());
            entry.Timestamp = time;
        }

        public void WriteTo(TextWriter writer)
        {
            var start = _log.NextIndex;
            for (UInt32 i = 0; i < _log.LineCount; ++i)
            {
                var entry = _log[i + start];
                if (entry.Timestamp.IsEmpty)
                    continue;
                var text = entry.ToString();
                if (text == null)
                    continue;
                writer.WriteLine(text);
            }
        }

        public static readonly UInt32 CursorAll = UInt32.MaxValue;
        public List<string> FollowFromCursor(ref UInt32 cursor)
        {
            var lines = new List<string>((int)_log.LineCount);
            var i = cursor;
            var all = cursor == CursorAll;
            if (all)
                i = _log.NextIndex;
            for (UInt32 l = 0; l < _log.LineCount; ++l, ++i)
            {
                if (!all && i % _log.LineCount == _log.NextIndex % _log.LineCount)
                    break;
                var entry = _log[i];
                if (entry.Timestamp.IsEmpty)
                {
                    if (all)
                        continue;
                    break;
                }
                cursor = (i + 1) % _log.LineCount;
                var text = entry.ToString();
                if (text == null)
                    continue;
                lines.Add(text);
            }
            return lines;
        }
    }
}