Lessons learend (from failuere) while I developing a log server for Windows

Wrote this post in Jan 2015 as a quick draft, and remained as it is still today. I thought it’s not that useful so tried to delete it, but changed mind and released here. Hope it helps.

Recently I developed a logging server based on C#/asp.net on Windows 2008 R2 server. The server primarily does receiving log files from clients and write into database and also drop files to that server. After I released it to production, I met some unexpected issues.

1. Huge(99.9%) memory consumption issue

The logging server writes huge excessive IO to the disk and it instantly caused the os SYSTEM process to consume almost all physical memories. I searched online and analyzed it through the Sysinternals’ RAMMap. It turns out the OS’s system cache takes all the memories. You can find out details from following links:

http://www.microsoft.com/en-us/download/details.aspx?id=9258 Windows Dynamic Cache Service

Sysinternals http://technet.microsoft.com/en-us/sysinternals/bb897561

KB article http://support.microsoft.com/kb/976618/

[Korean] http://snoopybox.co.kr/1635

Lesson learned: Reduce the file IO as much as you can!

 

http://blogs.msdn.com/b/ntdebugging/archive/2009/02/06/microsoft-windows-dynamic-cache-service.aspx

http://blogs.msdn.com/b/ntdebugging/archive/2007/11/27/too-much-cache.aspx

 

2. MongoDB

  • Don’t forget to use the indexing
  • You can figure it out whether it uses the index or not by using ‘Explain’

 

3. Deleting files from disk will take longer than you expect

  • My initial design approach was complete wrong and failure. The server used to drop huge number of files into the physical disk, and just deleting the very small portion of files required actually even hours.

Lesson learned: Does your server collect a number of files? Store it into the database directly.

Thanks,

Heejune

Beginning the coroutine with Visual Studio 2015 Update 3 Part 2

As we discussed through Part I, co_wait keyword requires sort of “resumable thing”. So what if we want to use co_await with time delta?

For example, you can see the code which the co_await takes std::chrono::duration in order to suspend for the specified time from here: https://github.com/Microsoft/cppwinrt/blob/master/10.0.14393.0/Samples/JustCoroutines/Main.cpp#L31

The answer is the fact that vc++ compiler allows co_await to be overloaded. So, we can overload the co_await keyword and returns the “resumable thing” within the overloading implementation.

See the code here. https://github.com/Microsoft/cppwinrt/blob/master/10.0.14393.0/winrt/base.h#L8897

If you follow the resume_after(), then you’ll clearly see it actually returns the instance of resumable thing struct which contain implementations of await_ready, await_suspend, and await_resume.

https://github.com/Microsoft/cppwinrt/blob/master/10.0.14393.0/winrt/base.h#L8643

Let’s test with another test sample here. https://github.com/heejune/wrl-cppwinrt-sample/blob/async-support/SampleLib.Shared/DemoCore.cpp#L81

In this sample, I called the winrt’s co_await as the above sample illustrated.

And if I step into the co_await… we hit the overloaded co_await.

part_ii_1

Step in again, then finally it creates resume_after struct instance and calls the await_suspend.

part_ii_2

part_ii_3

It spawns timer thread with specified time, and finally resume_after::callback static callback is being called.

part_ii_3-4png

The callback will finally call resume().

part_ii_4

And the resume() transfers its context into where the co_await being called.

part_ii_5

And lastly, the coroutine function hits the co_return keyword after looping 5 times,

part_ii_6

And reached the end.

Next time, I’d like to talk about another co_await adapter ‘await_adapter’ which makes winrt IAsync.. types possible to be awaitable. Thanks.

Heejune

How to upload a file from slack using SlackClient?

Slack provides an official python client module which you can easily work with.

It’s simple and easy to use. For example, sending a text line to a specific channel is simple enough to call through just one API – api_call(chat.postMessage, channel=channel, text=msg, attachments=attachment, as_user=True)

You can also upload a file to a channel. However, when I was searching some info how to achieve that at the first time, the answer described in the SlackClient’s Github issue was actually wrong. So I tested and added a snippet. Please check the issue page.

Anyway, I also shared the snippet at the public gist. The ‘upload_file’ method takes a long text as the ‘content’ param and upload it as a file. You’ll also upload a file directory from disk or memory if you modify it slightly.

Thanks,

Heejune

