Package com.abiquo.hypervisor.model.redis

Source Code of com.abiquo.hypervisor.model.redis.HypervisorDAO

/**
* Copyright (C) 2008 - Abiquo Holdings S.L. All rights reserved.
*
* Please see /opt/abiquo/tomcat/webapps/legal/ on Abiquo server
* or contact contact@abiquo.com for licensing information.
*/
package com.abiquo.hypervisor.model.redis;

import static com.abiquo.redis.util.RedisUtils.nest;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.base.Strings.nullToEmpty;
import static java.lang.Long.parseLong;
import static java.lang.String.valueOf;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisException;

import com.abiquo.redis.AbstractRedisDAO;
import com.abiquo.redis.client.TransactionBlock2;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import com.google.common.primitives.Ints;

public class HypervisorDAO extends AbstractRedisDAO<Hypervisor>
{
    private static final String HypervisorNamespace = "PhysicalMachine";

    private static final String VirtualMachinesCacheNamespace = "VirtualMachinesCache";

    private static final String ConnectionIndexNamespace = "connection";

    private static final String UniqueIdentifierIndexNamespace = "uid";

    private static final String CacheNamespace = "cache";

    private static final String IpKey = "ip";

    private static final String EndPointKey = "end_point";

    private static final String PortKey = "port";

    private static final String ManagerIpKey = "manager_ip";

    private static final String ManagerPortKey = "manager_port";

    private static final String AgentIpKey = "agent_ip";

    private static final String AgentPortKey = "agent_port";

    private static final String TypeKey = "type";

    private static final String UsernameKey = "username";

    private static final String PasswordKey = "password";

    private static final String ManagerUsernameKey = "manager_username";

    private static final String ManagerPasswordKey = "manager_password";

    private static final String AgentUsernameKey = "agent_username";

    private static final String AgentPasswordKey = "agent_password";

    private static final String UIDKey = "uid";

    private static final String VirtualMachinesCacheKey = "virtualMachines_id";

    @Override
    public Optional<TransactionBlock2> insert(final Hypervisor hypervisor, final Jedis redis)
    {
        final List<String> indicesToDelete = Lists.newArrayList();
        String cacheId = "";

        boolean newOne = hypervisor.getId() != null ? //
            !find(valueOf(hypervisor.getId()), redis).isPresent() //
            : true;

        if (newOne)
        {
            // It is a new hypervisor
            hypervisor.setId(generateUniqueId(HypervisorNamespace, redis));
            cacheId = valueOf(generateUniqueId(VirtualMachinesCacheNamespace, redis));
        }
        else
        {
            // It is an old one
            final String hypervisorId = valueOf(hypervisor.getId());

            // Get cache id
            final String key = nest(HypervisorNamespace, hypervisorId);
            cacheId = redis.hgetAll(key).get(VirtualMachinesCacheKey);

            // Delete index by connection
            final Hypervisor old = find(hypervisorId, redis).get();
            final String connIndex = calculateConnectionindex(old);
            indicesToDelete.add(nest(HypervisorNamespace, ConnectionIndexNamespace, connIndex));
        }

        if (isNullOrEmpty(hypervisor.getUniqueIdentifier()))
        {
            throw new RuntimeException("Monitor unique identifier is a required field.");
        }

        if (isNullOrEmpty(hypervisor.getType()))
        {
            throw new RuntimeException("Monitor type is a required field.");
        }

        final Map<String, String> hash = new HashMap<String, String>();
        hash.put(TypeKey, hypervisor.getType());
        hash.put(UIDKey, hypervisor.getUniqueIdentifier());
        hash.put(EndPointKey, nullToEmpty(hypervisor.getEndPoint()));
        hash.put(IpKey, nullToEmpty(hypervisor.getIp()));
        hash.put(PortKey, extractPort(hypervisor.getPort()));
        hash.put(UsernameKey, nullToEmpty(hypervisor.getUser()));
        hash.put(PasswordKey, nullToEmpty(hypervisor.getPassword()));
        hash.put(ManagerIpKey, nullToEmpty(hypervisor.getManagerIp()));
        hash.put(ManagerPortKey, extractPort(hypervisor.getManagerPort()));
        hash.put(ManagerUsernameKey, nullToEmpty(hypervisor.getManagerUser()));
        hash.put(ManagerPasswordKey, nullToEmpty(hypervisor.getManagerPassword()));
        hash.put(AgentIpKey, nullToEmpty(hypervisor.getAgentIp()));
        hash.put(AgentPortKey, extractPort(hypervisor.getAgentPort()));
        hash.put(AgentUsernameKey, nullToEmpty(hypervisor.getAgentUser()));
        hash.put(AgentPasswordKey, nullToEmpty(hypervisor.getAgentPassword()));
        hash.put(VirtualMachinesCacheKey, valueOf(cacheId));

        TransactionBlock2 transactionBlock = new TransactionBlock2()
        {
            @Override
            public void execute() throws JedisException
            {
                String id = valueOf(hypervisor.getId());
                String cacheId = hash.get(VirtualMachinesCacheKey);
                String cacheKey = nest(VirtualMachinesCacheNamespace, cacheId, CacheNamespace);

                // Delete old indices and create new ones
                final String connIndex = calculateConnectionindex(hypervisor);
                final String uidIndex = hash.get(UIDKey);

                for (String index : indicesToDelete)
                {
                    del(index);
                }

                sadd(nest(HypervisorNamespace, AllNamespace), id);
                set(nest(HypervisorNamespace, ConnectionIndexNamespace, connIndex), id);
                set(nest(HypervisorNamespace, UniqueIdentifierIndexNamespace, uidIndex), id);

                // Insert monitor data
                hmset(nest(HypervisorNamespace, id), hash);
                del(cacheKey);

                Set<String> cache = hypervisor.getVirtualMachines();

                if (cache != null)
                {
                    for (String name : cache)
                    {
                        sadd(cacheKey, name);
                    }
                }
                else
                {
                    hypervisor.setVirtualMachines(new HashSet<String>());
                }
            }
        };

        return Optional.of(transactionBlock);
    }

