Telegraf multiple nginx in a single host - telegraf

I have 3 Nginx servers running on a single host and have a diffuculty to set up correctly in Telegraf. Here is the current setup for one Nginx server and need to add two inputs which are for decoding log files for other two servers. Any help would be appreciated!
#nginx-metrics and logs
[[inputs.nginx]]
urls = ["https://example.com/nginx_status"]
response_timeout = "5s"
[[inputs.tail]]
name_override = "nginxlog"
files = ["/var/www/example/logs/http-access.log"]
from_beginning = false
pipe = false
data_format = "grok"
grok_patterns = ["%{COMBINED_LOG_FORMAT}"]
[[inputs.exec]]
commands = [
"sh /etc/telegraf/nginx_stats.sh"
]
timeout = "5s"
name_override = "nginx_response_code"
data_format = "json"
tag_keys = [
"resp_code"
]
[[outputs.prometheus_client]]
listen = "0.0.0.0:9125"
For example, something like this.
[[inputs.tail]]
name_override = "nginxlog"
files = ["/var/www/example2/logs/http-access.log"]
from_beginning = false
pipe = false
data_format = "grok"
grok_patterns = ["%{COMBINED_LOG_FORMAT}"]
[[inputs.exec]]
commands = [
"sh /etc/telegraf/nginx_stats2.sh"
]
timeout = "5s"
name_override = "nginx_response_code"
data_format = "json"
tag_keys = [
"resp_code"
]
[[inputs.tail]]
name_override = "nginxlog"
files = ["/var/www/example3/logs/http-access.log"]
from_beginning = false
pipe = false
data_format = "grok"
grok_patterns = ["%{COMBINED_LOG_FORMAT}"]
[[inputs.exec]]
commands = [
"sh /etc/telegraf/nginx_stats3.sh"
]
timeout = "5s"
name_override = "nginx_response_code"
data_format = "json"
tag_keys = [
"resp_code"
]

Related

Unable to reconnect to a socket

