1 /*
<lambda>null2  * Copyright 2017 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     https://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package trebuchet.importers.ftrace
18 
19 import trebuchet.importers.ImportFeedback
20 import trebuchet.importers.Importer
21 import trebuchet.importers.ImporterFactory
22 import trebuchet.importers.ftrace.events.CpuBufferStarted
23 import trebuchet.importers.ftrace.events.FtraceEvent
24 import trebuchet.importers.ftrace.events.createEventParser
25 import trebuchet.io.GenericByteBuffer
26 import trebuchet.io.StreamingReader
27 import trebuchet.io.iterLines
28 import trebuchet.model.fragments.ModelFragment
29 import trebuchet.util.contains
30 import trebuchet.util.par_map
31 
32 class FtraceImporter(val feedback: ImportFeedback) : Importer {
33     var score: Long = 0
34     var state = FtraceImporterState()
35 
36     override fun import(stream: StreamingReader): ModelFragment? {
37         par_map(stream.iterLines(), ::createEventParser) { parserState, it ->
38             try {
39                 FtraceEvent.tryParseText(parserState, it)
40             } catch (t: Throwable) {
41                 println("line '$it' failed")
42                 t.printStackTrace()
43                 null
44             }
45         }.forEach {
46             if (it == null) {
47                 score--
48                 if (score < -20) {
49                     feedback.reportImportWarning("Too many errors, giving up")
50                     return null
51                 }
52             } else {
53                 score++
54                 if (it === CpuBufferStarted) {
55                     state = FtraceImporterState()
56                 } else {
57                     state.importEvent(it)
58                 }
59             }
60         }
61         return state.finish()
62     }
63 
64     object Factory : ImporterFactory {
65         override fun importerFor(buffer: GenericByteBuffer, feedback: ImportFeedback): Importer? {
66             if (buffer.contains("# tracer: nop\n", 1000)
67                     || buffer.contains("       trace-cmd", 1000)) {
68                 return FtraceImporter(feedback)
69             }
70             return null
71         }
72     }
73 }