def update_ports_status(oneview_client):
    allPortStats = get_port_statistics(oneview_client)

    logging.info("Updating all ports status in logfile.")
    data = {}
    for interconnect in allPortStats:
        data['name'] = interconnect["interconnectName"]

        for port in interconnect['linkedPorts']:
            data['timestamp'] = datetime.now().isoformat()[:-3] + "Z"
            data['portName'] = port["portName"]
            data['status'] = port["members"]["Status"]
            data['speed'] = port["members"]["Speed"]
            data['adapterPort'] = port["members"]["adopterPort"]
            data['recv_octets'] = port["members"]["IfInOctets"]
            data['transmit_octets'] = port["members"]["IfOutOctets"]

            msg = "<{status}> {timestamp} {oneview_ip} oneview PortStats [{interconnect}] [{port}|Transmit={transmit}|Receive={receive}|Speed={speed}|AdaptorPort={adapter}]\n".format(
                timestamp=data["timestamp"],
                status=ovlog.syslogStatusMap[data["status"].upper()],
                interconnect=data['name'],
                port=data['portName'],
                transmit=data["transmit_octets"],
                receive=data["recv_octets"],
                speed=data['speed'],
                adapter=data['adapterPort'],
                oneview_ip=oneview_client.connection.get_host())
            ovlog.writeToSyslog(msg)
            sleep(0.3)
def update_server_stats(oneview_client):
    servers = oneview_client.server_hardware.get_all()
    for server in servers:
        serverStatsResponse = oneview_client.server_hardware.get_utilization(
            server["uri"])
        fullMetrics = serverStatsResponse["metricList"]
        serverAllStats = []
        serverStats = {}
        for metrics in fullMetrics:
            serverStats["metricName"] = metrics["metricName"]
            epochTimeStamp = metrics["metricSamples"][0][
                0] / 1000  # Timestamp is in millisec.
            serverStats["timeStamp"] = strftime('%Y-%m-%dT%H:%M:%SZ',
                                                localtime(epochTimeStamp))
            serverStats["value"] = metrics["metricSamples"][0][1]
            sleep(3)
            serverAllStats.append(serverStats)
            serverStats = {}

        if serverAllStats:
            status = (
                "<6> {timestamp} {ipAddr} oneview ServerStats [{serverName}] "
                "[AmbientTemperature={ambTemp} dec C|AveragePower={avgPower} watts|"
                "CpuAverageFreq={cpuAvgFreq} Hz|CpuUtilization={cpuUtil} %|"
                "PeakPower={peakPower} watts|PowerCap={powerCap}]\n").format(
                    timestamp=serverAllStats[0]["timeStamp"],
                    ipAddr=oneview_client.connection.get_host(),
                    serverName=server["name"],
                    ambTemp=serverAllStats[0]["value"],
                    avgPower=serverAllStats[1]["value"],
                    cpuAvgFreq=serverAllStats[2]["value"],
                    cpuUtil=serverAllStats[3]["value"],
                    peakPower=serverAllStats[4]["value"],
                    powerCap=serverAllStats[5]["value"])
            ovlog.writeToSyslog(status)
def update_host_status(hostName,
                       status,
                       description='Updating status in logfile.',
                       corrAction='None'):

    # Empty JSON to hold all relevant information
    data = {}
    status = status.upper()
    data["timestamp"] = datetime.now().isoformat()[:-3] + "Z"
    data["resource_name"] = hostName
    data["correctiveAction"] = corrAction

    if status in nodeStatusMap:
        data["description"] = description
        data["status"] = status
    else:
        logging.error("Check host status :- " + hostName + ". Its not OK.")
        data["description"] = 'Node not in valid status. Check. '

        # Node unreachable
        data["status"] = "UNKNOWN"

    msg = "<{status}> {timestamp} {oneview_ip} oneview NodeStats [{hostname}] [{action}|{model}|None]\n".format(
        timestamp=data["timestamp"],
        status=ovlog.syslogStatusMap[data["status"].upper()],
        hostname=hostName,
        model=data["description"],
        action=data["correctiveAction"],
        oneview_ip=oneview_client.connection.get_host())

    ovlog.writeToSyslog(msg)
def process_enclosure_stats(enclName, URI, oneview_client):
    enclPowerStats = oneview_client.enclosures.get_utilization(URI)
    fullMetrics = enclPowerStats["metricList"]
    allEnclosuresStats = []
    encStats = {}
    for metrics in fullMetrics:
        encStats["metricName"] = metrics["metricName"]
        epochTimeStamp = metrics["metricSamples"][0][
            0] / 1000  # Timestamp is in millisec.
        encStats["timeStamp"] = strftime('%Y-%m-%dT%H:%M:%SZ',
                                         localtime(epochTimeStamp))
        encStats["value"] = metrics["metricSamples"][0][1]
        allEnclosuresStats.append(encStats)
        encStats = {}

    if allEnclosuresStats:
        status = (
            "<6> {timestamp} {hostname} oneview EnclosureStats [{encName}] "
            "[AmbientTemperature={ambTemp} dec C|AveragePower={avgPower} watts|"
            "PeakPower={peakPower} watts]\n").format(
                timestamp=allEnclosuresStats[0]["timeStamp"],
                hostname=oneview_client.connection.get_host(),
                encName=enclName,
                ambTemp=allEnclosuresStats[0]["value"],
                avgPower=allEnclosuresStats[1]["value"],
                peakPower=allEnclosuresStats[2]["value"])
        ovlog.writeToSyslog(status)