• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 The Android Open Source Project
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  *      http://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 #include "src/trace_processor/dynamic/experimental_slice_layout_generator.h"
18 #include "perfetto/ext/base/optional.h"
19 #include "perfetto/ext/base/string_splitter.h"
20 #include "perfetto/ext/base/string_utils.h"
21 #include "src/trace_processor/sqlite/sqlite_utils.h"
22 
23 namespace perfetto {
24 namespace trace_processor {
25 namespace {
26 
27 struct GroupInfo {
GroupInfoperfetto::trace_processor::__anon9bd4c2900111::GroupInfo28   GroupInfo(int64_t _start, int64_t _end, uint32_t _max_height)
29       : start(_start), end(_end), max_height(_max_height) {}
30   int64_t start;
31   int64_t end;
32   uint32_t max_height;
33   uint32_t layout_depth;
34 };
35 
36 }  // namespace
37 
ExperimentalSliceLayoutGenerator(StringPool * string_pool,const tables::SliceTable * table)38 ExperimentalSliceLayoutGenerator::ExperimentalSliceLayoutGenerator(
39     StringPool* string_pool,
40     const tables::SliceTable* table)
41     : string_pool_(string_pool),
42       slice_table_(table),
43       empty_string_id_(string_pool_->InternString("")) {}
44 ExperimentalSliceLayoutGenerator::~ExperimentalSliceLayoutGenerator() = default;
45 
CreateSchema()46 Table::Schema ExperimentalSliceLayoutGenerator::CreateSchema() {
47   Table::Schema schema = tables::SliceTable::Schema();
48   schema.columns.emplace_back(Table::Schema::Column{
49       "layout_depth", SqlValue::Type::kLong, false /* is_id */,
50       false /* is_sorted */, false /* is_hidden */});
51   schema.columns.emplace_back(Table::Schema::Column{
52       "filter_track_ids", SqlValue::Type::kString, false /* is_id */,
53       false /* is_sorted */, true /* is_hidden */});
54   return schema;
55 }
56 
TableName()57 std::string ExperimentalSliceLayoutGenerator::TableName() {
58   return "experimental_slice_layout";
59 }
60 
EstimateRowCount()61 uint32_t ExperimentalSliceLayoutGenerator::EstimateRowCount() {
62   return slice_table_->row_count();
63 }
64 
ValidateConstraints(const QueryConstraints & cs)65 util::Status ExperimentalSliceLayoutGenerator::ValidateConstraints(
66     const QueryConstraints& cs) {
67   for (const auto& c : cs.constraints()) {
68     if (c.column == kFilterTrackIdsColumnIndex && sqlite_utils::IsOpEq(c.op)) {
69       return util::OkStatus();
70     }
71   }
72   return util::ErrStatus(
73       "experimental_slice_layout must have filter_track_ids constraint");
74 }
75 
ComputeTable(const std::vector<Constraint> & cs,const std::vector<Order> &)76 std::unique_ptr<Table> ExperimentalSliceLayoutGenerator::ComputeTable(
77     const std::vector<Constraint>& cs,
78     const std::vector<Order>&) {
79   std::set<TrackId> selected_tracks;
80   std::string filter_string = "";
81   for (const auto& c : cs) {
82     bool is_filter_track_ids = c.col_idx == kFilterTrackIdsColumnIndex;
83     bool is_equal = c.op == FilterOp::kEq;
84     bool is_string = c.value.type == SqlValue::kString;
85     if (is_filter_track_ids && is_equal && is_string) {
86       filter_string = c.value.AsString();
87       for (base::StringSplitter sp(filter_string, ','); sp.Next();) {
88         base::Optional<uint32_t> maybe = base::CStringToUInt32(sp.cur_token());
89         if (maybe) {
90           selected_tracks.insert(TrackId{maybe.value()});
91         }
92       }
93     }
94   }
95 
96   StringPool::Id filter_id =
97       string_pool_->InternString(base::StringView(filter_string));
98   return AddLayoutColumn(*slice_table_, selected_tracks, filter_id);
99 }
100 
101 // Build up a table of slice id -> root slice id by observing each
102 // (id, opt_parent_id) pair in order.
InsertSlice(std::map<tables::SliceTable::Id,tables::SliceTable::Id> & id_map,tables::SliceTable::Id id,base::Optional<tables::SliceTable::Id> parent_id)103 tables::SliceTable::Id ExperimentalSliceLayoutGenerator::InsertSlice(
104     std::map<tables::SliceTable::Id, tables::SliceTable::Id>& id_map,
105     tables::SliceTable::Id id,
106     base::Optional<tables::SliceTable::Id> parent_id) {
107   if (parent_id) {
108     tables::SliceTable::Id root_id = id_map[parent_id.value()];
109     id_map[id] = root_id;
110     return root_id;
111   } else {
112     id_map[id] = id;
113     return id;
114   }
115 }
116 
117 // The problem we're trying to solve is this: given a number of tracks each of
118 // which contain a number of 'stalactites' - depth 0 slices and all their
119 // children - layout the stalactites to minimize vertical depth without
120 // changing the horizontal (time) position. So given two tracks:
121 // Track A:
122 //     aaaaaaaaa       aaa
123 //                      aa
124 //                       a
125 // Track B:
126 //      bbb       bbb    bbb
127 //       b         b      b
128 // The result could be something like:
129 //     aaaaaaaaa  bbb  aaa
130 //                 b    aa
131 //      bbb              a
132 //       b
133 //                       bbb
134 //                        b
135 // We do this by computing an additional column: layout_depth. layout_depth
136 // tells us the vertical position of each slice in each stalactite.
137 //
138 // The algorithm works in three passes:
139 // 1. For each stalactite find the 'bounding box' (start, end, & max depth)
140 // 2. Considering each stalactite bounding box in start ts order pick a
141 //    layout_depth for the root slice of stalactite to avoid collisions with
142 //    all previous stalactite's we've considered.
143 // 3. Go though each slice and give it a layout_depth by summing it's
144 //    current depth and the root layout_depth of the stalactite it belongs to.
145 //
AddLayoutColumn(const Table & table,const std::set<TrackId> & selected,StringPool::Id filter_id)146 std::unique_ptr<Table> ExperimentalSliceLayoutGenerator::AddLayoutColumn(
147     const Table& table,
148     const std::set<TrackId>& selected,
149     StringPool::Id filter_id) {
150   const auto& track_id_col =
151       *table.GetTypedColumnByName<tables::TrackTable::Id>("track_id");
152   const auto& id_col = *table.GetIdColumnByName<tables::SliceTable::Id>("id");
153   const auto& parent_id_col =
154       *table.GetTypedColumnByName<base::Optional<tables::SliceTable::Id>>(
155           "parent_id");
156   const auto& depth_col = *table.GetTypedColumnByName<uint32_t>("depth");
157   const auto& ts_col = *table.GetTypedColumnByName<int64_t>("ts");
158   const auto& dur_col = *table.GetTypedColumnByName<int64_t>("dur");
159 
160   std::map<tables::SliceTable::Id, GroupInfo> groups;
161   // Map of id -> root_id
162   std::map<tables::SliceTable::Id, tables::SliceTable::Id> id_map;
163 
164   // Step 1:
165   // Find the bounding box (start ts, end ts, and max depth) for each group
166   // TODO(lalitm): Update this to use iterator (will be slow after event table)
167   for (uint32_t i = 0; i < table.row_count(); ++i) {
168     TrackId track_id = track_id_col[i];
169     if (selected.count(track_id) == 0) {
170       continue;
171     }
172 
173     tables::SliceTable::Id id = id_col[i];
174     base::Optional<tables::SliceTable::Id> parent_id = parent_id_col[i];
175     uint32_t depth = depth_col[i];
176     int64_t start = ts_col[i];
177     int64_t dur = dur_col[i];
178     int64_t end = start + dur;
179     InsertSlice(id_map, id, parent_id);
180     std::map<tables::SliceTable::Id, GroupInfo>::iterator it;
181     bool inserted;
182     std::tie(it, inserted) = groups.emplace(
183         std::piecewise_construct, std::forward_as_tuple(id_map[id]),
184         std::forward_as_tuple(start, end, depth + 1));
185     if (!inserted) {
186       it->second.max_height = std::max(it->second.max_height, depth + 1);
187       it->second.end = std::max(it->second.end, end);
188     }
189   }
190 
191   // Sort the groups by ts
192   std::vector<GroupInfo*> sorted_groups;
193   sorted_groups.resize(groups.size());
194   size_t idx = 0;
195   for (auto& group : groups) {
196     sorted_groups[idx++] = &group.second;
197   }
198   std::sort(std::begin(sorted_groups), std::end(sorted_groups),
199             [](const GroupInfo* group1, const GroupInfo* group2) {
200               return group1->start < group2->start;
201             });
202 
203   // Step 2:
204   // Go though each group and choose a depth for the root slice.
205   // We keep track of those groups where the start time has passed but the
206   // end time has not in this vector:
207   std::vector<GroupInfo*> still_open;
208   for (GroupInfo* group : sorted_groups) {
209     int64_t start = group->start;
210     uint32_t max_height = group->max_height;
211 
212     // Discard all 'closed' groups where that groups end_ts is < our start_ts:
213     {
214       auto it = still_open.begin();
215       while (it != still_open.end()) {
216         if ((*it)->end < start) {
217           it = still_open.erase(it);
218         } else {
219           ++it;
220         }
221       }
222     }
223 
224     // Find a start layout depth for this group s.t. our start depth +
225     // our max depth will not intersect with the start depth + max depth for
226     // any of the open groups:
227     uint32_t layout_depth = 0;
228     bool done = false;
229     while (!done) {
230       done = true;
231       uint32_t start_depth = layout_depth;
232       uint32_t end_depth = layout_depth + max_height;
233       for (const auto& open : still_open) {
234         bool top = open->layout_depth <= start_depth &&
235                    start_depth < open->layout_depth + open->max_height;
236         bool bottom = open->layout_depth < end_depth &&
237                       end_depth <= open->layout_depth + open->max_height;
238         if (top || bottom) {
239           // This is extremely dumb, we can make a much better guess for what
240           // depth to try next but it is a little complicated to get right.
241           layout_depth++;
242           done = false;
243           break;
244         }
245       }
246     }
247 
248     // Add this group to the open groups & re
249     still_open.push_back(group);
250 
251     // Set our root layout depth:
252     group->layout_depth = layout_depth;
253   }
254 
255   // Step 3: Add the two new columns layout_depth and filter_track_ids:
256   std::unique_ptr<NullableVector<int64_t>> layout_depth_column(
257       new NullableVector<int64_t>());
258   std::unique_ptr<NullableVector<StringPool::Id>> filter_column(
259       new NullableVector<StringPool::Id>());
260 
261   for (uint32_t i = 0; i < table.row_count(); ++i) {
262     TrackId track_id = track_id_col[i];
263     tables::SliceTable::Id id = id_col[i];
264     uint32_t depth = depth_col[i];
265     if (selected.count(track_id) == 0) {
266       // Don't care about depth for slices from non-selected tracks:
267       layout_depth_column->Append(0);
268       // We (ab)use this column to also filter out all the slices we don't care
269       // about by giving it a different value.
270       filter_column->Append(empty_string_id_);
271     } else {
272       // Each slice depth is it's current slice depth + root slice depth of the
273       // group:
274       layout_depth_column->Append(depth + groups.at(id_map[id]).layout_depth);
275       // We must set this to the value we got in the constraint to ensure our
276       // rows are not filtered out:
277       filter_column->Append(filter_id);
278     }
279   }
280 
281   return std::unique_ptr<Table>(new Table(
282       table
283           .ExtendWithColumn("layout_depth", std::move(layout_depth_column),
284                             TypedColumn<int64_t>::default_flags())
285           .ExtendWithColumn("filter_track_ids", std::move(filter_column),
286                             TypedColumn<StringPool::Id>::default_flags())));
287 }
288 
289 }  // namespace trace_processor
290 }  // namespace perfetto
291