globalstate.py 10.5 KB
Newer Older
1 2
#!/usr/bin/env python

3 4
from __future__ import print_function

5 6 7 8
import sys
import os
import glob
import json
9
from six.moves import configparser
10 11
import time
from datetime import datetime
12 13 14 15
import base64
import hashlib
import PyRSS2Gen

16 17
from slapos.util import bytes2str, str2bytes

18
def getKey(item):
19
  return item.source.name
20

21
class MonitorFeed(object):
22 23 24 25 26 27 28 29 30 31 32

  def __init__(self, instance_name, hosting_name,
      public_url, private_url, feed_url):
    self.rss_item_list = []
    self.report_date = datetime.utcnow()
    self.instance_name = instance_name
    self.hosting_name = hosting_name
    self.public_url = public_url
    self.private_url = private_url
    self.feed_url = feed_url

33 34 35 36
  def appendItem(self, item_dict, has_string=""):
    event_date = item_dict['result']['change-date']
    report_date = item_dict['result']['date']
    description = item_dict['result'].get('message', '')
37 38
    guid = base64.b64encode(str2bytes("%s, %s, %s, %s" % (self.hosting_name,
      item_dict['title'], has_string, event_date)))
39 40 41 42
    rss_item = PyRSS2Gen.RSSItem(
      categories = [item_dict['status']],
      source = PyRSS2Gen.Source(item_dict['title'], self.public_url),
      title = '[%s] %s' % (item_dict['status'], item_dict['title']),
43
      description = "\n%s" % (description,),
44
      link = self.private_url,
45
      pubDate = event_date,
46
      guid = PyRSS2Gen.Guid(bytes2str(guid), isPermaLink=False)
47 48 49
    )
    self.rss_item_list.append(rss_item)

50
  def generateRSS(self, output_file):
51
    ### Build the rss feed
52
    # try to keep the list in the same order
53 54 55 56 57 58 59 60
    sorted(self.rss_item_list, key=getKey)
    rss_feed = PyRSS2Gen.RSS2 (
      title = self.instance_name,
      link = self.feed_url,
      description = self.hosting_name,
      lastBuildDate = self.report_date,
      items = self.rss_item_list
    )
61

62 63
    with open(output_file, 'w') as frss:
      frss.write(rss_feed.to_xml())
64 65

def generateStatisticsData(stat_file_path, content):
66 67
  # csv document for success/error statictics
  if not os.path.exists(stat_file_path) or os.stat(stat_file_path).st_size == 0:
68 69 70 71 72 73 74 75
    with open(stat_file_path, 'w') as fstat:
      data_dict = {
        "date": time.time(),
        "data": ["Date, Success, Error, Warning"]
      }
      fstat.write(json.dumps(data_dict))

  current_state = ''
76
  if 'state' in content:
77 78 79 80
    current_state = '%s, %s, %s, %s' % (
      content['date'],
      content['state']['success'],
      content['state']['error'],
81
      '')
82 83 84 85 86 87 88 89 90

  # append to file
  if current_state:
    with open (stat_file_path, mode="r+") as fstat:
      fstat.seek(0,2)
      position = fstat.tell() -2
      fstat.seek(position)
      fstat.write('%s}' % ',"{}"]'.format(current_state))

91 92 93 94
def writeDocumentList(folder_path):
  # Save document list in a file called _document_list
  public_document_list = [os.path.splitext(file)[0]
                for file in os.listdir(folder_path) if file.endswith('.json')]
95

96 97
  with open(os.path.join(folder_path, '_document_list'), 'w') as lfile:
    lfile.write('\n'.join(public_document_list))
98

99 100 101
def generateMonitoringData(config, public_folder, private_folder, public_url,
    private_url, feed_url):
  feed_output = os.path.join(public_folder, 'feed')
102
  # search for all status files
103
  file_list = list(filter(
104 105
    os.path.isfile,
    glob.glob("%s/promise/*.status.json" % public_folder)
106
  ))
107