I am trying to connect to a socket using a client that is running Tkinter. The script runs a banking app allowing users to log in. The user data is stored in an SQLite database. When running the socket and client scripts the Tkinter window launches and the user is able to log in. However, when the user logs out and tries to log in as another user the program gets stuck.
LogInCommand() I think is getting stuck as it only fails when running again. I believe it has to do with how I am discounting from the socket. However, I need the socket to constantly run for the app to work.
Socket :
import socket
import sqlite3
Connection = sqlite3.connect('BankAccounts.sqlite')
st = socket.socket() #Creating a socket object. Second socket is the class.
print("socket ready")
st.bind(("Localhost",8080)) #Creating the socket using port 8080 (IP address + port number)
st.listen(100) #Only allowing a maximum of two connections at a time.
print("waiting for connections")
while True:
Client, address = st.accept() #Creating two variables and setting them equal to the accept object method.
# print("connected with", address)
print("Banking")
cdata = Client.recv(1024).decode()
print("in loop")
if not cdata:
break
if "*li#" in cdata:
print(cdata)
data = cdata.split("*li#")
cred = data[1].split("##")
sql = "SELECT * FROM bankusers"
curser = Connection.execute(sql)
username = cred[0]
password = cred[1]
for row in curser:
if row[0] == username and row[1] == password:
balance = str(row[2])
print(type(balance))
login = ("*Suc*"+balance)
print(login)
Client.send(bytes(f"{login}",'utf-8'))
Client.close()
Client :
from tkinter import *
from tkinter import *
from Bank import *
import socket
root = Tk()
Client = socket.socket()
Client.connect(("Localhost",8080))
import json
login = "Failed"
import sqlite3
Connection = sqlite3.connect('BankAccounts.sqlite')
def localuser(username,password,balance):
user1 = {
"username": username,
"password": password,
"balance" : balance
}
return user1
def sqlupdate():
with open("bankusers.json","r") as file:
reader = json.load(file)
balance2 = reader["balance"]
username2 = reader["username"]
print(balance2)
print(username2)
sql = f"UPDATE bankusers SET balance = {balance2} where username = '{username2}'"
Connection.execute(sql)
Connection.commit()
def updatenewuser(username, amount):
try:
sql1 = f"Select * from bankusers where username = '{username}' "
data = Connection.execute(sql1)
for row in data:
newbalance = int(row[2]) + int(amount)
sql2 = f"Update bankusers Set balance = {newbalance} where username = '{username}'"
Connection.execute(sql2)
except:
print("The user does not exist")
def logout():
canvas.delete("all")
label1 = Label(root,text = "Username")
label2 = Label(root,text = "Password")
global usernamebox
global passwordbox
usernamebox = Entry(root,width = 20)
passwordbox = Entry(root,width = 20)
buttonLogin = Button(root,text = "Login",width=10, command=LoginCommand)
canvas.create_window(230,100,window = label1)
canvas.create_window(230,150,window = label2)
canvas.create_window(400,100,window = usernamebox)
canvas.create_window(400,150,window = passwordbox)
canvas.create_window(400,200,window = buttonLogin)
canvas.pack()
def pay():
if name.get()==username1:
trylabel = Label(root,text= "You are unable to send money to yourself",)
canvas.create_window(400,250,window=trylabel)
else:
canvas.delete("all")
try:
sql2 = f"SELECT * FROM bankusers where username = '{username1}'"
curser = Connection.execute(sql2)
for row in curser:
if int(amountbox.get()) <= row[2]:
print("Sent")
newamount = row[2] - int(amountbox.get())
with open("bankusers.json", "w") as file:
user = localuser(username1,password1,newamount)
json.dump(user,file,indent=3)
sqlupdate()
updatenewuser(name.get(),int(amountbox.get()))
label1 = Label(root,text="Transaction Succsfull")
backbut = Button(root,text= "Done", command=mainscreen)
canvas.create_window(400,100,window=label1)
canvas.create_window(400,200,window=backbut)
else:
canvas.delete("all")
label1 = Label(root,text = "Transaction Failed. Please ensure you have suffcient funds for this transaction")
canvas.create_window(400,200,window=label1)
backbut = Button(root,text= "Done", command=mainscreen)
canvas.create_window(400,300,window=backbut)
except:
label1 = Label(root,text = "Transaction Failed. Please check recipient name and amount")
canvas.create_window(400,200,window=label1)
backbut = Button(root,text= "Done", command=mainscreen)
canvas.create_window(400,300,window=backbut)
def transact():
print("")
canvas.delete("all")
global name
label1 = Label(root,text = "Person Receiving:")
label2 = Label(root,text = "Amount:")
name = Entry(root,width = 20)
global amountbox
amountbox = Entry(root,width = 20)
paybutt = Button(root,text = "Pay", command = pay)
backbutton = Button(root,text = "Back",command = mainscreen)
canvas.create_window(350,300,window=backbutton)
canvas.create_window(450,100,window = name)
canvas.create_window(250,100,window=label1)
canvas.create_window(250,200,window=label2)
canvas.create_window(450,300,window=paybutt)
canvas.create_window(450,200,window=amountbox)
return
def LoginCommand():
count = 1
li = "*li#"
cred = li+usernamebox.get()+"##"+passwordbox.get()
Client.send((bytes(cred,"utf-8")))
message = Client.recv(1024).decode()
print(message)
if "*Suc*" in message:
count = 0
login = "Succsess"
global username1
global password1
global balance1
username1 = usernamebox.get()
password1 = passwordbox.get()
usernamebox.destroy()
passwordbox.destroy()
canvas.delete("all")
balance1 = message.split("*Suc*")
user = localuser(username1,password1,balance1[1])
with open("bankusers.json", "w") as file:
json.dump(user,file,indent=3)
mainscreen()
if count == 1:
global label2
label2 = Label(root,text = "Login Failed. Please Try Again")
canvas.create_window(400,250,window = label2)
def mainscreen():
with open("bankusers.json","r") as file:
reader = json.load(file)
balance2 = reader["balance"]
label2.destroy()
canvas.delete("all")
label1 = Label(root, text = f"Available Balance: R{balance2}")
buttonLogout = Button(root,text = "Log Out", command=logout)
buttonTrans = Button(root,text = "Transact", command=transact)
canvas.create_window(400,100,window = label1)
canvas.create_window(350,200,window=buttonLogout)
canvas.create_window(450,200,window = buttonTrans)
canvas.pack()
root.title("Raindrop Bank")
canvas = Canvas(root, width = 800, height = 400)
label1 = Label(root,text = "Username")
label2 = Label(root,text = "Password")
usernamebox = Entry(root,width = 20)
passwordbox = Entry(root,width = 20)
buttonLogin = Button(root,text = "Login",width=10, command=LoginCommand)
canvas.create_window(230,100,window = label1)
canvas.create_window(230,150,window = label2)
canvas.create_window(400,100,window = usernamebox)
canvas.create_window(400,150,window = passwordbox)
canvas.create_window(400,200,window = buttonLogin)
canvas.pack()
root.mainloop()

