from saas.tools.devops.lib23.saas_entity import saas_service_iterator
import logging

all_stable_services = saas_service_iterator()
all_search_services = saas_service_iterator(saas_ctypes=['stable', 'stable_patents'])
all_kv_services = saas_service_iterator(saas_ctypes=['stable_kv', 'stable_middle_kv'])

ypable_services = []


look_like_testing_services = []
for s in all_stable_services:
    if 'test' in s.name or 'priemka' in s.name or 'prestable' in s.name:
        look_like_testing_services.append(s)

latency_tolerant_services = []
for s in all_stable_services:
    try:
        if s.has_backup() and s.sla_info.get('search_q_99_ms', s.sla_info.get('search_q_999_ms', 1000)) > 300:
            print "Latency tolerant sevice : {}/{}".format(s.ctype, s.name)
            latency_tolerant_services.append(s)
    except:
        logging.exception('Could not analyze %s', s.name)

memory_locked_services = []
for s in all_search_services:
    try:
        info_server = s.sample_info_server()
        if (
            info_server['config']['Server'][0]['Searcher'][0]["ArchivePolicy"] in ["MAPMEMLOCK", "INMEM"] and
            info_server['config']['Server'][0]['Searcher'][0]["LockIndexFiles"] == '1' and
            s.has_backup()
        ):
            print "Locked sevice : {}/{}".format(s.ctype, s.name)
            memory_locked_services.append(s)
    except:
        logging.exception('Could not analyze %s', s.name)

for s in all_kv_services:
    try:
        info_server = s.sample_info_server()
        if (
            s.has_backup()
            and info_server['config']['Server'][0]['Searcher'][0]["LockIndexFiles"] and
            info_server['config']['Server'][0]['ComponentsConfig'][0]["FULLARC"][0]['Layers'][0]['full'][0]['ReadContextDataAccessType'] in ['MEMORY_LOCKED_MAP']
        ):
            print "Locked sevice : {}/{}".format(s.ctype, s.name)
            memory_locked_services.append(s)
    except:
        logging.exception('Could not analyze %s', s.name)

services_to_ypify = []
for s in look_like_testing_services + latency_tolerant_services + memory_locked_services:
    if s not in services_to_ypify:
        yp_allocated = False
        for ns in s.nanny_services:
            if ns.is_yp_lite():
                yp_allocated = True
                break
        if not yp_allocated:
            services_to_ypify.append(s)

print('Services to ypify:')
for s in services_to_ypify:
    print("-> {} / {}".format(
        s.name,
        ",".join([ns.name for ns in s.nanny_services])
    ))
