Search in sources :

Example 1 with ConfigurationException

use of javax.naming.ConfigurationException in project openhab1-addons by openhab.

the class HorizonBinding method updateConfiguration.

private void updateConfiguration(final Map<String, Object> configuration) throws ConfigurationException {
    Set<String> keys = configuration.keySet();
    Iterator<String> keysIt = keys.iterator();
    while (keysIt.hasNext()) {
        String key = keysIt.next();
        if ("service.pid".equals(key)) {
            continue;
        }
        Matcher matcher = EXTRACT_HORIZON_CONFIG_PATTERN.matcher(key);
        if (!matcher.matches()) {
            logger.debug("given config key '" + key + "' does not follow the expected pattern '<id>.<host>'");
            continue;
        }
        matcher.reset();
        matcher.find();
        String deviceId = matcher.group(1);
        String host = null;
        String configKey = matcher.group(2);
        String value = (String) configuration.get(key);
        if ("host".equals(configKey)) {
            host = value;
        } else {
            throw new ConfigurationException("The given configKey '" + configKey + "' is unknown");
        }
        HorizonBox horizonBox = new HorizonBox(host, DEFAULT_HORIZON_PORT);
        deviceConfigCache.put(deviceId, horizonBox);
    }
}
Also used : Matcher(java.util.regex.Matcher) ConfigurationException(javax.naming.ConfigurationException) HorizonBox(org.openhab.binding.horizon.internal.control.HorizonBox)

Example 2 with ConfigurationException

use of javax.naming.ConfigurationException in project CloudStack-archive by CloudStack-extras.

the class UsageManagerImpl method configure.

public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    final String run = "usage.vmops.pid";
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Checking to see if " + run + " exists.");
    }
    final Class<?> c = UsageServer.class;
    m_version = c.getPackage().getImplementationVersion();
    if (m_version == null) {
        throw new CloudRuntimeException("Unable to find the implementation version of this usage server");
    }
    if (s_logger.isInfoEnabled()) {
        s_logger.info("Implementation Version is " + m_version);
    }
    m_name = name;
    ComponentLocator locator = ComponentLocator.getCurrentLocator();
    ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
    if (configDao == null) {
        s_logger.error("Unable to get the configuration dao.");
        return false;
    }
    Map<String, String> configs = configDao.getConfiguration(params);
    if (params != null) {
        mergeConfigs(configs, params);
    }
    String execTime = configs.get("usage.stats.job.exec.time");
    String aggregationRange = configs.get("usage.stats.job.aggregation.range");
    String execTimeZone = configs.get("usage.execution.timezone");
    String aggreagationTimeZone = configs.get("usage.aggregation.timezone");
    String sanityCheckInterval = configs.get("usage.sanity.check.interval");
    if (sanityCheckInterval != null) {
        m_sanityCheckInterval = Integer.parseInt(sanityCheckInterval);
    }
    if (aggreagationTimeZone != null && !aggreagationTimeZone.isEmpty()) {
        m_usageTimezone = TimeZone.getTimeZone(aggreagationTimeZone);
    }
    s_logger.debug("Usage stats aggregation time zone: " + aggreagationTimeZone);
    try {
        if ((execTime == null) || (aggregationRange == null)) {
            s_logger.error("missing configuration values for usage job, usage.stats.job.exec.time = " + execTime + ", usage.stats.job.aggregation.range = " + aggregationRange);
            throw new ConfigurationException("Missing configuration values for usage job, usage.stats.job.exec.time = " + execTime + ", usage.stats.job.aggregation.range = " + aggregationRange);
        }
        String[] execTimeSegments = execTime.split(":");
        if (execTimeSegments.length != 2) {
            s_logger.error("Unable to parse usage.stats.job.exec.time");
            throw new ConfigurationException("Unable to parse usage.stats.job.exec.time '" + execTime + "'");
        }
        int hourOfDay = Integer.parseInt(execTimeSegments[0]);
        int minutes = Integer.parseInt(execTimeSegments[1]);
        m_jobExecTime.setTime(new Date());
        m_jobExecTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
        m_jobExecTime.set(Calendar.MINUTE, minutes);
        m_jobExecTime.set(Calendar.SECOND, 0);
        m_jobExecTime.set(Calendar.MILLISECOND, 0);
        if (execTimeZone != null && !execTimeZone.isEmpty()) {
            m_jobExecTime.setTimeZone(TimeZone.getTimeZone(execTimeZone));
        }
        // if the hour to execute the job has already passed, roll the day forward to the next day
        Date execDate = m_jobExecTime.getTime();
        if (execDate.before(new Date())) {
            m_jobExecTime.roll(Calendar.DAY_OF_YEAR, true);
        }
        s_logger.debug("Execution Time: " + execDate.toString());
        Date currentDate = new Date(System.currentTimeMillis());
        s_logger.debug("Current Time: " + currentDate.toString());
        m_aggregationDuration = Integer.parseInt(aggregationRange);
        if (m_aggregationDuration < USAGE_AGGREGATION_RANGE_MIN) {
            s_logger.warn("Usage stats job aggregation range is to small, using the minimum value of " + USAGE_AGGREGATION_RANGE_MIN);
            m_aggregationDuration = USAGE_AGGREGATION_RANGE_MIN;
        }
        m_hostname = InetAddress.getLocalHost().getHostName() + "/" + InetAddress.getLocalHost().getHostAddress();
    } catch (NumberFormatException ex) {
        throw new ConfigurationException("Unable to parse usage.stats.job.exec.time '" + execTime + "' or usage.stats.job.aggregation.range '" + aggregationRange + "', please check configuration values");
    } catch (Exception e) {
        s_logger.error("Unhandled exception configuring UsageManger", e);
        throw new ConfigurationException("Unhandled exception configuring UsageManager " + e.toString());
    }
    m_pid = Integer.parseInt(System.getProperty("pid"));
    return true;
}
Also used : ConfigurationDao(com.cloud.configuration.dao.ConfigurationDao) Date(java.util.Date) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SQLException(java.sql.SQLException) ComponentLocator(com.cloud.utils.component.ComponentLocator) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Example 3 with ConfigurationException

