check_cluster in icinga2 checks - monitoring

I am trying to configure check_cluster in icinga2. We currently have a health check that is carried on 8 servers. We wanted to notify if health check on 3 or more servers is critical.
apply Service "Cluster Service Health Check" {
check_command = "check_cluster"
vars.check_cluster_service = true
vars.check_cluster_label = "Health Check"
vars.check_cluster_warning = 2
vars.check_cluster_critical = 3
vars.check_cluster_data = {{
get_object(Service, "server1.net!Elements Health Check").state + "," + get_object(Service, "server2.net!Elements Health Check").state + "," + get_object(Service, "server3.net!Elements Health Check").state + "," + get_object(Service, "server4.net!Elements Health Check").state + "," + get_object(Service, "server5.net!Elements Health Check").state + "," + get_object(Service, "server6.net!Elements Health Check").state + "," + get_object(Service, "server7.net!Elements Health Check").state + "," + get_object(Service, "server8.net!Elements Health Check").state
}}
assign where host.name == "chicago-cluster"
}
When we apply the above logic,we see the below 3 health check Critical.
CLUSTER WARNING: Elements Health Check: 5 ok, 0 warning, 0 unknown, 3 critical
But Icinga2 shows it as Warning. (see below)
Please suggest.

you just need to add # to critical value.
```
apply Service "Cluster Service Health Check" {
check_command = "check_cluster"
vars.check_cluster_service = true
vars.check_cluster_label = "Health Check"
vars.check_cluster_warning = 2
vars.check_cluster_critical = #3
vars.check_cluster_data = {{
get_object(Service, "server1.net!Elements Health Check").state + "," + get_object(Service, "server2.net!Elements Health Check").state + "," + get_object(Service, "server3.net!Elements Health Check").state + "," + get_object(Service, "server4.net!Elements Health Check").state + "," + get_object(Service, "server5.net!Elements Health Check").state + "," + get_object(Service, "server6.net!Elements Health Check").state + "," + get_object(Service, "server7.net!Elements Health Check").state + "," + get_object(Service, "server8.net!Elements Health Check").state
}}
assign where host.name == "chicago-cluster"```

Related

print method in lua script/redis is not working