    @Override
    public Optional<TransactionBlock2> delete(final Hypervisor hypervisor, final Jedis redis)
    {
        final String id = valueOf(hypervisor.getId());

        if (find(id, redis) == null)
        {
            return Optional.absent();
        }

        final Map<String, String> hash = redis.hgetAll(nest(HypervisorNamespace, id));

        TransactionBlock2 transactionBlock = new TransactionBlock2()
        {
            @Override
            public void execute() throws JedisException
            {
                String cacheId = hash.get(VirtualMachinesCacheKey);

                // Delete indices
                String connIndex = calculateConnectionindex(hypervisor);
                final String uidIndex = hash.get(UIDKey);

                srem(nest(HypervisorNamespace, AllNamespace), id);
                del(nest(HypervisorNamespace, ConnectionIndexNamespace, connIndex));
                del(nest(HypervisorNamespace, UniqueIdentifierIndexNamespace, uidIndex));

                // Delete data
                del(nest(HypervisorNamespace, id));
                del(nest(VirtualMachinesCacheNamespace, cacheId));
                del(nest(VirtualMachinesCacheNamespace, cacheId, CacheNamespace));
            }
        };

        return Optional.of(transactionBlock);
    }

    @Override
    public Optional<Hypervisor> find(final String id, final Jedis redis)
    {
        if (!redis.exists(nest(HypervisorNamespace, id)))
        {
            return Optional.absent();
        }

        Map<String, String> hash = redis.hgetAll(nest(HypervisorNamespace, id));
        String cacheId = hash.get(VirtualMachinesCacheKey);
        String cacheKey = nest(VirtualMachinesCacheNamespace, cacheId, CacheNamespace);

        Hypervisor hypervisor = new Hypervisor();
        hypervisor.setId(parseLong(id));
        hypervisor.setType(hash.get(TypeKey));
        hypervisor.setUniqueIdentifier(hash.get(UIDKey));
        hypervisor.setUser(nullToEmpty(hash.get(UsernameKey)));
        hypervisor.setPassword(nullToEmpty(hash.get(PasswordKey)));
        hypervisor.setEndPoint(nullToEmpty(hash.get(EndPointKey)));
        hypervisor.setIp(nullToEmpty(hash.get(IpKey)));
        hypervisor.setPort(extractPort(hash.get(PortKey)));
        hypervisor.setManagerIp(nullToEmpty(hash.get(ManagerIpKey)));
        hypervisor.setManagerPort(extractPort(hash.get(ManagerPortKey)));
        hypervisor.setAgentIp(nullToEmpty(hash.get(AgentIpKey)));
        hypervisor.setAgentPort(extractPort(hash.get(AgentPortKey)));
        hypervisor.setVirtualMachines(redis.smembers(cacheKey));
        hypervisor.setManagerUser(nullToEmpty(hash.get(ManagerUsernameKey)));
        hypervisor.setManagerPassword(nullToEmpty(hash.get(ManagerPasswordKey)));
        hypervisor.setAgentUser(nullToEmpty(hash.get(AgentUsernameKey)));
        hypervisor.setAgentPassword(nullToEmpty(hash.get(AgentPasswordKey)));
        return Optional.of(hypervisor);
    }

