Commit 8877b0e4 authored by James Coyle's avatar James Coyle

Merge branch 'james-dev' into 'master'

Implemented console logging for send stats

See merge request !10
parents e17f91ba a135d92c
Pipeline #1154 failed with stages
in 4 seconds
import os
import re
import sys
import subprocess
from storjstatus import version
import logging
CONFIGFILE = '/etc/storjstatus/config.json'
APIENDPOINT = 'https://www.storjstatus.com/api/'
log = None
def setup_env():
global ENV
......@@ -18,6 +21,25 @@ def get_version():
return version.__version__
def setup_logger():
global log
if (log == None):
ssLog = logging.getLogger('storjstatus')
ssLog.setLevel(logging.DEBUG)
ssLog.propagate = False
logFormatter = logging.Formatter('%(asctime)s %(levelname)8s %(message)s', datefmt='%d/%m/%Y %I:%M:%S %p')
ch = logging.StreamHandler()
ch.setFormatter(logFormatter)
ssLog.addHandler(ch)
log = ssLog
def cleanup_json(json):
json = re.sub(r'(?<!https:)//.*', '', json, flags = re.MULTILINE)
json = json.strip().replace('\r', '').replace('\n', '')
......@@ -30,7 +52,6 @@ def check_strojshare():
if 'storjshare' in result[0].decode('utf-8'):
try:
result = subprocess_result(['storjshare', '-V'])
print("Found Storjshare : " + result[0].decode('utf-8').strip())
except FileNotFoundError:
return "fail", "Unable to find storjshare binary in PATH"
......
......@@ -12,6 +12,7 @@ from crontab import CronTab
from os import scandir
from storjstatus import storjstatus_common
### Vars
APIKEY = None
APISECRET = None
......@@ -22,6 +23,8 @@ def init_send():
storjstatus_common.setup_env()
storjstatus_common.setup_logger()
checks();
load_settings()
......@@ -33,7 +36,7 @@ def init_send():
for node in storj_json:
# Get values from bridge
print("Processing nodeid: " + node['id'])
storjstatus_common.log.info("Processing nodeid: " + node['id'])
# Check to see if a config exists for this node, if not, ignore it.
if node['configPath'] in conf_json:
......@@ -62,7 +65,7 @@ def init_send():
}
json_nodes.append(json_node)
else:
print_warning("No config file found for Node: " + node['id'] + ". Data for this node will not be sent.")
storjstatus_common.log.warning("No config file found for Node: %s. Data for this node will not be sent.", node['id'])
json_request = {
'serverId': SERVERGUID,
......@@ -71,14 +74,14 @@ def init_send():
'storjshareVersion': storjshare_version(),
'nodes': json_nodes
}
print_info('\nJSON Request...\n'+json.dumps(json_request, indent=4, sort_keys=True))
storjstatus_common.log.info('JSON Request:\n' + json.dumps(json_request, indent=4, sort_keys=True))
headers = {'content-type': 'application/json', 'api-key' : APIKEY, 'api-secret' : APISECRET}
try:
resp = requests.post(storjstatus_common.APIENDPOINT + "stats", json=json_request, headers=headers)
if not resp.status_code == 200:
print_error("Value returned when posting stats : " + resp.json()['description'])
except Exception as e:
print(str(e))
storjstatus_common.log.error(str(e))
print_error("Error sending report to: " + storjstatus_common.APIENDPOINT + "stats. Please try again later")
......@@ -134,7 +137,7 @@ def config_json():
for f in filenames:
# consume config file
with open(os.path.join(root, f), 'r', encoding = "ISO-8859-1") as f_open:
print_info("Parsing config file: " + os.path.join(root, f))
storjstatus_common.log.debug("Parsing config file: " + os.path.join(root, f))
node = {}
f_data = f_open.read()
f_clean = storjstatus_common.cleanup_json(f_data)
......@@ -148,13 +151,13 @@ def config_json():
node['storageAllocation'] = f_json['storageAllocation']
nodes[f_json['storagePath']] = node
print_info("Found valid config for " + f_json['storagePath'])
storjstatus_common.log.info("Found valid config for " + f_json['storagePath'])
except KeyError:
print_warning('JSON config file ' + f + ' invalid. Please check your config.')
storjstatus_common.log.warning('JSON config file ' + f + ' invalid. Please check your config.')
except json.JSONDecodeError:
print_warning('JSON config file ' + f + ' invalid. Please check your config.')
storjstatus_common.log.warning('JSON config file ' + f + ' invalid. Please check your config.')
except:
print_warning("File " + f + " is not a valid Storjshare JSON config file")
storjstatus_common.log.warning("File " + f + " is not a valid Storjshare JSON config file")
if nodes:
return nodes
......@@ -190,21 +193,9 @@ def load_settings():
def print_error(error_message):
print()
print("ERROR : " + error_message)
print()
storjstatus_common.log.error(error_message)
exit(1)
def print_warning(warning_message):
print()
print("WARNING : " + warning_message)
print()
def print_info(warning_message):
print()
print("INFO : " + warning_message)
print()
if __name__ == '__main__':
init_send()
__version__ = '0.2.5'
__version__ = '0.2.6'
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment