hystrixThreadPool.js 11.6 KB
Newer Older
Dave Syer committed
1 2 3 4

(function(window) {

	// cache the templates we use on this page as global variables (asynchronously)
5
	jQuery.get(getRelativePath("components/hystrixThreadPool/templates/hystrixThreadPool.html"), function(data) {
Dave Syer committed
6 7
		htmlTemplate = data;
	});
8
	jQuery.get(getRelativePath("components/hystrixThreadPool/templates/hystrixThreadPoolContainer.html"), function(data) {
Dave Syer committed
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
		htmlTemplateContainer = data;
	});

	function getRelativePath(path) {
		var p = location.pathname.slice(0, location.pathname.lastIndexOf("/")+1);
		return p + path;
	}

	/**
	 * Object containing functions for displaying and updating the UI with streaming data.
	 * 
	 * Publish this externally as "HystrixThreadPoolMonitor"
	 */
	window.HystrixThreadPoolMonitor = function(containerId) {
		
		var self = this; // keep scope under control
		
		this.containerId = containerId;
		
		/**
		 * Initialization on construction
		 */
		// intialize various variables we use for visualization
		var maxXaxisForCircle="40%";
		var maxYaxisForCircle="40%";
		var maxRadiusForCircle="125";
		var maxDomain = 2000;
		
		self.circleRadius = d3.scale.pow().exponent(0.5).domain([0, maxDomain]).range(["5", maxRadiusForCircle]); // requests per second per host
		self.circleYaxis = d3.scale.linear().domain([0, maxDomain]).range(["30%", maxXaxisForCircle]);
		self.circleXaxis = d3.scale.linear().domain([0, maxDomain]).range(["30%", maxYaxisForCircle]);
		self.colorRange = d3.scale.linear().domain([10, 25, 40, 50]).range(["green", "#FFCC00", "#FF9900", "red"]);
		self.errorPercentageColorRange = d3.scale.linear().domain([0, 10, 35, 50]).range(["grey", "black", "#FF9900", "red"]);

		/**
		 * We want to keep sorting in the background since data values are always changing, so this will re-sort every X milliseconds
		 * to maintain whatever sort the user (or default) has chosen.
		 * 
		 * In other words, sorting only for adds/deletes is not sufficient as all but alphabetical sort are dynamically changing.
		 */
		setInterval(function() {
			// sort since we have added a new one
			self.sortSameAsLast();
		}, 1000)
		
		/**
		 * END of Initialization on construction
		 */
		
		/**
		 * Event listener to handle new messages from EventSource as streamed from the server.
		 */
		/* public */ self.eventSourceMessageListener = function(e) {
			var data = JSON.parse(e.data);
			if(data) {
				// check for reportingHosts (if not there, set it to 1 for singleHost vs cluster)
				if(!data.reportingHosts) {
					data.reportingHosts = 1;
				}
				
				if(data && data.type == 'HystrixThreadPool') {
					if (data.deleteData == 'true') {
						deleteThreadPool(data.escapedName);
					} else {
						displayThreadPool(data);
					}
				}
			}
		}
		
		/**
		 * Pre process the data before displying in the UI. 
		 * e.g   Get Averages from sums, do rate calculation etc. 
		 */
		function preProcessData(data) {
			validateData(data);
			// escape string used in jQuery & d3 selectors
			data.escapedName = data.name.replace(/([ !"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g,'\\$1');
			// do math
			converAllAvg(data);
			calcRatePerSecond(data);
		}
		
		function converAllAvg(data) {
			convertAvg(data, "propertyValue_queueSizeRejectionThreshold", false);
		}
		
		function convertAvg(data, key, decimal) {
			if (decimal) {
				data[key] = roundNumber(data[key]/data["reportingHosts"]);
			} else {
				data[key] = Math.floor(data[key]/data["reportingHosts"]);
			}
		}
		
		function calcRatePerSecond(data) {
			var numberSeconds = data["propertyValue_metricsRollingStatisticalWindowInMilliseconds"] / 1000;

			var totalThreadsExecuted = data["rollingCountThreadsExecuted"];
			if (totalThreadsExecuted < 0) {
				totalThreadsExecuted = 0;
			}
			data["ratePerSecond"] =  roundNumber(totalThreadsExecuted / numberSeconds);
			data["ratePerSecondPerHost"] =  roundNumber(totalThreadsExecuted / numberSeconds / data["reportingHosts"]);
	    }

		function validateData(data) {
			
			assertNotNull(data,"type");
			assertNotNull(data,"name");
			// assertNotNull(data,"currentTime");
			assertNotNull(data,"currentActiveCount");
			assertNotNull(data,"currentCompletedTaskCount");
			assertNotNull(data,"currentCorePoolSize");
			assertNotNull(data,"currentLargestPoolSize");
			assertNotNull(data,"currentMaximumPoolSize");
			assertNotNull(data,"currentPoolSize");
			assertNotNull(data,"currentQueueSize");
			assertNotNull(data,"currentTaskCount");
			assertNotNull(data,"rollingCountThreadsExecuted");
			assertNotNull(data,"rollingMaxActiveThreads");
			assertNotNull(data,"reportingHosts");

            assertNotNull(data,"propertyValue_queueSizeRejectionThreshold");
			assertNotNull(data,"propertyValue_metricsRollingStatisticalWindowInMilliseconds");
		}
		
		function assertNotNull(data, key) {
			if(data[key] == undefined) {
				if (key == "dependencyOwner") {
					data["dependencyOwner"] = data.name;
				} else {
					throw new Error("Key Missing: " + key + " for " + data.name)
				}
			}
		}

		/**
		 * Method to display the THREAD_POOL data
		 * 
		 * @param data
		 */
		/* private */ function displayThreadPool(data) {
			
			try {
				preProcessData(data);
			} catch (err) {
				log("Failed preProcessData: " + err.message);
				return;
			}
			
			// add the 'addCommas' function to the 'data' object so the HTML templates can use it
			data.addCommas = addCommas;
			// add the 'roundNumber' function to the 'data' object so the HTML templates can use it
			data.roundNumber = roundNumber;
			
			var addNew = false;
			// check if we need to create the container
			if(!$('#THREAD_POOL_' + data.escapedName).length) {
				// it doesn't exist so add it
				var html = tmpl(htmlTemplateContainer, data);
				// remove the loading thing first
				$('#' + containerId + ' span.loading').remove();
				// get the current last column and remove the 'last' class from it
				$('#' + containerId + ' div.last').removeClass('last');
				// now create the new data and add it
				$('#' + containerId + '').append(html);
				// add the 'last' class to the column we just added
				$('#' + containerId + ' div.monitor').last().addClass('last');
				
				// add the default sparkline graph
				d3.selectAll('#graph_THREAD_POOL_' + data.escapedName + ' svg').append("svg:path");
				
				// remember this is new so we can trigger a sort after setting data
				addNew = true;
			}
			
			// set the rate on the div element so it's available for sorting
			$('#THREAD_POOL_' + data.escapedName).attr('rate_value', data.ratePerSecondPerHost);
			
			// now update/insert the data
			$('#THREAD_POOL_' + data.escapedName + ' div.monitor_data').html(tmpl(htmlTemplate, data));

			// set variables for circle visualization
			var rate = data.ratePerSecondPerHost;
			// we will treat each item in queue as 1% of an error visualization
			// ie. 5 threads in queue per instance == 5% error percentage
			var errorPercentage = data.currentQueueSize / data.reportingHosts; 
			
			updateCircle('#THREAD_POOL_' + data.escapedName + ' circle', rate, errorPercentage);
			
			if(addNew) {
				// sort since we added a new circuit
				self.sortSameAsLast();
			}
		}
		
		/* round a number to X digits: num => the number to round, dec => the number of decimals */
		/* private */ function roundNumber(num) {
			var dec=1; // we are hardcoding to support only 1 decimal so that our padding logic at the end is simple
			var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
			var resultAsString = result.toString();
			if(resultAsString.indexOf('.') == -1) {
				resultAsString = resultAsString + '.';
				for(var i=0; i<dec; i++) {
					resultAsString = resultAsString + '0';
				}
			}
			return resultAsString;
		};
		
		
		/* private */ function updateCircle(cssTarget, rate, errorPercentage) {
			var newXaxisForCircle = self.circleXaxis(rate);
			if(parseInt(newXaxisForCircle) > parseInt(maxXaxisForCircle)) {
				newXaxisForCircle = maxXaxisForCircle;
			}
			var newYaxisForCircle = self.circleYaxis(rate);
			if(parseInt(newYaxisForCircle) > parseInt(maxYaxisForCircle)) {
				newYaxisForCircle = maxYaxisForCircle;
			}
			var newRadiusForCircle = self.circleRadius(rate);
			if(parseInt(newRadiusForCircle) > parseInt(maxRadiusForCircle)) {
				newRadiusForCircle = maxRadiusForCircle;
			}
			
			d3.selectAll(cssTarget)
				.transition()
				.duration(400)
				.attr("cy", newYaxisForCircle)
				.attr("cx", newXaxisForCircle)
				.attr("r", newRadiusForCircle)
				.style("fill", self.colorRange(errorPercentage));
		}
		
		/* private */ function deleteThreadPool(poolName) {
			$('#THREAD_POOL_' + poolName).remove();
		}
		
	}

	// public methods for sorting
	HystrixThreadPoolMonitor.prototype.sortByVolume = function() {
		var direction = "desc";
		if(this.sortedBy == 'rate_desc') {
			direction = 'asc';
		}
		this.sortByVolumeInDirection(direction);
	}

	HystrixThreadPoolMonitor.prototype.sortByVolumeInDirection = function(direction) {
		this.sortedBy = 'rate_' + direction;
		$('#' + this.containerId + ' div.monitor').tsort({order: direction, attr: 'rate_value'});
	}

	HystrixThreadPoolMonitor.prototype.sortAlphabetically = function() {
		var direction = "asc";
		if(this.sortedBy == 'alph_asc') {
			direction = 'desc';
		}
		this.sortAlphabeticalInDirection(direction);
	}

	HystrixThreadPoolMonitor.prototype.sortAlphabeticalInDirection = function(direction) {
		this.sortedBy = 'alph_' + direction;
		$('#' + this.containerId + ' div.monitor').tsort("p.name", {order: direction});
	}

	HystrixThreadPoolMonitor.prototype.sortByMetricInDirection = function(direction, metric) {
		$('#' + this.containerId + ' div.monitor').tsort(metric, {order: direction});
	}

	// this method is for when new divs are added to cause the elements to be sorted to whatever the user last chose
	HystrixThreadPoolMonitor.prototype.sortSameAsLast = function() {
		if(this.sortedBy == 'alph_asc') {
			this.sortAlphabeticalInDirection('asc');
		} else if(this.sortedBy == 'alph_desc') {
			this.sortAlphabeticalInDirection('desc');
		} else if(this.sortedBy == 'rate_asc') {
			this.sortByVolumeInDirection('asc');
		} else if(this.sortedBy == 'rate_desc') {
			this.sortByVolumeInDirection('desc');
		} else if(this.sortedBy == 'error_asc') {
			this.sortByErrorInDirection('asc');
		} else if(this.sortedBy == 'error_desc') {
			this.sortByErrorInDirection('desc');
		} else if(this.sortedBy == 'lat90_asc') {
			this.sortByMetricInDirection('asc', 'p90');
		} else if(this.sortedBy == 'lat90_desc') {
			this.sortByMetricInDirection('desc', 'p90');
		} else if(this.sortedBy == 'lat99_asc') {
			this.sortByMetricInDirection('asc', 'p99');
		} else if(this.sortedBy == 'lat99_desc') {
			this.sortByMetricInDirection('desc', 'p99');
		} else if(this.sortedBy == 'lat995_asc') {
			this.sortByMetricInDirection('asc', 'p995');
		} else if(this.sortedBy == 'lat995_desc') {
			this.sortByMetricInDirection('desc', 'p995');
		} else if(this.sortedBy == 'latMean_asc') {
			this.sortByMetricInDirection('asc', 'pMean');
		} else if(this.sortedBy == 'latMean_desc') {
			this.sortByMetricInDirection('desc', 'pMean');
		} else if(this.sortedBy == 'latMedian_asc') {
			this.sortByMetricInDirection('asc', 'pMedian');
		} else if(this.sortedBy == 'latMedian_desc') {
			this.sortByMetricInDirection('desc', 'pMedian');
		}  
	}

	// default sort type and direction
	this.sortedBy = 'alph_asc';


	// a temporary home for the logger until we become more sophisticated
	function log(message) {
		console.log(message);
	};

	function addCommas(nStr){
	  nStr += '';
	  if(nStr.length <=3) {
		  return nStr; //shortcut if we don't need commas
	  }
	  x = nStr.split('.');
	  x1 = x[0];
	  x2 = x.length > 1 ? '.' + x[1] : '';
	  var rgx = /(\d+)(\d{3})/;
	  while (rgx.test(x1)) {
	    x1 = x1.replace(rgx, '$1' + ',' + '$2');
	  }
	  return x1 + x2;
	}
})(window)