Building WinRT component with WRL(non C++/CX) and cppwinrt

The cppwinrt project focused to consume Microsoft provided OS winrt components and it doesn’t support building a winrt component(yet) although they mentioned it will be supported later.

Even though it’s not technically supported yet, we still can create a winrt component with WRL(pure C++ and non C++/CX) and still can get some benefits from using cppwinrt within WRL component.

For example, I created a WinRT sample component with WRL and exports IAsyncAction async methods from it. Inside the method, I utilized the cppwinrt provided coroutine method which easily can produce IAsync operations. See the following:

https://github.com/heejune/wrl-cppwinrt-sample/blob/async-support/SampleLib.Shared/DemoCore.cpp

There’s a DemoCore::GetCppwinrtDataasync method defined as this:

It just (detached and) returns the object which also returned from GetAsyncOp private method. GetAsyncOp is a coroutine function which also creates an instance of winrt::Windows::Foundation::IAsyncOperation. And that’s the winrt implementation of IAsyncOperation.

You can download the source project and test it from https://github.com/heejune/wrl-cppwinrt-sample/tree/async-support

Thanks,

Heejune

Beginning the coroutine with Visual Studio 2015 Update 3 Part 1

I recently started using the cppwinrt library which brought chances dealing with the new C++ standard(yet) coroutine. The cppwinrt recommends using C++ coroutines instead of PPL while handling async operations. Refer to the following github issues for more information:

https://github.com/Microsoft/cppwinrt/issues/54

https://github.com/Microsoft/cppwinrt/issues/46

Although the coroutine concept itself might feel coming familiar because we’re already exposed async programming concept much from python asyncio, C# async/await experiences, however the C++ coroutine requires few prerequisite concepts, predefined structures and functions just in order to begin with. I had absolute no idea those, so I decided to start digging in to understand how things orchestrate and work under the hood.

Fortunately, James McNellis from the Microsoft VC++ team had an introductory talk “Introduction to C++ Coroutines” from the cppcon 2016. The talk is great. You really should watch it first if you want to learn the C++ coroutine. However, it feels like a little ambiguous. So that I decided to write actual codes what he had shown from his slides and test it.

So at the very beginning, I created the simplest C++ console project from the Visual Studio 2015 Update 3.

First, changed the warning level,

Typed the simple awaitable function shown from the slide and tried build it.

 

And of course the compiler failed to build and showed the following error:

 

1>—— Build started: Project: resumable-concept, Configuration: Debug x64 ——

1> Skipping… (no relevant changes detected)

1> stdafx.cpp

1> resumable-concept.cpp

1>d:\workspace\playground\async_research\resumable-idea\resumable-idea\resumable-concept.cpp(10): error C3773: please use /await compiler switch to enable coroutines

1>d:\workspace\playground\async_research\resumable-idea\resumable-idea\resumable-concept.cpp(13): error C3774: cannot find ‘std::experimental’: Please include <experimental/resumable> header

1>d:\workspace\playground\async_research\resumable-idea\resumable-idea\resumable-concept.cpp(15): error C3773: please use /await compiler switch to enable coroutines

1>d:\workspace\playground\async_research\resumable-idea\resumable-idea\resumable-concept.cpp(20): error C2228: left of ‘.get’ must have class/struct/union

========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

 

So I added the /await option as the error indicated:

Also included required header files at stdafx.h:

 

And tried build again…….

Succeeded!

 

1>—— Rebuild All started: Project: resumable-concept, Configuration: Debug x64 ——

1> stdafx.cpp

1> resumable-concept.cpp

1> resumable-idea.vcxproj -> D:\workspace\playground\async_research\resumable-idea\x64\Debug\resumable-concept.exe

1> resumable-idea.vcxproj -> D:\workspace\playground\async_research\resumable-idea\x64\Debug\resumable-concept.pdb (Full PDB)

========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

Let’s see what the co_await actually does in detail:

From the cppcon talk,

He explains that if we use the co_await keyword, the compiler will generate the code shown on the right. Which means in order to work with the co_await keyword, someone should provide the required functions such as await_ready, await_suspend, await_resume, so from the next page it introduces the ‘awaitable_concept’ structure which has the all functions mentioned.

For example, we used the std::future from the first sample, and you’ll see the following snippets if you open the future std header file and search ‘await_ready’ string.

 

