I had one of those dreaded tasks at work today - update a bazillion (okay, actually just 24, but it felt like a lot) servers with a config file that needs to be modified to reference the name of each of the servers. I either had to update each server in turn, or I could write a script to do it for me. I decided to write a script, and I will pretend that it took less time to write and run the script than doing it manually. It wasn't perfect - I had to copy/paste the password for each server because I didn't want to mess around with using keygen. I also didn't want to install software like expect. Expect is a software utility that allows you to write scripts that provide interactive programs with the parameters they might...well...expect. In this case it would have been handy to use since it could provide scp with the user's password. The script I wrote did what I needed it to, and I'm sure I'll be able to use something like this script in the future. Assuming that the source file is on server01, and the source file to be updated and copied is named somefile.conf, then this is what the script looked like:
#!/bin/sh
servers="server02 server03 server04 server05 server06 server07 server08 server09 server10 server11 server12 server13 server14 server15 server16 server17 server18 server19 server20 server21 server22 server23 server24"
filepath="/some/file/path/somefile.conf"
for server in $servers
do
echo "Working on $server."
SEDARG="s/server01/$server/g"
sed $SEDARG $filepath > $filepath.$server
scp $filepath.$server someuser@$server:$filepath
rm $filepath.$server
done
echo "Done."
I am attempting to store a bit of data that I fetch from a website in Solr. The data sometimes has HTML markup, so I decided to use the HTMLStripCharFilterFactory in the fields analyzer. Here is an example of the field type that I created: <fieldType name="strippedHtml" class="solr.TextField"> <analyzer> <charFilter class="solr.HTMLStripCharFilterFactory"/> <tokenizer class="solr.WhitespaceTokenizerFactory"/> <filter class="solr.LowerCaseFilterFactory" /> </analyzer> </fieldType>
I used the field type of strippedHtml in a field called itemDescription, and when I do a search after indexing some data I can see that the itemDescription contains data that still has HTML markup. I used the analyzer tab in Solr to see what would happen on index of HTML data, and I could see that none of the markup appears to be stripped out. It turns out that most of the HTML was encoded so that the angle bars are replaced with the escaped values. I will need to find a way to remove the escaped values.
Something that I've really enjoyed about DZone.com is that they have recurring themes for certain posts. One recurring set of posts is the Thursday Code Puzzler. Now and then there will be a really interesting solution. For example, one puzzler was to count the number of 1's that occurred in a set of integers. ie, {1, 2, 11, 14} = 4 since the number 1 occurs 4 times in that set. One of the solutions used map reduce to come up with the solution. I thought that was particularly neat.
public static int getLargestPalindrome(String palindromes) {
String[] palindromeArray = palindromes.split(" ");
int largestPalindrome = -1;
for(String potentialPalindrome : palindromeArray) {
if (potentialPalindrome.equals(new StringBuffer(potentialPalindrome).reverse().toString()) && potentialPalindrome.length() > largestPalindrome)
largestPalindrome = potentialPalindrome.length();
}
return largestPalindrome;
}
It works, but it felt like cheating to use the StringBuffer.reverse() method. Here is my second method:
public static int getLargestPalindrome(String palindromes) {
int largestPalindrome = -1;
for(String potentialPalindrome : palindromes.split(" ")) {
int start = 0;
int end = potentialPalindrome.length() - 1;
boolean isPalindrome = true;
while (start <= end) {
if (potentialPalindrome.charAt(start++) != potentialPalindrome.charAt(end--)) {
isPalindrome = false;
break;
}
}
if (isPalindrome && potentialPalindrome.length() > largestPalindrome) {
largestPalindrome = potentialPalindrome.length();
}
}
return largestPalindrome;
}
It works faster than the first method. I'm sure the performance improvement is mainly due to the first method's creation of new StringBuffer objects (and also new Strings for the reversed value) for each potential palindrome, but accessing locations in an array for half the length (worst case in 2nd version) is bound to be less work than (worst case in 1st version) comparing every character in a string to another string.
Using thread pools is something that is very easy to implement using Java's ExecutorService.
The Java ExecutorService class allows you to specify the number of asynchronous tasks that you want to process.
Here is an example of an ExecutorService class being instantiated where numThreads is an integer specifying the number of threads to create for the thread pool:
You pass a runnable in the ExecutorService's execute method like this:
executorService.execute(someRunnableObject);
I created a sample method that uses an ExecutorService to similute working on text files. It will move files from the source path to an archive path unless there is a "lock" file found. The "lock" file is an empty file that is named identically to one of the files that is being "worked" on. The lock file is used to ensure that the same file isn't attempted to be worked on by multiple threads. I made this sample because I figured this might be a nice way to handle indexing data in csv files to a Solr server.
Here is the method that does the work (which would be very poorly named if it weren't sample code):
public static void DoWorkOnFiles(String sourcePath, String archivePath, int numThreads) throws IOException {
Random random = new Random();
ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
File sourceFilePath = new File(sourcePath);
if (sourceFilePath.exists()) {
Collection<java.io.File> sourceFiles = FileUtils.listFiles(sourceFilePath, new String[]{"txt"}, false);
for (File sourceFile : sourceFiles) {
File lockFile = new File(sourceFile.getPath() + ".lock");
if (!lockFile.exists()) {
executorService.execute(new SampleFileWorker(sourceFile.getPath(), archivePath, random.nextInt(10000)));
}
}
// This will make the executor accept no new threads
// and finish all existing threads in the queue
try {
executorService.shutdown();
executorService.awaitTermination(10000, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignored) {
}
System.out.printf("%nFinished all threads.%n");
}
else {
System.out.printf("%s doesn't exist. No work to do.%n", sourceFilePath);
}
}
The SampleFileWorker class looks like this:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class SampleFileWorker implements Runnable {
private final String sourcePath;
private final String archivePath;
private final int testDelay;
public SampleFileWorker(String sourcePath, String archivePath, int testDelay) {
this.sourcePath = sourcePath;
this.archivePath = archivePath;
this.testDelay = testDelay;
}
@Override
public void run() {
try {
File lockFile = new File(sourcePath + ".lock");
if (!lockFile.exists()) {
lockFile.createNewFile();
} else {
return;
}
File sourceFile = new File(sourcePath);
String archiveFilePath = archivePath.concat(File.separator + sourceFile.getName());
File archiveFile = new File(archiveFilePath);
System.out.printf("Simulating work on file %s.%n", sourcePath);
System.out.printf("Starting: %s%n", sourcePath);
System.out.printf("Delay: %s%n", testDelay);
try {
Thread.sleep(testDelay);
} catch (InterruptedException ignored) {
}
System.out.printf("Done with: %s%n", sourcePath);
System.out.printf("Archiving %s to %s.%n", sourceFile, archivePath);
FileUtils.moveFile(sourceFile, archiveFile);
sourceFile.delete();
lockFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I had mentioned in one of my recent posts that I was told we are not using connection pooling in our C# web service code. I had done some reading, and it seemed pretty clear that connection pooling is enabled by default in the .Net framework, and that you would need to explicitly disable pooling.
I looked through our code and I couldn't find any instance where we set pooling to false for our connection strings. I also wrote some simple code to test if the classes we are using (from Microsoft.Practices.EnterpriseLibrary.Data) might do something odd that would prevent connection pooling, or require us to explicitly state that we want to use connection pooling.
The result of my test code was that the code where I explicitly set "pooling=false" took a longer time to execute than the code without "pooling=false". That shouldn't be surprising, but I was told by multiple people that the code was not using connection pooling. It is understandable why people thought the code was not using pooling, though. For one, there sometimes is a feeling that as code gets old, then the quality of the design degrades. Also, there are lots of coding styles and myths that get passed around as fact. This has been a concrete example for me that everyone should try things out before just accepting something as a fact when it comes to writing software. In addition, it pays to read the documentation!
The test code looks like this:
private const string pooled =
@"Data Source=someserver;Initial Catalog=dbname;Integrated Security=SSPI;";
private const string notpooled =
@"Data Source=someserver;Initial Catalog=dbname;Integrated Security=SSPI;Pooling=false;";
public static void Main(string[] args)
{
int testCount = 10000;
GenericDatabase db = new GenericDatabase(pooled, SqlClientFactory.Instance);
Console.WriteLine(" pooled : {0}", RunConnectionTest(db, testCount));
db = new GenericDatabase(notpooled, SqlClientFactory.Instance);
Console.WriteLine("not pooled : {0}", RunConnectionTest(db, testCount));
}
private static TimeSpan RunConnectionTest(GenericDatabase db, int testCount)
{
Stopwatch sw = new Stopwatch();
sw.Start();
DbConnection conn;
for (int i = 0; i < testCount; i++)
{
conn = db.CreateConnection();
conn.Open();
var schema = conn.GetSchema(); // just to make the code do something
conn.Close();
}
sw.Stop();
return sw.Elapsed;
}
I specifically did not use using statements for the connection. I wanted to mimic what the service code is doing.
The result of the test was that the loop using the connection string that implicitly uses connection pooling finished in just over 1 second. The loop for the connection string that explicitly says to not use connection pooling took about 30 seconds.
I'm pretty happy to know that we don't need to do any updates to our code to make it use connection pooling!
I signed up for a class on coursera.org. Well, that's not true - I signed up for 17 classes on coursera.org. The classes are all free, and they are taught by professors from top notch universities. I just started the "Introduction to Computer Networks" class. It's already been incredibly interesting, and I'm very happy I signed up for it. The class has already started, but if you don't really care about the grade you get out of the class, and you have an interest in learning how computer networks work, then don't hesitate to sign up. The lecture videos have been very straight forward so far, and the video length for each of the lecture segments are in easy to digest (short) segments. This lends itself to being easy to watch during a lunch break, or if you have 30 minutes or less available in the evenings. Most videos have been around 15 minutes or less, but I have found it useful to re-watch segments after realizing that I might have missed something important. We covered information that explains how latency is computed and it made me realize that, even though it is not difficult to understand latency, there is more to latency than I thought. I have always generalized latency to meaning lag. ie, playing some online game might be choppy for me due to network latency. That might be true, but now I understand what the latency is. The way I understood latency explained is that latency is the transmission delay (amount of time it takes to put bits of data onto a "wire") plus the propagation delay (amount of time for the bits to travel the distance from source host to the target host). L = latency, M = message length in bits, R = transmission rate, C = speed of light, and D = length / (2/3) C, then: Transmission delay : M/R Propagation delay : R = Length / (2/3) C Therefore:
Latency : L = M/R + D When you break it down in that way, then it seems pretty clear as to what might be causing high latency if you check out 1) where the target host is that you are connected to, 2) what your bandwidth is for your network connection, and 3) how much data you are transferring. Something else we covered was the Nyquist Limit which tells us how much data can be sent given a certain bandwidth. It was a fairly brief description, and the main thing I got out of it was how to use the formula. :) The formula is : Rate = 2 * Bandwidth * log(base 2)V bits per second V is the number of signal levels that are being used. Here is a sample question from the homework:
TV channels are 6 MHz wide. How much data can be sent per second, if four-level digital signals are used?Assume a noiseless channel, and use the Nyquist limit.
Fun stuff! Apparently the class will eventually include some java programming assignments, so I'm looking forward to those.
We are experiencing a very odd problem at work. The SQL Servers are needing to be failed over to the backup instances on a regular basis as a work-around for an issue where MS SQL is not appearing to accept connections, or the connections seem to take a while to establish. Microsoft support has been working with my employer since around November, and they seem to not be getting any closer to diagnosing and fixing the problem. One of the potential symptoms of the issue is that we have intermittent long running web method calls. The web methods are fairly simple - we make a sproc call, and then populate and return objects with the data. The SQL DBAs have checked the performance of the sproc calls during the time that the web methods are performing slowly and have assured us that the sproc calls are returning in 200ms or less. The CPU load on the load balanced web servers seem to be reasonable, so we have been speculating that the slow web method calls are either tied to the mysterious SQL Server connection issue, or due to some unknown issue while trying to connect to the database. We decided to take a number of steps to try to improve performance. If the issue is due to the MSC (mysterious SQL connection) issue, then our changes won't make much of a difference. However, we might find that our code is either exacerbating the MSC issue, or the direct cause of the slow web method calls. It's doubtful that our code is the sole cause of the MSC issue since multiple non-related SQL servers have experienced the MSC issue. Step 1: Add extra performance counters to try to pinpoint where the slow performance issue is occurring We added performance counters around some of our database connection code, and around the sproc call, to see if there are any performance issues. The tool we use to view performance counters was missing the new counters we added that would help show how often new connections are being made. That should hopefully be fixed soon. Step 2: Change the connection from using named pipes to TCP
Is it better to use TCP than named pipes? According to MSDN, the performance of using named pipes and TCP is virtually identical on fast networks. However, if you are on a slow network, and the SQL Server database is running on a different machine than the application that will be connecting to it, then TCP could give you better performance. The documentation made it sound as though named pipes might give better performance if the SQL Server instance was on the same machine as the app that is accessing the database. That is not our configuration, so it appears that there is no benefit to using named pipes. However, using TCP will be less "talky" (needs less communication back and forth to perform reads) than named pipes, and it can also help streamline communication by using backlog queues. I hadn't realized that there might be a potential performance benefit of using TCP. It shows me that I really should read through the documentation for technologies that I use regularly. It will help me be a lot more thoughtful about how and why I am doing something. Does using the default protocol (named pipes) work? Yes. However, we also need to be mindful of the performance our services have when fetching data from our databases. Step 3: Change the connections to be in a form that will allow connection pooling (if the app isn't already using connection pooling) I'm pretty new to C# / .Net, so some of what I've been told by my teammates has been taken on faith. However, I want to learn, so I did some reading. It appears that the connection pooling should happen regardless of using SqlConnection or DbConnection. I'll need to look closer at the code, and config files, to find out whether or not our app is disabling pooling, but it might be that we are using pooling, but the following is occurring due to the MSC issue. From an MSDN article on pooling:
When connection pooling is enabled, and if a timeout error or other login error occurs, an exception will be thrown and subsequent connection attempts will fail for the next five seconds, the "blocking period". If the application attempts to connect within the blocking period, the first exception will be thrown again. After the blocking period ends, another connection failure by the application will result in a blocking period that is twice as long as the previous blocking period. Subsequent failures after a blocking period ends will result in a new blocking periods that is twice as long as the previous blocking period, up to a maximum of five minutes.
So, if the mysterious SQL connection issue is causing a connection to fail, then we should expect exponentially longer waits (up to 5 minutes) for each failure to connect. It would explain why our web method call is taking hardly any time to return usually, and then takes 30+ seconds at other times. I just need to prove that we are using connection pooling, or find out why we are not using connection pooling. I hope that we are using connection pooling, because the connection failure blocking period seems to be a great explanation for what we are seeing. Leave a comment, or send an email, if you have any troubleshooting suggestions.