I am trying to execute the following script and getting the below error. Redis is running in docker
Exception in thread "main" org.redisson.client.RedisException: ERR
user_script:1: Script attempted to access nonexistent global variable
'print' script: 6f736423f082e141036b833d1f86b5a36a494611, on
#user_script:1..
I get the same error when I execute using redis CLI
127.0.0.1:6379> eval "print("Comparison is_made b/w minimum_value out of two is: ")" 0 (error) ERR user_script:1: Script attempted to
access nonexistent global variable 'print' script:
8598b7f0db450c711d3a9e73a296e331bd1ef945, on #user_script:1.
127.0.0.1:6379>
Java code. I am using Redison lib to connect to Redis and execute script.
String script = "local rate = redis.call('hget', KEYS[1], 'rate');"
+ "local interval = redis.call('hget', KEYS[1], 'interval');"
+ "local type = redis.call('hget', KEYS[1], 'type');"
+ "assert(rate ~= false and interval ~= false and type ~= false, 'RateLimiter is not initialized')"
+ "local valueName = KEYS[2];"
+ "local permitsName = KEYS[4];"
+ "if type == '1' then "
+ "valueName = KEYS[3];"
+ "permitsName = KEYS[5];"
+ "end;"
+"print(\"rate\"..rate) ;"
+"print(\"interval\"..interval) ;"
+"print(\"type\"..type); "
+ "assert(tonumber(rate) >= tonumber(ARGV[1]), 'Requested permits amount could not exceed defined rate'); "
+ "local currentValue = redis.call('get', valueName); "
+ "local res;"
+ "if currentValue ~= false then "
+ "local expiredValues = redis.call('zrangebyscore', permitsName, 0, tonumber(ARGV[2]) - interval); "
+ "local released = 0; "
+ "for i, v in ipairs(expiredValues) do "
+ "local random, permits = struct.unpack('Bc0I', v);"
+ "released = released + permits;"
+ "end; "
+ "if released > 0 then "
+ "redis.call('zremrangebyscore', permitsName, 0, tonumber(ARGV[2]) - interval); "
+ "if tonumber(currentValue) + released > tonumber(rate) then "
+ "currentValue = tonumber(rate) - redis.call('zcard', permitsName); "
+ "else "
+ "currentValue = tonumber(currentValue) + released; "
+ "end; "
+ "redis.call('set', valueName, currentValue);"
+ "end;"
+ "if tonumber(currentValue) < tonumber(ARGV[1]) then "
+ "local firstValue = redis.call('zrange', permitsName, 0, 0, 'withscores'); "
+ "res = 3 + interval - (tonumber(ARGV[2]) - tonumber(firstValue[2]));"
+ "else "
+ "redis.call('zadd', permitsName, ARGV[2], struct.pack('Bc0I', string.len(ARGV[3]), ARGV[3], ARGV[1])); "
+ "redis.call('decrby', valueName, ARGV[1]); "
+ "res = nil; "
+ "end; "
+ "else "
+ "redis.call('set', valueName, rate); "
+ "redis.call('zadd', permitsName, ARGV[2], struct.pack('Bc0I', string.len(ARGV[3]), ARGV[3], ARGV[1])); "
+ "redis.call('decrby', valueName, ARGV[1]); "
+ "res = nil; "
+ "end;"
+ "local ttl = redis.call('pttl', KEYS[1]); "
+ "if ttl > 0 then "
+ "redis.call('pexpire', valueName, ttl); "
+ "redis.call('pexpire', permitsName, ttl); "
+ "end; "
+ "return res;";
RedissonClient client = null;
try {
client = Redisson.create();
client.getRateLimiter("user1:endpoint1").setRate(
RateType.PER_CLIENT, 5, 1, RateIntervalUnit.SECONDS);
String sha1 = client.getScript().scriptLoad(script);
List<Object> keys =
Arrays.asList("user1:endpoint1", "{user1:endpoint1}:value",
"{user1:endpoint1}:value:febbb04d-6365-4cb8-b32b-8d90800cd4e6",
"{user1:endpoint1}:permits", "{user1:endpoint1}:permits:febbb04d-6365-4cb8-b32b-8d90800cd4e6");
byte[] random = new byte[8];
ThreadLocalRandom.current().nextBytes(random);
Object args[] = {1, System.currentTimeMillis(), random};
boolean res = client.getScript().evalSha(READ_WRITE, sha1, RScript.ReturnType.BOOLEAN, keys, 1,
System.currentTimeMillis(), random);
System.out.println(res);
}finally {
if(client != null && !client.isShutdown()){
client.shutdown();
}
}
checked the Lua print on the same line thread but io.write also is giving same error.
As in the comments wrote return() seems* the only way.
Example for redis-cli (set redis DB and use it in Lua)
(Collect Data and return as one string)
set LuaV 'local txt = "" for k, v in pairs(redis) do txt = txt .. tostring(k) .. " => " .. tostring(v) .. " | " end return(txt)'
Now the eval
eval "local f = redis.call('GET', KEYS[1]) return(loadstring(f))()" 1 LuaV
...shows whats in table: redis
(One long String no \n possible)
Exception: eval 'redis.log(2, _VERSION)' 0 gives out without ending the script but only on the server.
Than \n will work when you do...
set LuaV 'local txt = "" for k, v in pairs(redis) do txt = txt .. tostring(k) .. " => " .. tostring(v) .. "\n" end return(txt)'
...and the eval
eval 'local f = redis.call("GET", KEYS[1]) f = loadstring(f)() redis.log(2, f)' 1 LuaV

Check if number of OrdersHistoryTotal in Metatrader 4 trade history changed

I would like to fire a function as soon as a trade was closed (= the OrdersHistoryTotal increased by at least 1).
Is there any handler in MQL4 for such scenarios?
In my particular setup I have the following function pushSocket which should only push data in case the OrdersHistoryTotal changed.
int i,hstTotal=OrdersHistoryTotal();
string historical_trades = "";
for(i=0;i<hstTotal;i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) continue;
historical_trades = historical_trades +
"historical_trades|" +
version + "|" +
DID + "|" +
AccountNumber() + "|" +
IntegerToString(OrderTicket()) + "," +
TimeToString(OrderOpenTime(), TIME_DATE|TIME_SECONDS) + "," +
TimeToString(OrderCloseTime(), TIME_DATE|TIME_SECONDS) + "," +
IntegerToString(OrderType()) + "," +
DoubleToString(OrderLots(),2) + "," +
OrderSymbol() + "," +
DoubleToString(OrderOpenPrice(),5) + "," +
DoubleToString(OrderClosePrice(),5) + "," +
DoubleToString(OrderStopLoss(),5) + "," +
DoubleToString(OrderTakeProfit(),5) + "," +
DoubleToString(OrderCommission(),2) + "," +
DoubleToString(OrderSwap(),2) + "," +
DoubleToString(OrderProfit(),2) + "," +
"<" + OrderComment() + ">|";
}
pushSocket.send(StringFormat("%s", historical_trades, true));
I tried to insert a counter to compare it but the counter is deleted every time on memory clean-up.. The above function is nested in a onTick function which executes every second.
There is a function OnTradeAction() in MQL5 that is called every time some trading action is done. But unfortunately this function is not available in MQL4. On the other hand, you can implement a function inside OnTick() that will check that HistoryTraderTotal() increased compared to the previously saved value, and do all the steps you like in that case. A bit more work but almost the same.
OnTimer(){
Mt4OnTradeAction();
otherLogic();
}
Mt4OnTradeAction(){
static int historyTradesTotal=0;
if(HistoryTradesTotal()==historyTradesTotal) return;
historyTradesTotal = HistoryTradesTotal();
processingTrade();
}

