aboutsummaryrefslogtreecommitdiffstats
path: root/vespaclient/src/perl/lib/Yahoo/Vespa/VespaModel.pm
blob: fd324540bbab8cfb99191725b5d750d9bb14e91b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#
# Vespa model
#
# Make vespa model information available for tools. To for instance get an
# overview of where services are running.
#
# Possible improvements:
#
#   - Depending on config Rest API and config server might be better than
#     depending on vespa-get-config tool and config format.
#   - Support direct communication with config server if config proxy is not
#     running (unless vespa-get-config does that for us)
#   - Support specifying config server, to be able to run tool external from the
#     vespa system to talk to.
#   - Return a list of all matching sockets instead of first found.
#   - Be able to specify a set of port tags needed for a match.
#

package Yahoo::Vespa::VespaModel;

use strict;
use warnings;
use Yahoo::Vespa::ArgParser;
use Yahoo::Vespa::ConsoleOutput;
use Yahoo::Vespa::Utils;

my $RETRIEVE_MODEL_CONFIG; # Allow unit tests to switch source of config info
my $MODEL;
my $CONFIG_SERVER_HOST;
my $CONFIG_SERVER_PORT;
my $CONFIG_REQUEST_TIMEOUT;

&initialize();

return 1;

######################## Externally usable functions #######################

sub registerCommandLineArguments { # ()
    setOptionHeader("Config retrieval options:");
    setHostOption(
            ['config-server'],
            \$CONFIG_SERVER_HOST,
            'Host name of config server to query');
    setPortOption(
            ['config-server-port'],
            \$CONFIG_SERVER_PORT,
            'Port to connect to config server on');
    setFloatOption(
            ['config-request-timeout'],
            \$CONFIG_REQUEST_TIMEOUT,
            'Timeout of config request');
}

sub visitServices { # (Callback)
    my $model = &get();
    my ($callback) = @_;
    my @services = @{ &getServices($model); };
    foreach my $service (sort serviceOrder @services) {
        &$callback($service);
    }
}

sub getServices {
    my $model = &get();
    my @result;
    foreach my $hostindex (keys %{ $$model{'hosts'} }) {
        my $host = ${ $$model{'hosts'} }{ $hostindex };
        foreach my $serviceindex (keys %{ $$host{'services'} }) {
            my $service = ${ $$host{'services'} }{ $serviceindex };
            my %info = (
                'name' => $$service{'name'},
                'type' => $$service{'type'},
                'configid' => $$service{'configid'},
                'cluster' => $$service{'clustername'},
                'host' => $$host{'name'}
            );
            if (exists $$service{'index'}) {
                $info{'index'} = $$service{'index'};
            }
            push @result, \%info;
        }
    }
    return \@result;
}

# Get socket for given service matching given conditions (Given as a hash)
# Legal conditions:
#   type - Service type
#   tag - Port tag
#   index - Service index
#   clustername - Name of cluster.
# Example: getSocketForService( 'type' => 'distributor', 'index' => 3,
#                               'tag' => 'http', 'tag' => 'state' );
sub getSocketForService { # (Conditions) => [{host=>$,port=>$,index=>$}...]
    my $model = &get();
    my $conditions = \@_;
    printDebug "Looking at model to find socket for a service.\n";
    &validateConditions($conditions);
    my $hosts = $$model{'hosts'};
    if (!defined $hosts) { return; }
    my @results;
    foreach my $hostindex (keys %$hosts) {
        my $host = $$hosts{$hostindex};
        my $services = $$host{'services'};
        if (defined $services) {
            printSpam "Searching services on host $$host{'name'}\n";
            foreach my $serviceindex (keys %$services) {
                my $service = $$services{$serviceindex};
                my $type = $$service{'type'};
                my $cluster = $$service{'clustername'};
                if (!&serviceTypeMatchConditions($conditions, $type)) {
                    printSpam "Unwanted service '$type'.\n";
                    next;
                }
                if (!&indexMatchConditions($conditions, $$service{'index'})) {
                    printSpam "Unwanted index '$$service{'index'}'.\n";
                    next;
                }
                if (!&clusterNameMatchConditions($conditions, $cluster)) {
                    printSpam "Unwanted index '$$service{'index'}'.\n";
                    next;
                }
                my $ports = $$service{'ports'};
                if (defined $ports) {
                    my $resultcount = 0;
                    foreach my $portindex (keys %$ports) {
                        my $port = $$ports{$portindex};
                        my $tags = $$port{'tags'};
                        if (defined $tags) {
                            if (!&tagsMatchConditions($conditions, $tags)) {
                                next;
                            }
                        }
                        push @results, { 'host' => $$host{'name'},
                                         'port' => $$port{'number'},
                                         'index' => $$service{'index'} };
                        ++$resultcount;
                    }
                    if ($resultcount == 0) {
                        printSpam "No ports with acceptable tags found. "
                                . "Ignoring $type.$$service{'index'}\n";
                    }
                } else {
                    printSpam "No ports defined. "
                            . "Ignoring $type.$$service{'index'}\n";
                }
            }
        }
    }
    return \@results;
}

