StreamWriter and Samba2 (SMB2)

Ok guys, it's hard.

Scenario :

  • I have several services running on multiple machines.
  • Each service has multiple threads, and each thread writes a file to FILER - the shared storage used by my machines (using a shared resource such as \\ filername \ foo \ bar)
  • The FILER machine is a NetApp machine.
  • Both FILER and the machines running the services use SMB2 (http://en.wikipedia.org/wiki/Server_Message_Block).
  • The command used to write the file is simple as described below in [CODE]

[CODE]

using (StreamWriter outfile = new StreamWriter(pathToTheFile, false)) { outfile.Write(stringToWriteInTheFile); } 

[/CODE]

Problem :

Sometimes the service remains “stuck” in this manual. Indicated error:

The process cannot access the file '\\ filername \ foo \ bar \ myfile.txt' because it is being used by another process.

After some of these errors, the service refuses to release the file lock. What happens then?

You can delete the file, but the file is RECREATED IMMEDIATELY. For example, if some constant stream is alive and continues to write the file unlimitedly.

You can stop the service: it is stuck and will not be stopped, so I forced Thread.Abort (yes, I know, but practice, but what else?) After 2 minutes.

So, the service is now stopped, but the machine saves the file descriptor, and you CANNOT kill the process by storing the descriptor, except by restarting the computer.,.

I don’t know what to do right now, I think I tried everything.

Questions

Previously, FILER and machines used SMB1, and this problem did not occur. So I think something suspicious is happening in the background, but I can’t understand that ...

I recently changed the code used to write a file in a desperate attempt to “delegate” everything to .net. Now this:

 File.WriteAllText(pathToTheFile, stringToWriteInTheFile); 

but my gut feeling is that under .net wrappers it does the same thing - this change is quite recent, so I can't tell if the fix works or not.

EDIT (as per Vash comment): Usually a file is different, but it can happen (and it actually happens) that several threads try to write the same file, however :( - executing File.WriteAllText shouldn’t take care of concurrency issues?

+4
source share
1 answer

Try to open FileStream explicitly in "exclusive" mode, i.e.

 using (var fs = new FileStream("path", FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { using (var sw = new StreamWriter(fs)) { ... 

Of course, your code will have to anticipate that the file may be locked when it goes to write and respond accordingly. This part is left as an exercise for the reader :-)

Disclaimer: I used this in a multi-threaded environment, but I can not guarantee that it will work on Samba.

+2
source

Source: https://habr.com/ru/post/1347540/


All Articles