File: fgbzip2.cpp

package info (click to toggle)
onetbb 2022.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 19,440 kB
  • sloc: cpp: 129,228; ansic: 9,745; python: 808; xml: 183; objc: 176; makefile: 66; sh: 66; awk: 41; javascript: 37
file content (366 lines) | stat: -rw-r--r-- 12,585 bytes parent folder | download | duplicates (6)
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/*
    Copyright (c) 2005-2021 Intel Corporation

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

#include <iostream>
#include <fstream>
#include <string>
#include <memory>
#include <queue>
#include <thread>

#include "bzlib.hpp"

#include "common/utility/utility.hpp"

#include "oneapi/tbb/flow_graph.h"
#include "oneapi/tbb/tick_count.h"
#include "oneapi/tbb/concurrent_queue.h"

// TODO: change memory allocation/deallocation to be managed in constructor/destructor
struct Buffer {
    std::size_t len;
    char* b;
};

struct BufferMsg {
    BufferMsg() {}
    BufferMsg(Buffer& inputBuffer, Buffer& outputBuffer, std::size_t seqId, bool isLast = false)
            : inputBuffer(inputBuffer),
              outputBuffer(outputBuffer),
              seqId(seqId),
              isLast(isLast) {}

    static BufferMsg createBufferMsg(std::size_t seqId, std::size_t chunkSize) {
        Buffer inputBuffer;
        inputBuffer.b = new char[chunkSize];
        inputBuffer.len = chunkSize;

        Buffer outputBuffer;
        std::size_t compressedChunkSize = chunkSize * 1.01 + 600; // compression overhead
        outputBuffer.b = new char[compressedChunkSize];
        outputBuffer.len = compressedChunkSize;

        return BufferMsg(inputBuffer, outputBuffer, seqId);
    }

    static void destroyBufferMsg(const BufferMsg& destroyMsg) {
        delete[] destroyMsg.inputBuffer.b;
        delete[] destroyMsg.outputBuffer.b;
    }

    void markLast(std::size_t lastId) {
        isLast = true;
        seqId = lastId;
    }

    std::size_t seqId;
    Buffer inputBuffer;
    Buffer outputBuffer;
    bool isLast;
};

class BufferCompressor {
public:
    BufferCompressor(int blockSizeIn100KB) : m_blockSize(blockSizeIn100KB) {}

    BufferMsg operator()(BufferMsg buffer) const {
        if (!buffer.isLast) {
            unsigned int outSize = buffer.outputBuffer.len;
            BZ2_bzBuffToBuffCompress(buffer.outputBuffer.b,
                                     &outSize,
                                     buffer.inputBuffer.b,
                                     buffer.inputBuffer.len,
                                     m_blockSize,
                                     0,
                                     30);
            buffer.outputBuffer.len = outSize;
        }
        return buffer;
    }

private:
    int m_blockSize;
};

class IOOperations {
public:
    IOOperations(std::ifstream& inputStream, std::ofstream& outputStream, std::size_t chunkSize)
            : m_inputStream(inputStream),
              m_outputStream(outputStream),
              m_chunkSize(chunkSize),
              m_chunksRead(0) {}

    void readChunk(Buffer& buffer) {
        m_inputStream.read(buffer.b, m_chunkSize);
        buffer.len = static_cast<std::size_t>(m_inputStream.gcount());
        m_chunksRead++;
    }

    void writeChunk(const Buffer& buffer) {
        m_outputStream.write(buffer.b, buffer.len);
    }

    std::size_t chunksRead() const {
        return m_chunksRead;
    }

    std::size_t chunkSize() const {
        return m_chunkSize;
    }

    bool hasDataToRead() const {
        return m_inputStream.is_open() && !m_inputStream.eof();
    }

private:
    std::ifstream& m_inputStream;
    std::ofstream& m_outputStream;

    std::size_t m_chunkSize;
    std::size_t m_chunksRead;
};

//-----------------------------------------------------------------------------------------------------------------------
//---------------------------------------Compression example based on async_node-----------------------------------------
//-----------------------------------------------------------------------------------------------------------------------

typedef oneapi::tbb::flow::async_node<oneapi::tbb::flow::continue_msg, BufferMsg>
    async_file_reader_node;
typedef oneapi::tbb::flow::async_node<BufferMsg, oneapi::tbb::flow::continue_msg>
    async_file_writer_node;

class AsyncNodeActivity {
public:
    AsyncNodeActivity(IOOperations& io)
            : m_io(io),
              m_fileWriterThread(&AsyncNodeActivity::writingLoop, this) {}

    ~AsyncNodeActivity() {
        m_fileReaderThread.join();
        m_fileWriterThread.join();
    }

    void submitRead(async_file_reader_node::gateway_type& gateway) {
        gateway.reserve_wait();
        std::thread(&AsyncNodeActivity::readingLoop, this, std::ref(gateway))
            .swap(m_fileReaderThread);
    }

    void submitWrite(const BufferMsg& bufferMsg) {
        m_writeQueue.push(bufferMsg);
    }

private:
    void readingLoop(async_file_reader_node::gateway_type& gateway) {
        while (m_io.hasDataToRead()) {
            BufferMsg bufferMsg = BufferMsg::createBufferMsg(m_io.chunksRead(), m_io.chunkSize());
            m_io.readChunk(bufferMsg.inputBuffer);
            gateway.try_put(bufferMsg);
        }
        sendLastMessage(gateway);
        gateway.release_wait();
    }

    void writingLoop() {
        BufferMsg buffer;
        m_writeQueue.pop(buffer);
        while (!buffer.isLast) {
            m_io.writeChunk(buffer.outputBuffer);
            m_writeQueue.pop(buffer);
        }
    }

    void sendLastMessage(async_file_reader_node::gateway_type& gateway) {
        BufferMsg lastMsg;
        lastMsg.markLast(m_io.chunksRead());
        gateway.try_put(lastMsg);
    }

    IOOperations& m_io;

    oneapi::tbb::concurrent_bounded_queue<BufferMsg> m_writeQueue;

    std::thread m_fileReaderThread;
    std::thread m_fileWriterThread;
};

void fgCompressionAsyncNode(IOOperations& io, int blockSizeIn100KB) {
    oneapi::tbb::flow::graph g;

    AsyncNodeActivity asyncNodeActivity(io);

    async_file_reader_node file_reader(
        g,
        oneapi::tbb::flow::unlimited,
        [&asyncNodeActivity](const oneapi::tbb::flow::continue_msg& msg,
                             async_file_reader_node::gateway_type& gateway) {
            asyncNodeActivity.submitRead(gateway);
        });

    oneapi::tbb::flow::function_node<BufferMsg, BufferMsg> compressor(
        g, oneapi::tbb::flow::unlimited, BufferCompressor(blockSizeIn100KB));

    oneapi::tbb::flow::sequencer_node<BufferMsg> ordering(g,
                                                          [](const BufferMsg& bufferMsg) -> size_t {
                                                              return bufferMsg.seqId;
                                                          });

    // The node is serial to preserve the right order of buffers set by the preceding sequencer_node
    async_file_writer_node output_writer(
        g,
        oneapi::tbb::flow::serial,
        [&asyncNodeActivity](const BufferMsg& bufferMsg,
                             async_file_writer_node::gateway_type& gateway) {
            asyncNodeActivity.submitWrite(bufferMsg);
        });

    make_edge(file_reader, compressor);
    make_edge(compressor, ordering);
    make_edge(ordering, output_writer);

    file_reader.try_put(oneapi::tbb::flow::continue_msg());

    g.wait_for_all();
}

//-----------------------------------------------------------------------------------------------------------------------
//---------------------------------------------Simple compression example------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------

void fgCompression(IOOperations& io, int blockSizeIn100KB) {
    oneapi::tbb::flow::graph g;

    oneapi::tbb::flow::input_node<BufferMsg> file_reader(
        g, [&io](oneapi::tbb::flow_control& fc) -> BufferMsg {
            if (io.hasDataToRead()) {
                BufferMsg bufferMsg = BufferMsg::createBufferMsg(io.chunksRead(), io.chunkSize());
                io.readChunk(bufferMsg.inputBuffer);
                return bufferMsg;
            }
            fc.stop();
            return BufferMsg{};
        });
    file_reader.activate();

    oneapi::tbb::flow::function_node<BufferMsg, BufferMsg> compressor(
        g, oneapi::tbb::flow::unlimited, BufferCompressor(blockSizeIn100KB));

    oneapi::tbb::flow::sequencer_node<BufferMsg> ordering(g, [](const BufferMsg& buffer) -> size_t {
        return buffer.seqId;
    });

    oneapi::tbb::flow::function_node<BufferMsg> output_writer(
        g, oneapi::tbb::flow::serial, [&io](const BufferMsg& bufferMsg) {
            io.writeChunk(bufferMsg.outputBuffer);
            BufferMsg::destroyBufferMsg(bufferMsg);
        });

    make_edge(file_reader, compressor);
    make_edge(compressor, ordering);
    make_edge(ordering, output_writer);

    g.wait_for_all();
}

//-----------------------------------------------------------------------------------------------------------------------

bool endsWith(const std::string& str, const std::string& suffix) {
    return str.find(suffix, str.length() - suffix.length()) != std::string::npos;
}

//-----------------------------------------------------------------------------------------------------------------------

int main(int argc, char* argv[]) {
    oneapi::tbb::tick_count mainStartTime = oneapi::tbb::tick_count::now();

    const std::string archiveExtension = ".bz2";
    bool verbose = false;
    bool asyncType;
    std::string inputFileName;
    int blockSizeIn100KB = 1; // block size in 100KB chunks
    std::size_t memoryLimitIn1MB = 1; // memory limit for compression in megabytes granularity

    utility::parse_cli_arguments(
        argc,
        argv,
        utility::cli_argument_pack()
            //"-h" option for displaying help is present implicitly
            .arg(blockSizeIn100KB, "-b", "\t block size in 100KB chunks, [1 .. 9]")
            .arg(verbose, "-v", "verbose mode")
            .arg(memoryLimitIn1MB,
                 "-l",
                 "used memory limit for compression algorithm in 1MB (minimum) granularity")
            .arg(asyncType, "-async", "use graph async_node-based implementation")
            .positional_arg(inputFileName, "filename", "input file name"));

    if (inputFileName.empty()) {
        throw std::invalid_argument(
            "Input file name is not specified. Try 'fgbzip2 -h' for more information.");
    }

    if (blockSizeIn100KB < 1 || blockSizeIn100KB > 9) {
        throw std::invalid_argument("Incorrect block size. Try 'fgbzip2 -h' for more information.");
    }

    if (memoryLimitIn1MB < 1) {
        throw std::invalid_argument(
            "Incorrect memory limit size. Try 'fgbzip2 -h' for more information.");
    }

    if (verbose)
        std::cout << "Input file name: " << inputFileName << "\n";
    if (endsWith(inputFileName, archiveExtension)) {
        throw std::invalid_argument("Input file already have " + archiveExtension + " extension.");
    }

    std::ifstream inputStream(inputFileName.c_str(), std::ios::in | std::ios::binary);
    if (!inputStream.is_open()) {
        throw std::invalid_argument("Cannot open " + inputFileName + " file.");
    }

    std::string outputFileName(inputFileName + archiveExtension);

    std::ofstream outputStream(outputFileName.c_str(),
                               std::ios::out | std::ios::binary | std::ios::trunc);
    if (!outputStream.is_open()) {
        throw std::invalid_argument("Cannot open " + outputFileName + " file.");
    }

    // General interface to work with I/O buffers operations
    std::size_t chunkSize = blockSizeIn100KB * 100 * 1024;
    IOOperations io(inputStream, outputStream, chunkSize);

    if (asyncType) {
        if (verbose)
            std::cout
                << "Running flow graph based compression algorithm with async_node based asynchronous IO operations."
                << "\n";
        fgCompressionAsyncNode(io, blockSizeIn100KB);
    }
    else {
        if (verbose)
            std::cout << "Running flow graph based compression algorithm."
                      << "\n";
        fgCompression(io, blockSizeIn100KB);
    }

    inputStream.close();
    outputStream.close();

    utility::report_elapsed_time((oneapi::tbb::tick_count::now() - mainStartTime).seconds());

    return 0;
}