############## Utility functions - Not intended for external use #############

sub initialize { # ()
    $RETRIEVE_MODEL_CONFIG = \&retrieveModelConfigDefault;
}
sub setModelRetrievalFunction { # (Function)
    $RETRIEVE_MODEL_CONFIG = $_[0];
}
sub retrieveModelConfigDefault { # ()
    my $VESPA_HOME= $ENV{'VESPA_HOME'};
    my $cmd = ${VESPA_HOME} . '/bin/vespa-get-config -n cloud.config.model -i admin/model';

    if (defined $CONFIG_REQUEST_TIMEOUT) {
        $cmd .= " -w $CONFIG_REQUEST_TIMEOUT";
    }

    if (!defined $CONFIG_SERVER_HOST) {
        my $temp = `${VESPA_HOME}/bin/vespa-print-default configservers`;
        chomp($temp);
        $CONFIG_SERVER_HOST = $temp;
    }

    if (!defined $CONFIG_SERVER_PORT) {
        my $temp = `${VESPA_HOME}/bin/vespa-print-default configserver_rpc_port`;
        chomp($temp);
        $CONFIG_SERVER_PORT = $temp;
    }
    $cmd .= " -p $CONFIG_SERVER_PORT";

    my $errors = "";
    foreach my $cfshost (split(' ', $CONFIG_SERVER_HOST)) {
        my $hostcmd = $cmd . " -s $cfshost";

        printDebug "Fetching model config '$hostcmd'.\n";
        my @data = `$hostcmd 2>&1`;
        if ($? != 0 || join(' ', @data) =~ /^error/) {
            $errors .= "Failed to get model config from config command line tool:\n"
                 . "Command: $hostcmd\n"
                 . "Exit code: $?\n"
                 . "Output: " . join("\n", @data) . "\n";
        } else {
            return @data;
        }
    }
    printError $errors;
    exitApplication(1);
}
sub fetch { # ()
    my @data = &$RETRIEVE_MODEL_CONFIG();
    $MODEL = &parseConfig(@data);
    return $MODEL;
}
sub get { # ()
    if (!defined $MODEL) {
        return &fetch();
    }
    return $MODEL;
}
sub validateConditions { # (ConditionArrayRef)
    my ($condition) = @_;
    for (my $i=0, my $n=scalar @$condition; $i<$n; $i += 2) {
        if ($$condition[$i] !~ /^(type|tag|index|clustername)$/) {
            printError "Invalid socket for service condition "
                     . "'$$condition[$i]' given.\n";
            exitApplication(1);
        }
    }
}
sub tagsMatchConditions { # (Condition, TagList) -> Bool
    my ($condition, $taglist) = @_;
    my %tags = map { $_ => 1 } @$taglist;
    for (my $i=0, my $n=scalar @$condition; $i<$n; $i += 2) {
        if ($$condition[$i] eq 'tag' && !exists $tags{$$condition[$i + 1]}) {
            return 0;
        }
    }
    return 1;
}
sub serviceTypeMatchConditions { # (Condition, ServiceType) -> Bool
    my ($condition, $type) = @_;
    for (my $i=0, my $n=scalar @$condition; $i<$n; $i += 2) {
        if ($$condition[$i] eq 'type' && $$condition[$i + 1] ne $type) {
            return 0;
        }
    }
    return 1;
}
sub clusterNameMatchConditions { # (Condition, ClusterName) -> Bool
    my ($condition, $cluster) = @_;
    for (my $i=0, my $n=scalar @$condition; $i<$n; $i += 2) {
        if ($$condition[$i] eq 'clustername' && $$condition[$i + 1] ne $cluster)
        {
            return 0;
        }
    }
    return 1;
}
sub indexMatchConditions { # (Condition, Index) -> Bool
    my ($condition, $index) = @_;
    for (my $i=0, my $n=scalar @$condition; $i<$n; $i += 2) {
        if ($$condition[$i] eq 'index' && $$condition[$i + 1] ne $index) {
            return 0;
        }
    }
    return 1;
}
sub parseConfig { # ()
    my $model = {};
    printDebug "Parsing vespa model raw config to create object tree\n";
    my $autoLineBreak = enableAutomaticLineBreaks(0);
    foreach my $line (@_) {
        chomp $line;
        printSpam "Parsing line '$line'\n";
        if ($line =~ /^hosts\[(\d+)\]\.(([a-z]+).*)$/) {
            my ($hostindex, $tag, $rest) = ($1, $3, $2);
            my $host = &getHost($hostindex, $model);
            if ($tag eq 'services') {
                &parseService($host, $rest);
            } else {
                &parseValue($host, $rest);
            }
        }
    }
    enableAutomaticLineBreaks($autoLineBreak);
    return $model;
}
sub parseService { # (Host, Line)
    my ($host, $line) = @_;
    if ($line =~ /^services\[(\d+)\].(([a-z]+).*)$/) {
        my ($serviceindex, $tag, $rest) = ($1, $3, $2);
        my $service = &getService($serviceindex, $host);
        if ($tag eq 'ports') {
            &parsePort($service, $rest);
        } else {
            &parseValue($service, $rest);
        }
    }
}
sub parsePort { # (Service, Line)
    my ($service, $line) = @_;
    if ($line =~ /^ports\[(\d+)\].(([a-z]+).*)$/) {
        my ($portindex, $tag, $rest) = ($1, $3, $2);
        my $port = &getPort($portindex, $service);
        &parseValue($port, $rest);
    }
}
sub parseValue { # (Entity, Line)
    my ($entity, $line) = @_;
    $line =~ /^(\S+) (?:\"(.*)\"|(\d+))$/ or confess "Unexpected line '$line'.";
    my ($id, $string, $number) = ($1, $2, $3);
    if ($id eq 'tags' && defined $string) {
        my @tags = split(/\s+/, $string);
        $$entity{$id} = \@tags;
    } elsif (defined $string) {
        $$entity{$id} = $string;
    } else {
        defined $number or confess "Should not happen";
        $$entity{$id} = $number;
    }
}
sub getEntity { # (Type, Index, ParentEntity)
    my ($type, $index, $parent) = @_;
    if (!exists $$parent{$type}) {
        $$parent{$type} = {};
    }
    my $list = $$parent{$type};
    if (!exists $$list{$index}) {
        $$list{$index} = {};
    }
    return $$list{$index};
}
sub getHost { # (Index, Model)
    return &getEntity('hosts', $_[0], $_[1]);
}
sub getService { # (Index, Host)
    return &getEntity('services', $_[0], $_[1]);
}
sub getPort { # (Index, Service)
    return &getEntity('ports', $_[0], $_[1]);
}
sub serviceOrder {
    if ($a->{'cluster'} ne $b->{'cluster'}) {
        return $a->{'cluster'} cmp $b->{'cluster'};
    }
    if ($a->{'type'} ne $b->{'type'}) {
        return $a->{'type'} cmp $b->{'type'};
    }
    if ($a->{'index'} != $b->{'index'}) {
        return $a->{'index'} <=> $b->{'index'};
    }
    if ($a->{'host'} ne $b->{'host'}) {
        return $a->{'host'} cmp $b->{'host'};
    }
    if ($a->{'configid'} ne $b->{'configid'}) {
        return $a->{'configid'} cmp $b->{'configid'};
    }
    confess "Unsortable elements: " . dumpStructure($a) . "\n"
                                    . dumpStructure($b) . "\n";
}