108 109 110 111 112 113 114
  promises_status_file = os.path.join(private_folder, '_promise_status')
  previous_state_dict = {}
  new_state_dict = {}
  error = success = 0
  monitor_feed = MonitorFeed(
    config.get('monitor', 'title'),
    config.get('monitor', 'root-title'),
115 116 117
    public_url,
    private_url,
    feed_url)
118 119 120 121 122 123 124 125

  if os.path.exists(promises_status_file):
    with open(promises_status_file) as f:
      try:
        previous_state_dict = json.loads(f.read())
      except ValueError:
        pass

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
  # clean up stale history files
  expected_history_json_name_list = [
    os.path.basename(q).replace('status.json', 'history.json') for q in file_list]
  cleanup_history_json_path_list = []
  for history_json_name in [q for q in os.listdir(public_folder) if q.endswith('history.json')]:
    if history_json_name not in expected_history_json_name_list:
      cleanup_history_json_path_list.append(os.path.join(public_folder, history_json_name))
  for cleanup_path in cleanup_history_json_path_list:
    try:
      os.unlink(cleanup_path)
    except Exception:
      print('ERROR: Failed to remove stale %s' % (cleanup_path,))
    else:
      print('OK: Removed stale %s' % (cleanup_path,))

141 142 143 144
  for file in file_list:
    try:
      with open(file, 'r') as temp_file:
        tmp_json = json.loads(temp_file.read())
145 146 147 148 149 150 151 152

      if tmp_json['result']['failed']:
        promise_status = "ERROR"
        error += 1
      else:
        promise_status = "OK"
        success += 1
      tmp_json['result']['change-date'] = tmp_json['result']['date']
153
      if tmp_json['name'] in previous_state_dict:
154 155 156 157 158
        status, change_date, _ = previous_state_dict[tmp_json['name']]
        if promise_status == status:
          tmp_json['result']['change-date'] = change_date

      tmp_json['status'] = promise_status
159 160
      message_hash = hashlib.md5(
        str2bytes(tmp_json['result'].get('message', ''))).hexdigest()
161 162 163 164 165 166 167 168 169 170 171 172
      new_state_dict[tmp_json['name']] = [
        promise_status,
        tmp_json['result']['change-date'],
        message_hash
      ]
      monitor_feed.appendItem(tmp_json, message_hash)
      savePromiseHistory(
        tmp_json['title'],
        tmp_json,
        previous_state_dict.get(tmp_json['name']),
        public_folder
      )
173
    except ValueError as e:
174
      # bad json file
175
      print("ERROR: Bad json file at: %s\n%s" % (file, e))
176 177
      continue

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
  with open(promises_status_file, "w") as f:
    json.dump(new_state_dict, f)

  monitor_feed.generateRSS(feed_output)
  return error, success

def savePromiseHistory(promise_name, state_dict, previous_state_list,
    history_folder):
  if not os.path.exists(history_folder) and os.path.isdir(history_folder):
    self.logger.warning('Bad promise history folder, history is not saved...')
    return

  history_file = os.path.join(
    history_folder,
    '%s.history.json' % promise_name
  )

  # Remove useless informations
  result = state_dict.pop('result')
  state_dict.update(result)
  state_dict.pop('path', '')
  state_dict.pop('type', '')
  if not os.path.exists(history_file) or not os.stat(history_file).st_size:
    with open(history_file, 'w') as f:
      data_dict = {
        "date": time.time(),
        "data": [state_dict]
      }
      json.dump(data_dict, f)
  else:
    if previous_state_list is not None:
      _, change_date, checksum = previous_state_list
210
      current_sum = hashlib.md5(str2bytes(state_dict.get('message', ''))).hexdigest()
211 212 213 214 215 216 217 218 219 220 221 222 223 224
      if state_dict['change-date'] == change_date and \
          current_sum == checksum:
        # Only save the changes and not the same info
        return

    state_dict.pop('title', '')
    state_dict.pop('name', '')
    with open (history_file, mode="r+") as f:
      f.seek(0,2)
      f.seek(f.tell() -2)
      f.write('%s}' % ',{}]'.format(json.dumps(state_dict)))