If so, how can you make your own type to awaitable to work with co_await instead of using std::future?

From the cppcon talk, James explains it type named ‘resumable_thing’.

Let’s type exactly same code he’d shown us and try build it. I added the ‘resume()’ class method which is not listed from the slide but to work. This is to see what functions exactly required to be implemented to work with co_await keyword.

 

You’ll get following errors when you build the example:

 

1>—— Build started: Project: resumable-concept, Configuration: Debug x64 ——

1> resumable-concept.cpp

1>d:\devtools\vs14\vc\include\experimental\resumable(44): error C2039: ‘promise_type’: is not a member of ‘resumable_thing’

1> d:\workspace\playground\async_research\resumable-idea\resumable-idea\resumable-concept.cpp(9): note: see declaration of ‘resumable_thing’

1> d:\workspace\playground\async_research\resumable-idea\resumable-idea\resumable-concept.cpp(17): note: see reference to class template instantiation ‘std::experimental::coroutine_traits<resumable_thing>’ being compiled

1>d:\devtools\vs14\vc\include\experimental\resumable(44): error C2061: syntax error: identifier ‘promise_type’

1>d:\devtools\vs14\vc\include\experimental\resumable(44): error C2238: unexpected token(s) preceding ‘;’

1>d:\workspace\playground\async_research\resumable-idea\resumable-idea\resumable-concept.cpp(25): error C2440: ‘initializing’: cannot convert from ‘resumable_thing (__cdecl *)(void)’ to ‘resumable_thing’

1> d:\workspace\playground\async_research\resumable-idea\resumable-idea\resumable-concept.cpp(25): note: No constructor could take the source type, or constructor overload resolution was ambiguous

========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Double clicked the first error line to move to exact error location,

1>d:\devtools\vs14\vc\include\experimental\resumable(44): error C2039: ‘promise_type’: is not a member of ‘resumable_thing’

namespace experimental {

    // TEMPLATE CLASS coroutine_traits

    template <typename
_Ret, typename_Ts>

    struct
coroutine_traits

    {

        using
promise_type = typename
_Ret::promise_type;

    };

As you see, the compiler failed to template instantiate coroutine_traits<resumable_thing> because the promise_type is not declared from resumable_thing.

If so, let’s fill up the remaining method implementations as the slide shows:

 

Finally works as expected:

If so, what exactly happening from the ‘counter’ coroutine function returns resumable_thing? From the talk, the slide shows the following pseudo code:

If you’re stepping into the assembly code while debugging, you’ll see similar functions are actually implemented:

First of all, it starts its async operation by calling the ‘InitCoro$1’. If you stepped into the inside ‘InitCoro$1’ function, you’ll see the function implements prologue what the next image suggests as the first three lines:

00B12A41 call std::experimental::_Resumable_helper_traits<resumable_thing>::_ConstructPromise (0B1132Ah)

00B12A46 add esp,0Ch

00B12A49 mov byte ptr [ebp-4],1

00B12A4D lea eax,[ebp-0D1h]

00B12A53 push eax

00B12A54 mov ecx,dword ptr [<coro_frame_ptr>]

00B12A57 push ecx

00B12A58 call std::experimental::_Resumable_helper_traits<resumable_thing>::_Promise_from_frame (0B11217h)

00B12A5D add esp,4

00B12A60 mov ecx,eax

00B12A62 call resumable_thing::promise_type::initial_suspend (0B111EFh)

00B12A67 mov dl,byte ptr [eax]

00B12A69 movzx eax,dl

00B12A6C push eax

00B12A6D mov ecx,80h

00B12A72 add ecx,dword ptr [<coro_frame_ptr>]

00B12A75 call `counter’::`5′::<parameters>::<parameters> (0B11FC0h)

00B12A7A mov eax,dword ptr [__$ReturnUdt]

00B12A7D push eax

00B12A7E mov ecx,dword ptr [<coro_frame_ptr>]

00B12A81 push ecx

00B12A82 call std::experimental::_Resumable_helper_traits<resumable_thing>::_Promise_from_frame (0B11217h)

00B12A87 add esp,4

00B12A8A mov ecx,eax

00B12A8C call resumable_thing::promise_type::get_return_object (0B11479h)

00B12A91 mov dword ptr [ebp-4],2

00B12A98 mov ecx,80h

00B12A9D add ecx,dword ptr [<coro_frame_ptr>]

00B12AA0 call std::experimental::suspend_never::await_ready (0B11348h)

00B12AA5 movzx eax,al

00B12AA8 test eax,eax

00B12AAA je counter$_InitCoro$1+0CAh (0B12ABAh)

00B12AAC mov ecx,dword ptr [<coro_frame_ptr>]

00B12AAF push ecx

00B12AB0 call counter$_ResumeCoro$2 (0B12B70h)

00B12AB5 add esp,4

00B12AB8 jmp counter$_InitCoro$1+103h (0B12AF3h)

}

