<s> import calendar <EOL> from decimal import Decimal <EOL> import logging <EOL> import datetime <EOL> from celery import shared_task <EOL> from django . db import transaction , IntegrityError <EOL> from nodeconductor . iaas . models import Instance , InstanceSlaHistory <EOL> from nodeconductor . monitoring . zabbix . api_client import ZabbixApiClient <EOL> from nodeconductor . monitoring . zabbix . errors import ZabbixError <EOL> logger = logging . getLogger ( __name__ ) <EOL> def add_months ( source_date , months ) : <EOL> month = source_date . month - <NUM_LIT:1> + months <EOL> year = source_date . year + month / <NUM_LIT:12> <EOL> month = month % <NUM_LIT:12> + <NUM_LIT:1> <EOL> day = min ( source_date . day , calendar . monthrange ( year , month ) [ <NUM_LIT:1> ] ) <EOL> return datetime . datetime . strptime ( '<STR_LIT>' % ( day , month , year ) , '<STR_LIT>' ) <EOL> @ shared_task <EOL> def update_instance_sla ( sla_type ) : <EOL> if sla_type not in ( '<STR_LIT>' , '<STR_LIT>' ) : <EOL> logger . error ( '<STR_LIT>' % sla_type ) <EOL> return <EOL> dt = datetime . datetime . now ( ) <EOL> if sla_type == '<STR_LIT>' : <EOL> period = dt . year <EOL> start_time = int ( datetime . datetime . strptime ( '<STR_LIT>' % dt . year , '<STR_LIT>' ) . strftime ( "<STR_LIT:%s>" ) ) <EOL> else : <EOL> period = '<STR_LIT>' % ( dt . year , dt . month ) <EOL> month_start = datetime . datetime . strptime ( '<STR_LIT>' % ( dt . month , dt . year ) , '<STR_LIT>' ) <EOL> start_time = int ( month_start . strftime ( "<STR_LIT:%s>" ) ) <EOL> end_time = int ( dt . strftime ( "<STR_LIT:%s>" ) ) <EOL> instances = Instance . objects . exclude ( <EOL> state__in = [ Instance . States . DELETING , Instance . States . PROVISIONING_SCHEDULED , Instance . States . PROVISIONING ] <EOL> ) . exclude ( backend_id = '<STR_LIT>' ) <EOL> zabbix_client = ZabbixApiClient ( ) <EOL> for instance in instances : <EOL> try : <EOL> logger . debug ( '<STR_LIT>' % ( <EOL> sla_type , instance , period , start_time , end_time <EOL> ) ) <EOL> current_sla , events = zabbix_client . get_current_service_sla ( instance , start_time = start_time , end_time = end_time ) <EOL> with transaction . atomic ( ) : <EOL> entry , _ = InstanceSlaHistory . objects . get_or_create ( <EOL> instance = instance , <EOL> period = period <EOL> ) <EOL> entry . value = Decimal ( current_sla ) <EOL> entry . save ( ) <EOL> for event in events : <EOL> event_state = '<STR_LIT>' if int ( event [ '<STR_LIT:value>' ] ) == <NUM_LIT:0> else '<STR_LIT:D>' <EOL> entry . events . get_or_create ( <EOL> timestamp = int ( event [ '<STR_LIT>' ] ) , <EOL> state = event_state <EOL> ) <EOL> except ZabbixError as e : <EOL> logger . warning ( '<STR_LIT>' % ( instance , e ) ) <EOL> except IntegrityError as e : <EOL> logger . warning ( '<STR_LIT>' , instance ) <EOL> except Exception as e : <EOL> logger . warning ( '<STR_LIT>' % ( instance , e ) ) </s>