R - Arguments for Graph API notifications subscription: error HTTP 405

I'm trying to create a subscription to the callRecords notifications with Graph API in R. I'm looking at this Microsoft page as a reference: https://learn.microsoft.com/en-us/graph/api/subscription-post-subscriptions?view=graph-rest-beta&tabs=http
Here is my code:
Subscribtion_Call <- AzureGraph::call_graph_endpoint(Tok, options = list(), api_version = Version, operation = "subscriptions", content_type = "application/json")
Subscription_Properties <- list(
changeType = "created,updated",
notificationUrl = "https://webhook.azurewebsites.net/notificationClient",
resource = "communications/callRecords",
expirationDateTime = "2022-04-09T11:00:00.0000000Z",
clientState = "SecretClientState"
)
Send_Subscription <- call_graph_url(Tok, Endpoint, body = Subscription_Properties, encode = "json",
content_type = "application/json",
http_verb = "POST",
http_status_handler = "message",
simplify = FALSE,
auto_refresh = TRUE
)
This gets me an HTTP 405 error as below:
> Subscribtion_Call <- AzureGraph::call_graph_endpoint(Tok, options = list(), api_version = Version, operation = "subscriptions", content_type = "application/json")
>
> Subscription_Properties <- list(
+ changeType = "created,updated",
+ notificationUrl = "https://webhook.azurewebsites.net/notificationClient",
+ resource = "communications/callRecords",
+ expirationDateTime = "2022-04-09T11:00:00.0000000Z",
+ clientState = "SecretClientState"
+ )
>
> Send_Subscription <- call_graph_url(Tok, Endpoint, body = Subscription_Properties, encode = "json",
+ content_type = "application/json",
+ http_verb = "POST",
+ http_status_handler = "message",
+ simplify = FALSE,
+ auto_refresh = TRUE
+ )
Method Not Allowed (HTTP 405). Failed to complete operation. Message:
.
If I change the http_verb to "GET" this is returned:
> Send_Subscription <- call_graph_url(Tok, Endpoint, body = Subscription_Properties, encode = "json",
+ content_type = "application/json",
+ http_verb = "GET",
+ http_status_handler = "message",
+ simplify = FALSE,
+ auto_refresh = TRUE
+ )
OK (HTTP 200). Failed to complete operation. Message:
.
>
What am I missing?
Thanks in advance for your help!

is it possible way to customize the sub resource api platform?

The goal was i aiming to is to change identifier from id of entity to JWT token that user has attached at specific path.
#ApiResource(
itemOperations = {
"get" ={
"security" = "is_granted('VIEW',object)",
"normalization_context" = {"groups" = {"read"}}
},
"put" = {
"security" = "is_granted('WRITE',object)",
"normalization_context" = {"groups" = {"get"}},
"denormalization_context" = {"groups" = {"put"}}
},
"api_users_cart_subresource" = {
"method" = "GET",
"path" = "/users/{id}/carts",
"security" = "is_granted('VIEW',object)",
"normalization_context" = {"groups" = {"user:cart"}}
}
},
collectionOperations = {
"post" = {
"denormalization_context" = {"groups" = {"post"}},
"normalization_context" = {"groups" = {"get"}}
},
"get" = {
"access_control" = "is_granted('ROLE_ADMIN')",
"normalization_context" = {"groups" = {"admin:read"}}
}
}
)
is it possible to change the path to /users/carts and return normalized data that belong to the user base from their token?
ps. sorry for my grammar

How to split values of a map in terraform to create lists?

