001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.activemq.tool.sampler;
018    
019    import java.io.IOException;
020    
021    import org.apache.activemq.tool.reports.AbstractPerfReportWriter;
022    import org.apache.activemq.tool.sampler.plugins.CpuSamplerPlugin;
023    import org.apache.activemq.tool.sampler.plugins.LinuxCpuSamplerPlugin;
024    
025    public class CpuSamplerTask extends AbstractPerformanceSampler {
026    
027        private CpuSamplerPlugin plugin;
028    
029        public void createPlugin() throws IOException {
030            createPlugin(System.getProperty("os.name"));
031        }
032    
033        public void createPlugin(String osName) throws IOException {
034            if (osName == null) {
035                throw new IOException("No defined OS name found. Found: " + osName);
036            }
037    
038            if (osName.equalsIgnoreCase(CpuSamplerPlugin.LINUX)) {
039                plugin = new LinuxCpuSamplerPlugin(getInterval());
040            } else {
041                throw new IOException("No CPU Sampler Plugin found for OS: " + osName + ". CPU Sampler will not be started.");
042            }
043        }
044    
045        public void sampleData() {
046            if (plugin != null && perfReportWriter != null) {
047                perfReportWriter.writeCsvData(AbstractPerfReportWriter.REPORT_PLUGIN_CPU, "index=" + sampleIndex + "," + plugin.getCpuUtilizationStats());
048            }
049        }
050    
051        protected void onRampUpStart() {
052            super.onRampUpStart();
053            if (plugin != null) {
054                plugin.start();
055            }
056        }
057    
058        protected void onRampDownEnd() {
059            super.onRampDownEnd();
060            if (plugin != null) {
061                plugin.stop();
062            }
063        }
064    }