Coverage details for com.clustercontrol.performance.rrdtool.PerformanceCSVExport

LineHitsSource
1 /*
2  
3 Copyright (C) 2008 NTT DATA Corporation
4  
5 This program is free software; you can redistribute it and/or
6 Modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation, version 2.
8  
9 This program is distributed in the hope that it will be
10 useful, but WITHOUT ANY WARRANTY; without even the implied
11 warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
12 PURPOSE. See the GNU General Public License for more details.
13  
14  */
15  
16 package com.clustercontrol.performance.rrdtool;
17  
18 import java.io.BufferedOutputStream;
19 import java.io.BufferedReader;
20 import java.io.FileOutputStream;
21 import java.io.FileReader;
22 import java.io.IOException;
23 import java.nio.channels.FileChannel;
24 import java.rmi.RemoteException;
25 import java.text.DecimalFormat;
26 import java.text.SimpleDateFormat;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Collections;
30 import java.util.Date;
31 import java.util.HashMap;
32 import java.util.StringTokenizer;
33 import java.util.regex.Pattern;
34  
35 import javax.naming.NamingException;
36  
37 import org.apache.commons.logging.Log;
38 import org.apache.commons.logging.LogFactory;
39 import org.jnp.interfaces.NamingContext;
40  
41 import com.clustercontrol.bean.FacilityTreeItem;
42 import com.clustercontrol.performance.bean.CollectedDataInfo;
43 import com.clustercontrol.performance.bean.CollectorItemInfo;
44 import com.clustercontrol.performance.bean.CollectorProperty;
45 import com.clustercontrol.performance.ejb.session.CollectorController;
46 import com.clustercontrol.performance.ejb.session.CollectorControllerHome;
47 import com.clustercontrol.performance.rrdtool.csv.CSVColumn;
48 import com.clustercontrol.performance.rrdtool.util.CollectedDataInfoDateComparator;
49 import com.clustercontrol.performance.rrdtool.util.Config;
50 import com.clustercontrol.performance.rrdtool.util.LoginManager;
51  
52 /**
53  * Hinemos Addon for RRDTool<br>
54  * CSVファイル出力?? 実行クラス<br>
55  *
56  * @since 3.0.0
57  */
581public class PerformanceCSVExport {
59  
60     // main関数に与えられる引数の格納変数
611    private static String collectorID = null;
621    private static String facilityID = null;
631    private static String listFilePath = null;
641    private static String outputFilePath = null;
651    private static String startDateEpochStr = null;
661    private static String endDateEpochStr = null;
67  
68     // main関数に与えられる引数を変換した変数
691    private static long startDateEpoch = 0;
701    private static long endDateEpoch = 0;
71  
72     // 実行ログ出力用クラス
731    private static Log log = LogFactory.getLog(PerformanceCSVExport.class);
74  
75     /**
76      * CSV出力実行関数<br>
77      *
78      * @param args
79      */
80     public static void main(String args[]) {
81  
82         // 出力??目定義格納変数
8323        ArrayList<CSVColumn> csvCols = new ArrayList<CSVColumn>();
84  
85         // 収集設定変数
8623        CollectorProperty property = null;
87  
88         // 不正出力??目?目存在フラグ
8923        boolean invalidColFlg = false;
90  
91         // 収集性能値の格納変数
9223        ArrayList<CollectedDataInfo> collectedDataInfos = null;
93  
94         // 出力??目の性能値存在フラグ
9523        HashMap<CSVColumn, Boolean> csvColFlg = null;
96  
97         // マネージャとのセ?ション?報
9823        NamingContext m_ctx = null;
9923        CollectorController collector = null;
100  
101         // 実行ログを記?
10223        log.info(Config.getMsg("RRDTool.ExportCSV.Exec") + " : " + Arrays.toString(args));
103  
104         // 引数の数の確?
10523        if (args.length != 6) {
1063            log.error(Config.getMsg("RRDTool.ExportCSV.ArgsInvalid"));
1073            System.exit(11);
108         }
109  
110         // 引数の格?
11120        collectorID = args[0];
11220        facilityID = args[1];
11320        listFilePath = args[2];
11420        startDateEpochStr = args[3];
11520        endDateEpochStr = args[4];
11620        outputFilePath = args[5];
117  
118         // エクスポ?ト期間?確?
119         try {
12020            startDateEpoch = Long.decode(startDateEpochStr);
12118            endDateEpoch = Long.decode(endDateEpochStr);
122  
12316            if (startDateEpoch <= 0 || endDateEpoch <= 0 || endDateEpoch < startDateEpoch) {
124                 // 検索日時が正数??0より大きい?でな?、もしくは検索終?日時が検索開始日時より前である場?
1252                log.error(Config.getMsg("RRDTool.ExportCSV.DateFormatInvalid"));
1262                System.exit(52);
127             }
128  
129             // ミリ秒へ変換
13014            startDateEpoch *= 1000;
13114            endDateEpoch *= 1000;
1324        } catch (NumberFormatException e) {
133             // 検索日時が整数でな?場合?Long型として読み込めな?場合?
1344            log.error(Config.getMsg("RRDTool.ExportCSV.DateFormatInvalid"), e);
1354            System.exit(52);
136         }
137  
138         // 出力??目定義ファイルの読み込み
13914        csvCols = readColumnDefFile(listFilePath);
140  
141         // マネージャーへの接?
142         try {
14328            m_ctx = LoginManager.getContextManager().getNamingContext(Config.getConfig("Login.USER"),
14414                    Config.getConfig("Login.PASSWORD"), Config.getConfig("Login.URL"));
14522            collector = (CollectorController) ((CollectorControllerHome) m_ctx.lookup(CollectorControllerHome.JNDI_NAME))
1469                    .create();
1475        } catch (Exception e) {
1485            log.error(Config.getMsg("RRDTool.ExportCSV.ConnectManagerFailed"), e);
1495            System.exit(14);
150         }
151  
152         try {
153             // 収集プロパティの取得を試み、取得できな?場合?エラー処?を実施する
1549            property = collector.getCollectorProperty(collectorID);
155  
156             // ?定?収集IDの収集が存在しな?場合?、nullが返る
1578            if (property == null) {
1581                log.error(Config.getMsg("RRDTool.ExportCSV.CollectorIDNotFound"));
1591                System.exit(53);
160             }
161  
1621        } catch (RemoteException e) {
1631            log.error(Config.getMsg("RRDTool.ExportCSV.ConnectManagerFailed"), e);
1641            System.exit(14);
165         }
166  
167         // ファシリ?ィIDの妥当?確?
1687        if (!checkFacilityDefinition(property, facilityID)) {
1691            log.error(Config.getMsg("RRDTool.ExportCSV.FacilityIDNotFound"));
1701            System.exit(54);
171         }
172  
173         // 出力??目の妥当?確?
1746        invalidColFlg = !checkCollectorDefinition(property, csvCols);
175  
176         // 収集性能値の格?
177         try {
17812            collectedDataInfos = (ArrayList<CollectedDataInfo>) collector.getRecordCollectedData(collectorID, facilityID,
1796                    new Date(startDateEpoch), new Date(endDateEpoch));
1801        } catch (RemoteException e) {
1811            log.error(Config.getMsg("RRDTool.ExportCSV.ConnectManagerFailed"), e);
1821            System.exit(14);
183         }
184  
185         // 不要な性能値の除去
1865        csvColFlg = examineCollectedDataInfo(collectedDataInfos, csvCols);
187  
188         // 出力??目の 収集性能値?1つも存在しな?場?
1895        if (collectedDataInfos.size() == 0) {
1901            log.error(Config.getMsg("RRDTool.ExportCSV.ColValueNotFound"));
1911            System.exit(55);
192         }
193  
194         // 性能値の日時ソー?
1954        Collections.sort(collectedDataInfos, new CollectedDataInfoDateComparator());
196  
197         // CSVファイルの出?
1984        writeCSVFile(outputFilePath, csvCols, collectedDataInfos);
199         
200         // マネージャー接続??断
201         try {
2024            LoginManager.getContextManager().logout();
2030        } catch (NamingException e) {
2040            log.warn(Config.getMsg("RRDTool.ExportCSV.DisconnectManagerFailed"), e);
205         }
206         
2074        if (invalidColFlg) {
208             // 不正な出力??目定義がある??
2091            System.exit(101);
2103        } else if (csvColFlg.containsValue(false)) {
211             // 性能値のな?出力??目がある??
2121            System.exit(102);
213         } else {
214             // 正常終?
2152            log.info(Config.getMsg("RRDTool.ExportCSV.Exit"));
2162            System.exit(0);
217         }
2182    }
219  
220     /**
221      * 出力??目定義ファイルを読み込んで、?力??目?報を取得する??
222      *
223      * @param fileName
224      * 出力??目定義ファイルのファイルパス?絶対パス、相対パスともに可??
225      * @return 出力??目?報の配?(?力??目?に格納されて?る?
226      */
227     public static ArrayList<CSVColumn> readColumnDefFile(String fileName) {
228  
229         // 返り値
23029        ArrayList<CSVColumn> ret = new ArrayList<CSVColumn>();
231  
232         // ファイル読み込み用変数
23329        BufferedReader br = null;
23429        String line = null;
23529        String colName = null;
23629        String itemCode = null;
23729        String deviceName = null;
238  
239         // 出力??目定義のフォーマット確認用変数
24029        StringTokenizer defTokenizer = null;
24129        String tokenStr = "\t";
24229        Pattern colNamePattern = Pattern.compile("^[^\t\",]+$");
24329        boolean invalidDefFormat = false;
244  
245         try {
246             // 出力??目定義ファイルを開?
24729            br = new BufferedReader(new FileReader(fileName));
248  
249259            while ((line = br.readLine()) != null) {
250  
251                 // カラ?数の確?
252203                defTokenizer = new StringTokenizer(line, tokenStr, false);
253203                if (defTokenizer.countTokens() == 2) {
254                     // 出力??目?<tab>?目コード?場?
255156                    colName = defTokenizer.nextToken();
256156                    itemCode = defTokenizer.nextToken();
257156                    deviceName = "";
25847                } else if (defTokenizer.countTokens() == 3) {
259                     // 出力??目?<tab>?目コー?<tab>?バイス名?場?
26042                    colName = defTokenizer.nextToken();
26142                    itemCode = defTokenizer.nextToken();
26242                    deviceName = defTokenizer.nextToken();
263                 } else {
264                     // 不正な書式?行?場?
2655                    colName = null;
2665                    itemCode = null;
2675                    deviceName = null;
2685                    log.error(Config.getMsg("RRDTool.ExportCSV.LineFormatInvalid") + " : " + line);
2695                    invalidDefFormat = true;
270                 }
271  
272                 // 出力??目名?書式確?
273203                if (colName != null && !colNamePattern.matcher(colName).matches()) {
274                     // 出力??目名に不正な場?
2752                    log.error(Config.getMsg("RRDTool.ExportCSV.ColNameFormatInvalid") + " : " + colName);
2762                    invalidDefFormat = true;
277                 }
278  
279                 // 出力カラ?定義の格?
280203                if (!invalidDefFormat) {
281193                    ret.add(new CSVColumn(colName, itemCode, deviceName));
282                 }
283  
284             }
285  
2861        } catch (Exception e) {
287             // ファイルの読み込み処?に失敗した??
2881            log.error(Config.getMsg("RRDTool.ExportCSV.ReadFileFailed"), e);
2891            System.exit(12);
2900        } finally {
291             try {
292                 // 出力??目定義ファイルを閉じる
29329                if (br != null) {
29428                    br.close();
295                 }
2961            } catch (IOException e) {
297                 // ファイルの読み込み処?に失敗した??
2981                log.error(Config.getMsg("RRDTool.ExportCSV.ReadFileFailed"), e);
2991                System.exit(12);
300             }
30129            if (invalidDefFormat) {
302                 // 不正な?目定義が存在した場?
3037                System.exit(13);
304             }
3050        }
306  
30729        return ret;
308     }
309  
310     /**
311      * 性能収集定義に該当する収?対象?収?ID, ?バイス名)が存在するかど?かを確認する??
312      *
313      * @param property
314      * 性能収集定義オブジェク?
315      * @param csvCols
316      * 出力??目?報の配?(?力??目?に格納されて?る?
317      * @return 不正な出力??目?報が?とつでも存在する場?false, それ以外?true
318      */
319     public static boolean checkCollectorDefinition(CollectorProperty property, ArrayList<CSVColumn> csvCols) {
320  
32115        boolean ret = true;
32215        boolean invalidColumn = false;
323  
324         // 出力??目が?能収集定義に含まれるかど?かを確認す?
325153        for (CSVColumn csvCol : csvCols) {
326123            invalidColumn = true;
3271166            for (CollectorItemInfo collectorItemInfo : (ArrayList<CollectorItemInfo>) property.getItemList()) {
3281037                if (csvCol.equalsCollection(collectorItemInfo.getItemCode(), collectorItemInfo.getDeviceName())) {
329117                    invalidColumn = false;
330117                    break;
331                 }
332             }
333123            if (invalidColumn) {
334                 // 性能収集定義に含まれな?出力??目の場?
33512                log.warn(Config.getMsg("RRDTool.ExportCSV.ColDefinitionInvalid") + " : " + csvCol.getItemCode() + ", "
3366                        + csvCol.getDeviceName());
3376                ret = false;
338             }
339         }
340  
34115        return ret;
342     }
343  
344     /**
345      * 性能収集定義に該当するファシリ?ィIDが存在するかど?かを確認する??
346      *
347      * @param property
348      * 性能収集定義オブジェク?
349      * @param facilityId
350      * 出力対象ノ?ド?ファシリ?ィID
351      * @return ファシリ?ィIDが存在しな?場?false, それ以外?true
352      */
353     public static boolean checkFacilityDefinition(CollectorProperty property, String facilityId) {
354         // 収集対象スコープ?下?スコープツリーを取?
3557        FacilityTreeItem tree = property.getCollectorData().getFacilityTree();
356  
357         // トップ?ファシリ?ィから?番に子要?を?帰?に調べ?
3587        return checkChildFacility(tree, facilityId);
359     }
360  
361     /**
362      * ?定ファシリ?ィ?リーの配下に該当?ファシリ?ィIDの要?が存在するか否かを再帰?に調べる??
363      *
364      * @param treeItem
365      * ファシリ?ィ?リー?報
366      * @param facilityId
367      * ファシリ?ィID
368      * @return
369      */
370     private static boolean checkChildFacility(FacilityTreeItem treeItem, String facilityId) {
371         // ?致するも?が見つかった?合?、trueを返す
37223        if (treeItem.getData().getFacilityId().equals(facilityId)) {
3736            return true;
374         }
375  
37621        for (int i = 0; i < treeItem.getChildren().length; i++) {
37716            FacilityTreeItem child = treeItem.getChildren()[i];
378  
379             // 子要?を?帰?に捜査し?見つかった?合にはtrueを返す
380             // falseの場合?継続して捜査を実?
38116            if (checkChildFacility(child, facilityId) == true) {
38212                return true;
383             }
384         }
385  
386         // ?致するも?が見つからなかった?合?nullを返す
3875        return false;
388     }
389  
390     /**
391      * 出力??目定義に存在しな?性能?報を??から取り除き?各出力??目における?能?報が存在するかど?かを定義した連想配?を返す?
392      *
393      * @param collectedDataInfos
394      * 収集性能値の格納???
395      * @param csvCols
396      * 出力??目定義オブジェク?
397      * @return 出力??目オブジェクトをキーとして、収?性能値?1つ以上存在すればtrue, 存在しなければfalseを?とする連想配??
398      */
399     public static HashMap<CSVColumn, Boolean> examineCollectedDataInfo(ArrayList<CollectedDataInfo> collectedDataInfos,
400             ArrayList<CSVColumn> csvCols) {
401  
40216        boolean valueExistFlg = false;
40316        CollectedDataInfo collectedDataInfo = null;
40416        HashMap<CSVColumn, Boolean> ret = new HashMap<CSVColumn, Boolean>();
405  
406         // すべての出力??目の収集性能値存在フラグをfalseとする
407169        for (CSVColumn csvCol : csvCols) {
408137            ret.put(csvCol, false);
409         }
410  
411         // すべての収集性能値オブジェクトが収集?目に含まれるかど?かを確認す?
4121908        for (int i = 0; i < collectedDataInfos.size(); i++) {
4131892            collectedDataInfo = collectedDataInfos.get(i);
4141892            valueExistFlg = false;
41537264            for (CSVColumn csvCol : csvCols) {
41633480                if (csvCol.equalsCollection(collectedDataInfo.getItemCode(), collectedDataInfo.getDeviceName())) {
4172989                    valueExistFlg = true;
4182989                    ret.put(csvCol, true);
419                 }
420             }
421             // 出力??目に含まれな?収集性能値オブジェクトを取り除?
4221892            if (!valueExistFlg) {
423206                collectedDataInfos.remove(i);
424206                i--;
425             }
426         }
427  
42816        return ret;
429     }
430  
431     /**
432      * 収集性能値をCSVファイルに出力する??<br>
433      * <br> - 出力?<br>
434      * "Date","Time","CPU_ALL","SWAP_ALL","PCK_RCV eth0"[LF]<br>
435      * "08/05/30","0:00",0.64,0.00,22.27,11.07[LF]<br>
436      * "08/05/30","0:30",1.00,0.00,26.40,12.93[LF]<br>
437      * <br>
438      * ただし??"Date", "Time"は性能収集の予定日時ではなく?実際に収集した日時である?<br>
439      * また?何らか?原因により収集?延が発生し?1?間?中で??yyyy-MM-dd HH:mm?に<br>
440      * 同?キー??collector_id, item_code,device_name)に対する?数の性能値が存在する場合?<br>
441      * ?も古?日時?性能値を?力??容とする。(古?日時?性能値のほ?が計測時間が長く?信頼性が高いため??
442      *
443      * @param filePath
444      * CSVファイルのファイルパス?絶対パス、相対パスともに可??
445      * @param csvCols
446      * 出力??目定義オブジェク?
447      * @param collectedDataInfos
448      * 収集性能値の格納??(た?し?日時でソートされており、?力??目以外?収集性能値が存在しな?こと。また??能値がnullでな?こと。?
449      */
450     public static void writeCSVFile(String filePath, ArrayList<CSVColumn> csvCols,
451             ArrayList<CollectedDataInfo> collectedDataInfos) {
452  
453         // ファイル書き込み用変数
45421        FileOutputStream fos = null;
45521        BufferedOutputStream bos = null;
45621        FileChannel channel = null;
45721        StringBuffer line = new StringBuffer();
458  
459         // 日付書式用変数
46021        SimpleDateFormat dateformat = new SimpleDateFormat("yy/MM/dd");
46121        SimpleDateFormat timeformat = new SimpleDateFormat("H:mm");
46221        SimpleDateFormat hashKeyformat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
463  
464         // 収集性能値書式用変数
46521        DecimalFormat valueformat = new DecimalFormat("#.00");
466  
467         // 日時文字??yyyy-MM-dd hh:mm?をキーとした収集性能値の連想配??
46821        HashMap<String, ArrayList<CollectedDataInfo>> dataHash = new HashMap<String, ArrayList<CollectedDataInfo>>();
46921        String hashKey = null;
47021        ArrayList<String> hashKeys = new ArrayList<String>();
471  
472         // 連想配?への収集性能値の格?
4732500        for (CollectedDataInfo collectedDataInfo : collectedDataInfos) {
4742458            hashKey = hashKeyformat.format(collectedDataInfo.getDate());
4752458            if (!dataHash.containsKey(hashKey)) {
476352                dataHash.put(hashKey, new ArrayList<CollectedDataInfo>());
477             }
4782458            dataHash.get(hashKey).add(collectedDataInfo);
4792458            if (!hashKeys.contains(hashKey)) {
480352                hashKeys.add(hashKey);
481             }
482         }
483  
484         // CSVファイルへの出?
485         try {
486             // 出力ファイルを開?
48721            fos = new FileOutputStream(filePath);
488  
489             // ファイルの排他制御?排他ロ?クを取得?
49020            channel = fos.getChannel();
49120            if (channel.tryLock() == null) {
492                 // ロ?クに失敗した??
4931                log.error(Config.getMsg("RRDTool.ExportCSV.LockFileFailed"));
4941                System.exit(51);
495             }
49620            bos = new BufferedOutputStream(fos);
497  
498             // ヘッ?ー行?出?
49920            line.delete(0, line.length());
50020            line.append("\"Date\",\"Time\",");
501162            for (int i = 0; i < csvCols.size(); i++) {
502142                line.append("\"" + csvCols.get(i).getColumnName() + "\"");
503142                if (i < csvCols.size() - 1) {
504122                    line.append(",");
505                 }
506             }
507             // ?終行以外では末尾にLFを付与す?
50820            if (hashKeys.size() != 0) {
50919                line.append("\n");
510             }
51120            bos.write(line.toString().getBytes());
512  
513             // 性能値の出?
514388            for (String datekey : hashKeys) {
515350                line.delete(0, line.length());
516350                line.append("\"" + dateformat.format(dataHash.get(datekey).get(0).getDate()) + "\",");
517350                line.append("\"" + timeformat.format(dataHash.get(datekey).get(0).getDate()) + "\",");
518                 // 出力??目ごとに出?
5196008                for (int i = 0; i < csvCols.size(); i++) {
520                     // 該当日時文字?キーに性能値が存在する場合???
52132589                    for (CollectedDataInfo collectedDataInfo : dataHash.get(datekey)) {
52249002                        if (csvCols.get(i).equalsCollection(collectedDataInfo.getItemCode(),
52324501                                collectedDataInfo.getDeviceName())) {
5243228                            line.append(valueformat.format(collectedDataInfo.getValue()));
5253228                            break;
526                         }
527                     }
5285658                    if (i < csvCols.size() - 1) {
5295308                        line.append(",");
530                     }
531                 }
532350                line.append("\n");
533350                bos.write(line.toString().getBytes());
534             }
535  
5362        } catch (Exception e) {
537             // ファイルの書き込み処?に失敗した??
5382            log.error(Config.getMsg("RRDTool.ExportCSV.WriteFileFailed"), e);
5392            System.exit(51);
5400        } finally {
541             try {
542                 // 出力ファイルに書き?し??容を反?して閉じ?
54321                if (bos != null) {
54420                    bos.flush();
54519                    bos.close();
546                 }
5472            } catch (IOException e) {
548                 // ファイルの書き込み処?に失敗した??
5492                log.error(Config.getMsg("RRDTool.ExportCSV.WriteFileFailed"), e);
5502                System.exit(51);
551             }
5520        }
553  
55421        return;
555     }
556  
557 }

this report was generated by version @product.version@ of jcoverage.
visit www.jcoverage.com for updates.

copyright © 2003, jcoverage ltd. all rights reserved.
Java is a trademark of Sun Microsystems, Inc. in the United States and other countries.