I have a map variable with many values (NACL rules). I am trying to add rules accordingly
variable "rules" {
default = {
a = "200,false,tcp,allow,0.0.0.0/0,23,23"
b = "100,true,tcp,allow,0.0.0.0/0,1024,65535"
}
}
resource "aws_network_acl_rule" "bar" {
network_acl_id = "<id>"
rule_number = "${split(",",element(values(var.rules),count.index))[0]}"
egress = "${split(",",element(values(var.rules),count.index))[1]}"
protocol = "${split(",",element(values(var.rules),count.index))[2]}"
rule_action = "${split(",",element(values(var.rules),count.index))[3]}"
cidr_block = "${split(",",element(values(var.rules),count.index))[4]}"
from_port = "${split(",",element(values(var.rules),count.index))[5]}"
to_port = "${split(",",element(values(var.rules),count.index))[6]}"
count = "${length(values(var.rules))}"
}
Error:
expected "}" but found "["
Since maps with lists as values aren't supported, I am trying to split the values and iterate
Another option, easier to read, is with lookup():
variable "rules" {
default = [
{
rule_number = 200
egress = false
protocol = "tcp"
rule_action = "allow"
cidr_block = "0.0.0.0/0"
from_port= 23
to_port = 23
},
{
rule_number = 100
egress = true
procotol = "tcp"
rule_action = "allow"
cidr_block = "0.0.0.0/0"
from_port = 1024
to_port = 65535
},
]
}
resource "aws_network_acl_rule" "bar" {
count = "${length(var.rules)}"
network_acl_id = "<id>"
rule_number = "${lookup(var.rules[count.index], "rule_number")}"
egress = "${lookup(var.rules[count.index], "egress")}"
protocol = "${lookup(var.rules[count.index], "protocol")}"
rule_action = "${lookup(var.rules[count.index], "rule_action")}"
cidr_block = "${lookup(var.rules[count.index], "cidr_block")}"
from_port = "${lookup(var.rules[count.index], "from_port")}"
to_port = "${lookup(var.rules[count.index], "to_port")}"
}
Here is a simpler way to deal with the map rules
variable "rules" {
default = {
"0" = "200,false,tcp,allow,0.0.0.0/0,23,23"
"1" = "100,true,tcp,allow,0.0.0.0/0,1024,65535"
}
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
resource "aws_network_acl" "bar" {
vpc_id = "${aws_vpc.main.id}"
}
resource "aws_network_acl_rule" "bar" {
count = "${length(var.rules)}"
network_acl_id = "${aws_network_acl.bar.id}"
rule_number = "${element(split(",",var.rules[count.index]),0)}"
egress = "${element(split(",",var.rules[count.index]),1)}"
protocol = "${element(split(",",var.rules[count.index]),2)}"
rule_action = "${element(split(",",var.rules[count.index]),3)}"
cidr_block = "${element(split(",",var.rules[count.index]),4)}"
from_port = "${element(split(",",var.rules[count.index]),5)}"
to_port = "${element(split(",",var.rules[count.index]),6)}"
}
If you insist to use old map, key is "a,b,...", you need to adjust resource to
variable "rules" {
default = {
"a" = "200,false,tcp,allow,0.0.0.0/0,23,23"
"b" = "100,true,tcp,allow,0.0.0.0/0,1024,65535"
}
}
resource "aws_network_acl_rule" "bar" {
count = "${length(var.rules)}"
network_acl_id = "${aws_network_acl.bar.id}"
rule_number = "${element(split(",",element(values(var.rules),count.index)),0)}"
egress = "${element(split(",",element(values(var.rules),count.index)),1)}"
protocol = "${element(split(",",element(values(var.rules),count.index)),2)}"
rule_action = "${element(split(",",element(values(var.rules),count.index)),3)}"
cidr_block = "${element(split(",",element(values(var.rules),count.index)),4)}"
from_port = "${element(split(",",element(values(var.rules),count.index)),5)}"
to_port = "${element(split(",",element(values(var.rules),count.index)),6)}"
}

How to send different contents to different recipients with mailR

I am trying to send different contents to different recipients, but all recipients get all contents. Any help?
library(mailR)
msg<- data.frame(recipients=c("first#mail.com","second#mail.com","third#mail.com"),
messages=c("firstmsg","secondmsg","thirdmsg"))
for ( i in msg$recipients)
{
for (j in msg$messages) {
send.mail(from="myemail#mail.com",
to= i,
body = j,
subject = "subject",
encoding = "utf-8",
smtp= list(host.name = "smtp.gmail.com", port = 465,
user.name = "myemail#mail.com", passwd = "mypassword", ssl = TRUE),
authenticate = TRUE, send = TRUE, attach.files=NULL, debug = FALSE)
}
}
You are using a double loop which will go through each value of j for each value of i in your loop. One approach would be to use list indexing:
msg<-data.frame(recipients=c("first#mail.com","second#mail.com",
"third#mail.com"),messages=c("firstmsg","secondmsg","thirdmsg"))
for i in 1:nrow(msg)
{
send.mail(from="myemail#mail.com",
to= msg$recipients[i],
body = msg$message[i],
subject = "subject",
encoding = "utf-8",
smtp= list(host.name = "smtp.gmail.com", port = 465,
user.name = "myemail#mail.com", passwd = "mypassword", ssl = TRUE),
authenticate = TRUE, send = TRUE, attach.files=NULL, debug = FALSE)
}

Resources