def run(monitor_conf_file):

225
  config = configparser.ConfigParser()
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
  config.read(monitor_conf_file)

  base_folder = config.get('monitor', 'private-folder')
  status_folder = config.get('monitor', 'public-folder')
  base_url = config.get('monitor', 'base-url')
  related_monitor_list = config.get("monitor", "monitor-url-list").split()
  statistic_folder = os.path.join(base_folder, 'documents')
  # need webdav to update parameters
  parameter_file = os.path.join(base_folder, 'config', '.jio_documents', 'config.json')

  public_url = "%s/share/public/" % base_url
  private_url = "%s/share/private/" % base_url
  feed_url = "%s/public/feed" % base_url
  status = 'OK'
  global_state_file = os.path.join(base_folder, 'monitor.global.json')
  public_state_file = os.path.join(status_folder, 'monitor.global.json')
242
  report_date = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S+0000')
243 244 245

  error, success = generateMonitoringData(config, status_folder, base_folder,
                                          public_url, private_url, feed_url)
246 247 248 249
  if error:
    status = 'ERROR'

  global_state_dict = dict(
250 251 252
    status=status,
    state={
      'error': error,
253
      'success': success
254
    },
255 256
    type='global', # bwd compatibility
    portal_type='Software Instance',
257
    date=report_date,
258
    _links={"rss_url": {"href": feed_url},
259
            "public_url": {"href": public_url},
260 261
            "private_url": {"href": private_url},
            "related_monitor": []
262 263 264 265 266 267 268
          },
    data={'state': 'monitor_state.data',
          'process_state': 'monitor_process_resource.status',
          'process_resource': 'monitor_resource_process.data',
          'memory_resource': 'monitor_resource_memory.data',
          'io_resource': 'monitor_resource_io.data',
          'monitor_process_state': 'monitor_resource.status'},
269 270 271 272 273 274 275 276
    title=config.get('monitor', 'title'),
    specialise_title=config.get('monitor', 'root-title'),
    aggregate_reference=config.get('promises', 'computer-id'),
    ipv4=config.get('promises', 'ipv4'),
    ipv6=config.get('promises', 'ipv6'),
    software_release=config.get('promises', 'software-release'),
    software_type=config.get('promises', 'software-type'),
    partition_id=config.get('promises', 'partition-id'),
277 278 279 280 281
  )

  if not global_state_dict['title']:
    global_state_dict['title'] = 'Instance Monitoring'

282
  if related_monitor_list:
283
    global_state_dict['_links']['related_monitor'] = [{'href': "%s/share/public" % url}
284 285 286 287 288 289 290 291 292 293
                          for url in related_monitor_list]

  if os.path.exists(parameter_file):
    with open(parameter_file) as cfile:
      global_state_dict['parameters'] = json.loads(cfile.read())

  # Public information with the link to private folder
  public_state_dict = dict(
    status=status,
    date=report_date,
294
    _links={'monitor': {'href': '%s/share/private/' % base_url}},
295 296
    title=global_state_dict.get('title', ''),
    specialise_title=global_state_dict.get('specialise_title', ''),
297 298 299 300 301 302 303 304 305
  )
  public_state_dict['_links']['related_monitor'] = global_state_dict['_links'].get('related_monitor', [])

  with open(global_state_file, 'w') as fglobal:
    fglobal.write(json.dumps(global_state_dict))

  with open(public_state_file, 'w') as fpglobal:
    fpglobal.write(json.dumps(public_state_dict))

306 307 308 309
  # write list of files
  writeDocumentList(status_folder)
  writeDocumentList(base_folder)
  writeDocumentList(statistic_folder)
310

311 312
  generateStatisticsData(
    os.path.join(statistic_folder, 'monitor_state.data.json'),
313 314
    global_state_dict
  )
315 316 317 318

  return 0

def main():
319 320
  if len(sys.argv) < 2:
    print("Usage: %s <monitor_conf_path>" % sys.argv[0])
321
    sys.exit(2)
322
  sys.exit(run(sys.argv[1]))