It first creates the Promise instance:

00B12A41 call std::experimental::_Resumable_helper_traits<resumable_thing>::_ConstructPromise (0B1132Ah)

The function creates it by calling the std::experimental::_Resumable_helper_traits<resumable_thing>::_ConstructPromise(void *, void *, int) function which is implemented at “\VC\include\experimental\resumable”

If you open the file and see the code,

        static
void _ConstructPromise(void *_Addr, void *_Resume_addr, int
_HeapElision)

        {

            *reinterpret_cast<void **>(_Addr) = _Resume_addr;

            *reinterpret_cast<uint32_t *>(reinterpret_cast<uintptr_t>(_Addr) +

                                         sizeof(void *)) = 2 + (_HeapElision ? 0 : 0x10000);

            auto _Prom = _Promise_from_frame(_Addr);

            ::new (static_cast<void *>(_Prom)) _PromiseT();

        }

It instantiates the promise_type which is defined within resumable_thing from our example. After instantiated, initial_suspend() will be executed as the deck explained.

As a next step, resumable_thing::promise_type::get_return_object() will be called. The resumable_thing instance is getting created from this get_return_object().

The prologue pseudo code explained that _promise.initial_suspend() will be called as a next step, and from the our example, the resumable_thing::promise_type::initial_suspend() returns suspend_never{}. So suspend_never::await_ready is getting called as next.

Finally, if we step into the function counter$_ResumeCoro$2(void) which is below:

There exists actual counter() function implementation if we stepped into resumeCoro. Later when the the_counter.resume() ran, Instruction Pointer is transferred same as if the resumeCoro ran.

Next time, let’s see how the cppwinrt overloads co_await operator and utilize it.

Part II

[C++/Cx] How can I get the AsyncOperationWithProgress progress?

Windows Runtime provides the HttpClient class along with async APIs. For example, you can send a GET request through the GetAsync(Uri) method.

GetAsync() method is an awaitable API so that it returns IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress>^. You will get the HttpResponseMessage by specifying the IAsyncOperationWithProgress to Concurrency::create_task(). However, how can I get the progress?

There’s no direct answer from MSDN but gives a hint here:

You just supply the delegate for the object’s Progress property

Here’s the snippet:

Generating assembly output from msvc and CMake

Sometimes it’s needed or you may require to see the assembly output listing of a C++ snippet code just for the testing purpose. Testing yourself with Jason Turner’s session might be the example.

If you’re using a msvc with Windows environment, then it’s quite easy by running the simple command line argument:

Let’s say we have an optimizaing.cpp as following:

#include <string>

int main()

{

    std::string s(“a”);

    return s.size();

}

Launch the build environment and run the cl.exe with a ‘/FA’ parameter.


cl /EHsc /nologo /W4  optimizing.cpp /FAs /GL /O2


CMake also automatically adds the target generating assembly output and it’ll be also a good choice when you’re not using msvc.

Let’s say if we have the following CMakeLists.txt,

project(demo)

cmake_minimum_required(VERSION 3.1)

#—————————————————-

# Flags

#—————————————————-

set(CMAKE_CXX_STANDARD 14)

add_definitions(-DCMAKE_EXPORT_COMPILE_COMMANDS=1)

#—————————————————-

# Executable

#—————————————————-

add_executable(optimizing “optimizing.cpp”)


You can generate the build files. I use theMinGWw g++ toolchain here.

cmake -G “MinGW Makefiles” -DCMAKE_BUILD_TYPE=RELEASE ..


Then you’ll see the target.s for the assembly output. For example, the generated Makefile contains ‘optimizing.s’ here.


You’ll finally get the assembly output listing by running make target.s as below:


 

Thanks,

Heejune