Exemplo n.º 1
0
 def get(self, template_id):
     logger.debug("top of GET /templates/{template_id}")
     template_result, msg = kapacitor.get_template(template_id)
     logger.debug(str(template_result))
     result = meta.strip_meta(template_result)
     logger.debug(result)
     return utils.ok(result=result, msg=msg)
Exemplo n.º 2
0
    def post(self, project_id):
        # validator = RequestValidator(utils.spec)
        # result = validator.validate(FlaskOpenAPIRequest(request))
        # if result.errors:
        #     raise errors.ResourceError(msg=f'Invalid POST data: {result.errors}.')
        # validated_params = result.parameters
        # validated_body = result.body
        # logger.debug(f"validated_body: {dir(validated_body)}")

        #need to add check for project permission & project exists before chords insertion
        logger.debug('omg')
        logger.debug(request.json)
        body = request.json
        postSite = ChordsSite("", body['site_name'], body['latitude'],
                              body['longitude'], body['elevation'],
                              body['description'])
        resp, msg = chords.create_site(postSite)
        if msg == "Site created":
            site_result, message = meta.create_site(project_id, resp['id'],
                                                    body)
            #resp['results']=meta_resp['results']
            logger.debug('success')
            logger.debug(site_result)
            result = meta.strip_meta(site_result)
            #meta_resp, getmsg = meta.get_site(project_id, resp['id'])
        else:
            logger.debug('failed')
            message = msg
            result = ''
        return utils.ok(result=result, msg=message)
Exemplo n.º 3
0
 def post(self):
     logger.debug("top of POST /tempates")
     body = request.json
     #TODO need to check our permissions
     result, msg = kapacitor.create_template(body)
     logger.debug(result)
     return utils.ok(result=meta.strip_meta(result), msg=msg)
Exemplo n.º 4
0
 def get(self, channel_id):
     logger.debug("top of GET /channels/{channel_id}")
     channel_result, msg = kapacitor.get_channel(channel_id)
     logger.debug(channel_result)
     result = meta.strip_meta(channel_result)
     logger.debug(result)
     return utils.ok(result=result, msg=msg)
Exemplo n.º 5
0
def create_alert(channel, req_data):
    actor_id = channel['triggers_with_actions'][0]['action']['actor_id']
    logger.debug('actor_id:' + actor_id)
    abaco_base_url = channel['triggers_with_actions'][0]['action'][
        'abaco_base_url']
    abaco_nonce = channel['triggers_with_actions'][0]['action']['nonces']
    abaco_url = abaco_base_url + '/actors/v2/' + actor_id + '/messages?x-nonce=' + abaco_nonce
    logger.debug('abaco_url: ' + abaco_url)

    #prepare request for abaco
    headers = {'accept': 'application/json'}
    message_data = {}
    message_data['message'] = req_data
    message_data['message']['channel_id'] = channel['channel_id']

    result = meta.fetch_instrument_index(
        channel["triggers_with_actions"][0]['inst_ids'][0])
    message_data['message']['project_id'] = result[0]['project_id']
    message_data['message']['site_id'] = result[0]['site_id']
    message_data['message']['inst_id'] = result[0]['instrument_id']

    cond_key = channel['triggers_with_actions'][0]['condition']['key'].split(
        ".")
    message_data['message']['var_id'] = cond_key[1]
    logger.debug('message_data: ' + str(message_data))

    try:
        res = requests.post(abaco_url,
                            json=message_data,
                            headers=headers,
                            verify=False)
    except Exception as e:
        msg = f"Got exception trying to post message to Abaco actor: {actor_id}; exception: {e}"
        raise errors.BaseTapyException(msg=msg, request=res.request)

    logger.debug('abaco response:' + res.text)
    logger.debug('abaco response status code:' + str(res.status_code))

    if res.status_code == 200:
        abaco_res = json.loads(res.text)
        #TODO create alert summary and alert object with all details
        execution_id = abaco_res['result']['executionId']
        alert = {}
        alert['alert_id'] = str(uuid.uuid4())
        alert['channel_name'] = channel['channel_name']
        alert['channel_id'] = channel['channel_id']
        alert['actor_id'] = actor_id
        alert['execution_id'] = execution_id
        alert['message'] = req_data['message']
        alert['create_time'] = str(datetime.datetime.utcnow())
        logger.debug(alert)
        alert_result, msg = meta.create_alert(alert)
        logger.debug(alert_result)
        result = meta.strip_meta(alert_result)
        logger.debug(result)
        return result, msg
    else:
        msg = f"Abaco Actor: {actor_id} unable to perform the execution on the message: {message_data}. Check the Actor Status and the message"
        raise errors.ResourceError(msg=msg)
Exemplo n.º 6
0
 def put(self, project_id, site_id):
     body = request.json
     putSite = ChordsSite(site_id, body['site_name'], body['latitude'],
                          body['longitude'], body['elevation'],
                          body['description'])
     site_result, msg = meta.update_site(project_id, site_id, body)
     result = meta.strip_meta(site_result)
     chord_result, chord_msg = chords.update_site(site_id, putSite)
     return utils.ok(result=result, msg=msg)