Rails: sending data to asana and getting a syntax error

assign task to Asana
require "rubygems"
require "JSON"
require "net/https"
api_key = "1wPBetR9.6bhINO7xO9ypG6iP2aYU8hx"
workspace_id = "5386494137624"
assignee = "craig#theaerialistpress.com"
# set up HTTPS connection
uri = URI.parse("https://app.asana.com/api/1.0/tasks")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
# set up the request
header = {
"Content-Type" => "application/json"
}
req = Net::HTTP::Post.new(uri.path, header)
req.basic_auth(api_key, '')
req.body = {
"data" => {
"workspace" => workspace_id,
"name" => "House Order: " + #order.name,
"assignee" => assignee,
"projects" => "35978729781365",
"notes" => "Name: " + #order.name +
"\nEmail: " + #order.email +
"\nEvent Date: " + #date.to_s +
"\nDesign: " + #order.design +
"\n\nPaper Color: " + #order.paper_color +
"\nFont #1: " + #order.font1 +
"\nFont #2: " + #order.font2 +
if #order.card_type1 != "none"
"\n\nCard #1: " + #order.card_type1 + "\nPaper Weight: " + #order.paper_weight1 + "\nQuantity: " + #order.quantity1 + "\nInk Color #1: " + #order.ink_color11 + "\nInk Color #2: " + #order.ink_color12 + "\nWording: " + #order.wording1 + "\nReturn Address Printing: " + #order.return_address1 + "\nGuest Address Printing: " + #order.guest_address1.to_s + "\nEnvelope Liners: " + #order.envelope_liners1
end
if #order.card_type2 != "none"
"\n\nCard #2: " + #order.card_type2 + "\nPaper Weight: " + #order.paper_weight2 + "\nQuantity: " + #order.quantity2 + "\nInk Color #2: " + #order.ink_color21 + "\nInk Color #2: " + #order.ink_color22 + "\nWording: " + #order.wording2 + "\nReturn Address Printing: " + #order.return_address2 + "\nGuest Address Printing: " + #order.guest_address2.to_s + "\nEnvelope Liners: " + #order.envelope_liners2
end
}
}.to_json()
# issue the request
res = http.start { |http| http.request(req) }
# output
body = JSON.parse(res.body)
if body['errors'] then
puts "Server returned an error: #{body['errors'][0]['message']}"
else
puts "Created task with id: #{body['data']['id']}"
end
I am getting a syntax error when I am using if statements inside the data I am sending to asana. I am very new at rails and not sure what I am doing wrong.
This is the error:
syntax error, unexpected keyword_if, expecting '}' if #order.card_type2 != "none" ^ /Users/craigrinde/Dropbox/top_secret/aerialist/app/controllers/orders_controller.rb:212: syntax error, unexpected '}', expecting keyword_end } ^

nest api target temperature for both thermostat modes