use of javax.naming.ConfigurationException in project CloudStack-archive by CloudStack-extras.

the class ProcessUtil method pidCheck.

// paths cannot be hardcoded
public static void pidCheck(String pidDir, String run) throws ConfigurationException {
    String dir = pidDir == null ? "/var/run" : pidDir;
    try {
        final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
        if (propsFile == null) {
            s_logger.debug("environment.properties could not be opened");
        } else {
            final FileInputStream finputstream = new FileInputStream(propsFile);
            final Properties props = new Properties();
            props.load(finputstream);
            finputstream.close();
            dir = props.getProperty("paths.pid");
            if (dir == null) {
                dir = "/var/run";
            }
        }
    } catch (IOException e) {
        s_logger.debug("environment.properties could not be opened");
    }
    final File pidFile = new File(dir + File.separator + run);
    try {
        if (!pidFile.createNewFile()) {
            if (!pidFile.exists()) {
                throw new ConfigurationException("Unable to write to " + pidFile.getAbsolutePath() + ".  Are you sure you're running as root?");
            }
            final FileInputStream is = new FileInputStream(pidFile);
            final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            final String pidLine = reader.readLine();
            if (pidLine == null) {
                throw new ConfigurationException("Java process is being started twice.  If this is not true, remove " + pidFile.getAbsolutePath());
            }
            try {
                final long pid = Long.parseLong(pidLine);
                final Script script = new Script("bash", 120000, s_logger);
                script.add("-c", "ps -p " + pid);
                final String result = script.execute();
                if (result == null) {
                    throw new ConfigurationException("Java process is being started twice.  If this is not true, remove " + pidFile.getAbsolutePath());
                }
                if (!pidFile.delete()) {
                    throw new ConfigurationException("Java process is being started twice.  If this is not true, remove " + pidFile.getAbsolutePath());
                }
                if (!pidFile.createNewFile()) {
                    throw new ConfigurationException("Java process is being started twice.  If this is not true, remove " + pidFile.getAbsolutePath());
                }
            } catch (final NumberFormatException e) {
                throw new ConfigurationException("Java process is being started twice.  If this is not true, remove " + pidFile.getAbsolutePath());
            }
        }
        pidFile.deleteOnExit();
        final Script script = new Script("bash", 120000, s_logger);
        script.add("-c", "echo $PPID");
        final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
        script.execute(parser);
        final String pid = parser.getLine();
        final FileOutputStream strm = new FileOutputStream(pidFile);
        strm.write((pid + "\n").getBytes());
        strm.close();
    } catch (final IOException e) {
        throw new CloudRuntimeException("Unable to create the " + pidFile.getAbsolutePath() + ".  Are you running as root?", e);
    }
}
Also used : Script(com.cloud.utils.script.Script) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) OutputInterpreter(com.cloud.utils.script.OutputInterpreter) File(java.io.File)

Example 4 with ConfigurationException

use of javax.naming.ConfigurationException in project CloudStack-archive by CloudStack-extras.

the class LibvirtComputingResource method execute.