Exemplo n.º 7
0
 def post(self):
     logger.debug(request.json)
     body = request.json
     proj_result, msg = meta.create_project(body)
     logger.debug(proj_result)
     result = meta.strip_meta(proj_result)
     #resp['status'] = result['status']
     #logger.debug(meta_resp['status'])
     #logger.debug(resp)
     return utils.ok(result, msg=msg)
Exemplo n.º 8
0
 def get(self, project_id, site_id, instrument_id):
     result = []
     msg = ""
     logger.debug("top of GET /measurements")
     #inst_result = meta.get_instrument(project_id,site_id,instrument_id)
     site, msg = meta.get_site(project_id, site_id)
     logger.debug(site)
     replace_cols = {}
     for inst in site['instruments']:
         logger.debug(inst)
         if inst['inst_id'] == instrument_id:
             instrument = inst
             logger.debug(inst)
             for v in inst['variables']:
                 logger.debug(v)
                 replace_cols[str(v['chords_id'])] = v['var_id']
     js = influx.query_measurments([{
         "inst": str(instrument['chords_id'])
     }, {
         "start_date":
         request.args.get('start_date')
     }, {
         "end_date": request.args.get('end_date')
     }])
     logger.debug(js)
     if len(js) > 1 and len(js['series']) > 0:
         df = pd.DataFrame(js['series'][0]['values'],
                           columns=js['series'][0]['columns'])
         pv = df.pivot(index='time', columns='var', values=['value'])
         df1 = pv
         df1.columns = df1.columns.droplevel(0)
         df1 = df1.reset_index().rename_axis(None, axis=1)
         df1.rename(columns=replace_cols, inplace=True)
         df1.set_index('time', inplace=True)
         if request.args.get('format') == "csv":
             logger.debug("CSV")
             # csv_response = Response(result, mimetype="text/csv")
             # si = StringIO.StringIO()
             #cw = csv.write(si)
             # cw.writerows(csvList)
             output = make_response(df1.to_csv())
             output.headers[
                 "Content-Disposition"] = "attachment; filename=export.csv"
             output.headers["Content-type"] = "text/csv"
             return output
         else:
             result = json.loads(df1.to_json())
             result['measurements_in_file'] = len(df1.index)
             result['instrument'] = instrument
             site.pop('instruments', None)
             result['site'] = meta.strip_meta(site)
             return utils.ok(result=result, msg="Measurements Found")
     else:
         return utils.ok(result=[], msg="No Measurements Founds")
Exemplo n.º 9
0
    def put(self, channel_id):
        logger.debug("top of PUT /channels/{channel_id}")

        body = request.json
        # TODO need to check the user permission to update channel status
        #if body['channel_id'] != channel_id:
        #    raise errors.ResourceError(msg=f'Invalid PUT data: {body}. You cannot change channel id')
        result = {}
        try:
            result, msg = kapacitor.update_channel(channel_id, body)
        except Exception as e:
            msg = f"Could not update the channel: {channel_id}; exception: {e}"

        logger.debug(result)
        return utils.ok(result=meta.strip_meta(result), msg=msg)
Exemplo n.º 10
0
 def post(self, channel_id):
     logger.debug("top of POST /channels/{channel_id}")
     body = request.json
     # TODO need to check the user permission to update channel status
     # TODO Convert to Status Enum
     if body['status'] == 'ACTIVE':
         body['status'] = 'enabled'
     elif body['status'] == 'INACTIVE':
         body['status'] = 'disabled'
         logger.debug(body)
     else:
         raise errors.ResourceError(msg=f'Invalid POST data: {body}.')
     result = {}
     try:
         result, msg = kapacitor.update_channel_status(channel_id, body)
     except Exception as e:
         logger.debug(type(e))
         logger.debug(e.args)
         msg = f"Could not update the channel status: {channel_id}; exception: {e} "
         logger.debug(msg)
     logger.debug(result)
     if result:
         return utils.ok(result=meta.strip_meta(result), msg=msg)
     return utils.error(result=result, msg=msg)
Exemplo n.º 11
0
 def put(self, project_id):
     body = request.json
     proj_result, msg = meta.update_project(project_id, body)
     result = meta.strip_meta(proj_result)
     return utils.ok(result=result, msg=msg)
Exemplo n.º 12
0
 def get(self, project_id):
     proj_result, msg = meta.get_project(project_id)
     result = meta.strip_meta(proj_result)
     logger.debug(result)
     return utils.ok(result=result, msg=msg)
Exemplo n.º 13
0
 def get(self, project_id, site_id):
     site_result, msg = meta.get_site(project_id, site_id)
     result = meta.strip_meta(site_result)
     logger.debug(result)
     return utils.ok(result=result, msg=msg)