Is it possible to fetch target temperature for both thermostat mode (cool, heat) in one call ? For now I have a feeling that I can get target temperature for current thermostat mode and then change thermostat mode to second one and get target temperature for second thermostat mode.
Also the same question for changing target temps. Is it possible to change both target temperature for heat and cool mode in one request ?
Assuming your system can cool and heat, the thermostat has 3 modes: heat, cool, heat-cool.
If you are in heat mode or cool mode you can set target_temperature. If you are in heat-cool mode you can set target_temperature_low_c & target_temperature_high_c.
You can retrieve all target temperatures in one thermostat call:
https://developer-api.nest.com/devices/thermostats/$THERMOSTAT_ID?auth=$AUTH
You can set heat-cool temperatures in one call, but you will need to be in heat-cool mode:
{"target_temperature_low_c": 19, "target_temperature_high_c": 21}
You can set heat or cool temperature in one call, but you will need to be in heat or cool mode:
{"target_temperature_c": 20}
You will need to make 2 calls to set the mode and set the temperature(s) if you are not already in an appropriate mode.
It is possible to get all of the thermostat data, even for multiple thermostats in a single API call. I just posted an opensource application written in python that does it on BitBucket at:
https://bitbucket.org/dwalton64_/window-watcher
The application looks at weather data from weather underground, air quality data from airnow and data from Nest to determine if the user should open or close the windows. I make the API call to Nest, getting all of the data in a single call, and then parse the data in a structure. The application then uses the thermostat hvac mode and the target temperature to see if the user should open the windows.
Here is some Python code I pulled out of my application:
nestUserUrl = "https://developer-api.nest.com/?auth=" + auth_token
nest_user_file = urllib2.urlopen(self.nestUserUrl)
nest_user_json = json.loads(nest_user_file.read())
# copy thermostat data out of the json from Nest
thermostat_data = []
for tstat_id in nest_user_json['devices']['thermostats']:
thermostat_data.append(nest_user_json['devices']['thermostats'][tstat_id])
# create thermostat objects containing the thermostat data we want to access
thermostats = []
for tstat in thermostat_data:
thermostats.append(
NestThermostat(tstat['ambient_temperature_f'], tstat['device_id'],
tstat['hvac_mode'],
tstat['is_online'], tstat['last_connection'],
tstat['name'],
tstat['software_version'], tstat['structure_id'],
tstat['target_temperature_f'],
tstat['target_temperature_high_f'],
tstat['target_temperature_low_f']))
class NestThermostat():
def __init__(self, ambient_temperature_f, device_id, hvac_mode, is_online,
last_connection, name, software_version, structure_id,
target_temperature_f, target_temperature_high_f, target_temperature_low_f):
self.ambient_temperature_f = ambient_temperature_f
self.device_id = device_id
self.hvac_mode = hvac_mode
self.is_online = is_online
self.last_connection = last_connection
self.name = name
self.software_version = software_version
self.structure_id = structure_id
self.target_temperature_f = target_temperature_f
self.target_temperature_high_f = target_temperature_high_f
self.target_temperature_low_f = target_temperature_low_f
def print_current_temp_f(self):
print("Thermostat " + self.name + " measures a current temperature of " + str(
self.ambient_temperature_f) + " degrees F")
def print_target_temp_f(self):
print("Thermostat " + self.name + " is set to " + str(self.target_temperature_f) + " degrees F")
Once I have the data in the thermostat objects, I can use both the hvac mode and the target temperatures:
email = ""
for thermostat in thermostats:
email += "For the thermostat " + thermostat.name + ":\n"
if thermostat.hvac_mode == 'cool':
if myWeather.temp_f < thermostat.target_temperature_f:
open_windows = True
email += " - It is cool outside (" + str(myWeather.temp_f) + " Deg F). \n"
else:
email += " - It is too hot outside to have the windows open. \n"
email += " - Thermostat is set at " + str(thermostat.target_temperature_f) + \
" Deg F\n"
if thermostat.hvac_mode == 'heat-cool':
if thermostat.target_temperature_high_f > myWeather.temp_f > thermostat.target_temperature_low_f:
open_windows = True
email += " - Thermostat is set to heat-cool and it's comfortable out (" + \
str(myWeather.temp_f) + " Deg F). \n"
elif myWeather.temp_f >= thermostat.target_temperature_high_f:
email += " - The thermostat is set to heat-cool and it is hot outside (" + \
str(myWeather.temp_f) + " Deg F). \n"
else:
email += " - The thermostat is set to heat-cool & it is cold outside (" + \
str(myWeather.temp_f) + " Deg F). \n"
email += " - The thermostat is set to cool at " + \
str(thermostat.target_temperature_high_f) + " Deg F\n"
email += " - The thermostat is set to heat at " + \
str(thermostat.target_temperature_low_f) + " Deg F\n"
if thermostat.hvac_mode == 'heat':
if myWeather.temp_f > thermostat.target_temperature_f:
open_windows = True
email += " - The thermostat is set to heat and it is warm outside (" + \
str(myWeather.temp_f) + " Deg F). \n"
else:
email += " - The thermostat is set to heat and it is cool outside (" + \
str(myWeather.temp_f) + " Deg F). \n"
email += " - Thermostat is set at " + str(thermostat.target_temperature_f) + \
" Deg F\n"
email += "\n"
Note that the target temperature for heat and cool mode is the same value: target_temperature_f.

Parsing on server versus parsing on localhost

Here is my code:
if (amount != -1)
returnJson.Add("<p style=\"color: black;\">" + double.Parse(res_q.Replace(",", ".")) * amount + " " + res_i + "</p>");
else
returnJson.Add("<p style=\"color: black;\">" + res_q + " " + " ") + res_i + "</p>");
And no matter if the execution of the program goes to if or the else, if res_q="1,5", this returns 15 on server, and 1.5 locally.
Why is this happening?
The problem was in the comma.
I want to apply globalization in my program. Using CultureInfo.InvariantCulture was the answer I needed. Or simple replcing the comma with dot.

Resources