protected CreatePrivateTemplateAnswer execute(CreatePrivateTemplateFromVolumeCommand cmd) {
    String secondaryStorageURL = cmd.getSecondaryStorageUrl();
    KVMStoragePool secondaryStorage = null;
    try {
        Connect conn = LibvirtConnection.getConnection();
        String templateFolder = cmd.getAccountId() + File.separator + cmd.getTemplateId() + File.separator;
        String templateInstallFolder = "/template/tmpl/" + templateFolder;
        secondaryStorage = _storagePoolMgr.getStoragePoolByURI(secondaryStorageURL);
        KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd.getPrimaryStoragePoolNameLabel());
        KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath());
        String tmpltPath = secondaryStorage.getLocalPath() + File.separator + templateInstallFolder;
        _storage.mkdirs(tmpltPath);
        Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger);
        command.add("-f", disk.getPath());
        command.add("-t", tmpltPath);
        command.add("-n", cmd.getUniqueName() + ".qcow2");
        String result = command.execute();
        if (result != null) {
            s_logger.debug("failed to create template: " + result);
            return new CreatePrivateTemplateAnswer(cmd, false, result);
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(StorageLayer.InstanceConfigKey, _storage);
        Processor qcow2Processor = new QCOW2Processor();
        qcow2Processor.configure("QCOW2 Processor", params);
        FormatInfo info = qcow2Processor.process(tmpltPath, null, cmd.getUniqueName());
        TemplateLocation loc = new TemplateLocation(_storage, tmpltPath);
        loc.create(1, true, cmd.getUniqueName());
        loc.addFormat(info);
        loc.save();
        return new CreatePrivateTemplateAnswer(cmd, true, null, templateInstallFolder + cmd.getUniqueName() + ".qcow2", info.virtualSize, info.size, cmd.getUniqueName(), ImageFormat.QCOW2);
    } catch (LibvirtException e) {
        s_logger.debug("Failed to get secondary storage pool: " + e.toString());
        return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
    } catch (InternalErrorException e) {
        return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
    } catch (IOException e) {
        return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
    } catch (ConfigurationException e) {
        return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
    } catch (CloudRuntimeException e) {
        return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
    } finally {
        if (secondaryStorage != null) {
            secondaryStorage.delete();
        }
    }
}
Also used : Script(com.cloud.utils.script.Script) QCOW2Processor(com.cloud.storage.template.QCOW2Processor) Processor(com.cloud.storage.template.Processor) LibvirtException(org.libvirt.LibvirtException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) KVMPhysicalDisk(com.cloud.agent.storage.KVMPhysicalDisk) Connect(org.libvirt.Connect) InternalErrorException(com.cloud.exception.InternalErrorException) IOException(java.io.IOException) QCOW2Processor(com.cloud.storage.template.QCOW2Processor) KVMStoragePool(com.cloud.agent.storage.KVMStoragePool) ConfigurationException(javax.naming.ConfigurationException) TemplateLocation(com.cloud.storage.template.TemplateLocation) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CreatePrivateTemplateAnswer(com.cloud.agent.api.storage.CreatePrivateTemplateAnswer) FormatInfo(com.cloud.storage.template.Processor.FormatInfo)

Example 5 with ConfigurationException

use of javax.naming.ConfigurationException in project CloudStack-archive by CloudStack-extras.

the class LibvirtComputingResource method getDeveloperProperties.

private Map<String, Object> getDeveloperProperties() throws ConfigurationException {
    final File file = PropertiesUtil.findConfigFile("developer.properties");
    if (file == null) {
        throw new ConfigurationException("Unable to find developer.properties.");
    }
    s_logger.info("developer.properties found at " + file.getAbsolutePath());
    Properties properties = new Properties();
    try {
        properties.load(new FileInputStream(file));
        String startMac = (String) properties.get("private.macaddr.start");
        if (startMac == null) {
            throw new ConfigurationException("Developers must specify start mac for private ip range");
        }
        String startIp = (String) properties.get("private.ipaddr.start");
        if (startIp == null) {
            throw new ConfigurationException("Developers must specify start ip for private ip range");
        }
        final Map<String, Object> params = PropertiesUtil.toMap(properties);
        String endIp = (String) properties.get("private.ipaddr.end");
        if (endIp == null) {
            endIp = getEndIpFromStartIp(startIp, 16);
            params.put("private.ipaddr.end", endIp);
        }
        return params;
    } catch (final FileNotFoundException ex) {
        throw new CloudRuntimeException("Cannot find the file: " + file.getAbsolutePath(), ex);
    } catch (final IOException ex) {
        throw new CloudRuntimeException("IOException in reading " + file.getAbsolutePath(), ex);
    }
}
Also used : ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Properties(java.util.Properties) File(java.io.File) FileInputStream(java.io.FileInputStream)

Aggregations

ConfigurationException (javax.naming.ConfigurationException)168 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)57 IOException (java.io.IOException)44 HashMap (java.util.HashMap)39 File (java.io.File)23 Map (java.util.Map)21 InternalErrorException (com.cloud.exception.InternalErrorException)19 Properties (java.util.Properties)19 StorageLayer (com.cloud.storage.StorageLayer)18 Processor (com.cloud.storage.template.Processor)17 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)17 Answer (com.cloud.agent.api.Answer)16 ServerResource (com.cloud.resource.ServerResource)16 TemplateLocation (com.cloud.storage.template.TemplateLocation)16 Script (com.cloud.utils.script.Script)16 FormatInfo (com.cloud.storage.template.Processor.FormatInfo)14 FileNotFoundException (java.io.FileNotFoundException)14 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)13 Host (com.cloud.host.Host)11 TransactionStatus (com.cloud.utils.db.TransactionStatus)11