-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConsumer.cs
249 lines (230 loc) · 7.67 KB
/
Consumer.cs
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Confluent.Kafka;
using System.Collections.ObjectModel;
using System.Windows;
using NLog;
namespace KafkaSniffer
{
internal class Consumer : BrokerInfo
{
private string _messageLog = "";
private readonly List<string> _messageLogs = new List<string>();
private string _topic = "", _groupId = "";
private bool _notSubscribe = true;
private int _count = 0;
private int _consumerCnt = 0;
private StreamWriter _logFile = null;
private bool _firstAssigned = true;
private Task _pollTask = null;
private CancellationTokenSource _cancelConsumer = null;
private static Logger Logger = LogManager.GetLogger("consumer");
public string CurOffsetType { get; set; } = "Stored Offset";
public ObservableCollection<string> OffsetTypeList { get; } = new ObservableCollection<string> { "Beginning", "End", "Stored Offset" };
~Consumer()
{
Close();
}
public string Topic
{
get { return _topic; }
set
{
_topic = value;
OnPropertyChanged("Topic");
}
}
public string GroupId
{
get { return _groupId; }
set
{
_groupId = value;
OnPropertyChanged("GroupId");
}
}
public int Count
{
get { return _count; }
set
{
_count = value;
OnPropertyChanged("Count");
}
}
public string MessageLog
{
get { return _messageLog; }
private set
{
_messageLog = value;
OnPropertyChanged("MessageLog");
}
}
public bool NotSubscribe
{
get
{
return _notSubscribe;
}
set
{
_notSubscribe = value;
OnPropertyChanged("NotSubscribe");
}
}
public bool IsLogToFile { get; set; } = false;
public void ClearMessageLog()
{
_messageLogs.Clear();
MessageLog = "";
}
public async void Close()
{
_cancelConsumer?.Cancel();
if (!NotSubscribe && _pollTask != null)
{
await _pollTask;
}
}
public void SubScribe()
{
_cancelConsumer = new CancellationTokenSource();
_consumerCnt = 0;
var brokerList = Endpoint;
var config = new ConsumerConfig
{
BootstrapServers = brokerList,
GroupId = _groupId,
ApiVersionRequest = true,
EnableAutoCommit = true,
};
if (Debug)
{
config.Debug = "msg,broker,topic,protocol";
}
var consumer = new ConsumerBuilder<string, string>(config)
.SetLogHandler((_, msg) =>
{
Logger.Log(MapLogLevel(msg.Level), msg.Message);
})
.SetPartitionsAssignedHandler((c, partitions) =>
{
var parFiltered = partitions.Where(_ => _.Topic == Topic).ToList();
var ret = new List<TopicPartitionOffset>();
if (!parFiltered.Any())
{
_messageLogs.Add($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} WARNING!!! empty partition filtered?\n\n");
}
else if (!_firstAssigned)
{
ret = parFiltered.Select(p => new TopicPartitionOffset(p.Topic, p.Partition, Confluent.Kafka.Offset.Unset)).ToList();
}
else if (CurOffsetType == "Beginning")
{
ret = parFiltered.Select(p => new TopicPartitionOffset(p.Topic, p.Partition, Confluent.Kafka.Offset.Beginning)).ToList(); ;
}
else if (CurOffsetType == "End")
{
ret = parFiltered.Select(p => new TopicPartitionOffset(p.Topic, p.Partition, Confluent.Kafka.Offset.End)).ToList(); ;
}
else
{
ret = parFiltered.Select(p => new TopicPartitionOffset(p.Topic, p.Partition, Confluent.Kafka.Offset.Unset)).ToList();
}
var assignedInfo = "";
ret.ForEach(offset =>
{
assignedInfo +=
$"(Topic: {offset.Topic}, Partition: {offset.Partition}, Offset: {offset.Offset})";
});
_messageLogs.Add($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} partitions assigned. [{assignedInfo}]\n\n");
RefreshMessageLog();
_firstAssigned = false;
return ret;
}).Build();
consumer.Subscribe(Topic);
_messageLogs.Add($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} subscribe done.\n\n");
RefreshMessageLog();
_pollTask = Task.Run(() =>
{
try
{
while (true)
{
try
{
var result = consumer.Consume(_cancelConsumer.Token);
if (result.IsPartitionEOF)
{
continue;
}
OnMessage(result);
}
catch (ConsumeException e)
{
MessageBox.Show($"Consume error: {e.Error.Reason}");
}
}
}
catch (OperationCanceledException)
{
consumer.Close();
}
consumer.Dispose();
});
NotSubscribe = false;
}
private void OnMessage(ConsumeResult<string, string> e)
{
if (_count > 0)
{
if (_consumerCnt == _count)
{
_cancelConsumer.Cancel();
Task.Run(() =>
{
NotSubscribe = true;
});
}
_consumerCnt++;
}
var now = DateTime.Now;
var msg = $"{now:yyyy-MM-dd HH:mm:ss} Partition:[{e.Partition}] Offset:[{e.Offset}] Length:[{e.Value.Length}]\n{e.Key}\n{e.Value}\n\n";
_messageLogs.Add(msg);
_logFile?.Write(msg);
if (_messageLogs.Count > 20)
{
_messageLogs.RemoveAt(0);
}
RefreshMessageLog();
}
private void RefreshMessageLog()
{
_messageLog = "";
_messageLogs.ForEach(log =>
{
_messageLog += log;
});
OnPropertyChanged("MessageLog");
}
public void EndLogToFile()
{
if (_logFile != null)
{
_logFile.Close();
_logFile = null;
}
}
public void StartLogToFile(Stream fs)
{
_logFile = new StreamWriter(fs);
}
}
}