    public Optional<Hypervisor> find(final String endPoint, final String ip, final Integer port,
        final String user, final String password, final String managerIp,
        final Integer managerPort, final String managerUser, final String managerPassword,
        final String agentIp, final Integer agentPort, final String agentUser,
        final String agentPassword, final Jedis redis)
    {
        final String index =
            calculateConnectionIndex(endPoint, ip, port, user, password, managerIp, managerPort,
                managerUser, managerPassword, agentIp, agentPort, agentUser, agentPassword);
        final String key = nest(HypervisorNamespace, ConnectionIndexNamespace, index);
        final String id = redis.get(key);

        if (Strings.isNullOrEmpty(id))
        {
            return Optional.absent();
        }

        return find(id, redis);
    }

    public Optional<Hypervisor> findByUID(final String uniqueIdentifier, final Jedis redis)
    {
        String key = nest(HypervisorNamespace, UniqueIdentifierIndexNamespace, uniqueIdentifier);
        String id = redis.get(key);

        if (Strings.isNullOrEmpty(id))
        {
            return Optional.absent();
        }

        return find(id, redis);
    }

    public Set<Hypervisor> findAll(final Jedis redis)
    {
        Set<Hypervisor> machines = new HashSet<Hypervisor>();

        for (String id : redis.smembers(nest(HypervisorNamespace, AllNamespace)))
        {
            Optional<Hypervisor> hypervisor = find(id, redis);

            if (hypervisor.isPresent())
            {
                machines.add(hypervisor.get());
            }
        }

        return machines;
    }

    private String calculateConnectionindex(final Hypervisor hypervisor)
    {
        return calculateConnectionIndex(hypervisor.getEndPoint(), hypervisor.getIp(),
            hypervisor.getPort(), hypervisor.getUser(), hypervisor.getPassword(),
            hypervisor.getManagerIp(), hypervisor.getManagerPort(), hypervisor.getManagerUser(),
            hypervisor.getManagerPassword(), hypervisor.getAgentIp(), hypervisor.getAgentPort(),
            hypervisor.getAgentUser(), hypervisor.getAgentPassword());
    }

    private String calculateConnectionIndex(final String endPoint, final String ip,
        final Integer port, final String user, final String password, final String managerIp,
        final Integer managerPort, final String managerUser, final String managerPassword,
        final String agentIp, final Integer agentPort, final String agentUser,
        final String agentPassword)
    {
        final Hasher hasher = Hashing.md5().newHasher();

        // End point
        hasher.putBytes(nullToEmpty(endPoint).getBytes());

        // Host attributes
        hasher.putBytes(nullToEmpty(ip).getBytes());
        hasher.putBytes(nullToEmpty(user).getBytes());
        hasher.putBytes(nullToEmpty(password).getBytes());
        hasher.putBytes(extractPort(port).getBytes());

        // Manager attributes
        hasher.putBytes(nullToEmpty(managerIp).getBytes());
        hasher.putBytes(nullToEmpty(managerUser).getBytes());
        hasher.putBytes(nullToEmpty(managerPassword).getBytes());
        hasher.putBytes(extractPort(managerPort).getBytes());

        // Agent attributes
        hasher.putBytes(nullToEmpty(agentIp).getBytes());
        hasher.putBytes(nullToEmpty(agentUser).getBytes());
        hasher.putBytes(nullToEmpty(agentPassword).getBytes());
        hasher.putBytes(extractPort(agentPort).getBytes());

        return hasher.hash().toString();
    }

    private String extractPort(final Integer port)
    {
        return nullToEmpty(port != null ? String.valueOf(port) : null);
    }

    private Integer extractPort(final String port)
    {
        return Ints.tryParse(nullToEmpty(port));
    }
}
TOP

Related Classes of com.abiquo.hypervisor.model.redis.HypervisorDAO

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.