aboutsummaryrefslogtreecommitdiffstats
path: root/yt/cpp/mapreduce/interface/config.cpp
blob: e159780ba90709711d45efc69b48fc9b1565fe03 (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
#include "config.h"

#include "operation.h"

#include <yt/cpp/mapreduce/interface/logging/yt_log.h>

#include <library/cpp/json/json_reader.h>
#include <library/cpp/svnversion/svnversion.h>

#include <library/cpp/yson/node/node_builder.h>
#include <library/cpp/yson/node/node_io.h>

#include <library/cpp/yson/json/yson2json_adapter.h>

#include <util/string/strip.h>
#include <util/folder/dirut.h>
#include <util/folder/path.h>
#include <util/stream/file.h>
#include <util/generic/singleton.h>
#include <util/string/builder.h>
#include <util/string/cast.h>
#include <util/string/type.h>
#include <util/system/hostname.h>
#include <util/system/user.h>
#include <util/system/env.h>

namespace NYT {

////////////////////////////////////////////////////////////////////////////////

bool TConfig::GetBool(const char* var, bool defaultValue)
{
    TString val = GetEnv(var, "");
    if (val.empty()) {
        return defaultValue;
    }
    return IsTrue(val);
}

int TConfig::GetInt(const char* var, int defaultValue)
{
    int result = 0;
    TString val = GetEnv(var, "");
    if (val.empty()) {
        return defaultValue;
    }
    try {
        result = FromString<int>(val);
    } catch (const yexception& e) {
        ythrow yexception() << "Cannot parse " << var << '=' << val << " as integer: " << e.what();
    }
    return result;
}

TDuration TConfig::GetDuration(const char* var, TDuration defaultValue)
{
    return TDuration::Seconds(GetInt(var, defaultValue.Seconds()));
}

EEncoding TConfig::GetEncoding(const char* var)
{
    const TString encodingName = GetEnv(var, "identity");
    EEncoding encoding;
    if (TryFromString(encodingName, encoding)) {
        return encoding;
    } else {
        ythrow yexception() << var << ": encoding '" << encodingName << "' is not supported";
    }
}

 EUploadDeduplicationMode TConfig::GetUploadingDeduplicationMode(
        const char* var,
        EUploadDeduplicationMode defaultValue)
{
    const TString deduplicationMode = GetEnv(var, TEnumTraits<EUploadDeduplicationMode>::ToString(defaultValue));
    return TEnumTraits<EUploadDeduplicationMode>::FromString(deduplicationMode);
}

void TConfig::ValidateToken(const TString& token)
{
    for (size_t i = 0; i < token.size(); ++i) {
        ui8 ch = token[i];
        if (ch < 0x21 || ch > 0x7e) {
            ythrow yexception() << "Incorrect token character '" << ch << "' at position " << i;
        }
    }
}

TString TConfig::LoadTokenFromFile(const TString& tokenPath)
{
    TFsPath path(tokenPath);
    return path.IsFile() ? Strip(TIFStream(path).ReadAll()) : TString();
}

TNode TConfig::LoadJsonSpec(const TString& strSpec)
{
    TNode spec;
    TStringInput input(strSpec);
    TNodeBuilder builder(&spec);
    TYson2JsonCallbacksAdapter callbacks(&builder);

    Y_ENSURE(NJson::ReadJson(&input, &callbacks), "Cannot parse json spec: " << strSpec);
    Y_ENSURE(spec.IsMap(), "Json spec is not a map");

    return spec;
}

TRichYPath TConfig::LoadApiFilePathOptions(const TString& ysonMap)
{
    TNode attributes;
    try {
        attributes = NodeFromYsonString(ysonMap);
    } catch (const yexception& exc) {
        ythrow yexception() << "Failed to parse YT_API_FILE_PATH_OPTIONS (it must be yson map): " << exc;
    }
    TNode pathNode = "";
    pathNode.Attributes() = attributes;
    TRichYPath path;
    Deserialize(path, pathNode);
    return path;
}

void TConfig::LoadToken()
{
    if (auto envToken = GetEnv("YT_TOKEN")) {
        Token = envToken;
    } else if (auto envToken = GetEnv("YT_SECURE_VAULT_YT_TOKEN")) {
        // If this code runs inside an vanilla peration in YT
        // it should not use regular environment variable `YT_TOKEN`
        // because it would be visible in UI.
        // Token should be passed via `secure_vault` parameter in operation spec.
        Token = envToken;
    } else if (auto tokenPath = GetEnv("YT_TOKEN_PATH")) {
        Token = LoadTokenFromFile(tokenPath);
    } else {
        Token = LoadTokenFromFile(GetHomeDir() + "/.yt/token");
    }
    ValidateToken(Token);
}

void TConfig::LoadSpec()
{
    TString strSpec = GetEnv("YT_SPEC", "{}");
    Spec = LoadJsonSpec(strSpec);

    strSpec = GetEnv("YT_TABLE_WRITER", "{}");
    TableWriter = LoadJsonSpec(strSpec);
}

void TConfig::LoadTimings()
{
    ConnectTimeout = GetDuration("YT_CONNECT_TIMEOUT",
        TDuration::Seconds(10));

    SocketTimeout = GetDuration("YT_SOCKET_TIMEOUT",
        GetDuration("YT_SEND_RECEIVE_TIMEOUT", // common
            TDuration::Seconds(60)));

    AddressCacheExpirationTimeout = TDuration::Minutes(15);

    CacheLockTimeoutPerGb = TDuration::MilliSeconds(1000.0 * 1_GB * 8 / 20_MB); // 20 Mbps = 20 MBps / 8.

    TxTimeout = GetDuration("YT_TX_TIMEOUT",
        TDuration::Seconds(120));

    PingTimeout = GetDuration("YT_PING_TIMEOUT",
        TDuration::Seconds(5));

    PingInterval = GetDuration("YT_PING_INTERVAL",
        TDuration::Seconds(5));

    WaitLockPollInterval = TDuration::Seconds(5);

    RetryInterval = GetDuration("YT_RETRY_INTERVAL",
        TDuration::Seconds(3));

    ChunkErrorsRetryInterval = GetDuration("YT_CHUNK_ERRORS_RETRY_INTERVAL",
        TDuration::Seconds(60));

    RateLimitExceededRetryInterval = GetDuration("YT_RATE_LIMIT_EXCEEDED_RETRY_INTERVAL",
        TDuration::Seconds(60));

    StartOperationRetryInterval = GetDuration("YT_START_OPERATION_RETRY_INTERVAL",
        TDuration::Seconds(60));

    HostListUpdateInterval = TDuration::Seconds(60);
}

void TConfig::Reset()
{
    Hosts = GetEnv("YT_HOSTS", "hosts");
    Pool = GetEnv("YT_POOL");
    Prefix = GetEnv("YT_PREFIX");
    ApiVersion = GetEnv("YT_VERSION", "v3");
    LogLevel = GetEnv("YT_LOG_LEVEL", "error");

    ContentEncoding = GetEncoding("YT_CONTENT_ENCODING");
    AcceptEncoding = GetEncoding("YT_ACCEPT_ENCODING");

    GlobalTxId = GetEnv("YT_TRANSACTION", "");

    UseAsyncTxPinger = false;
    AsyncHttpClientThreads = 1;
    AsyncTxPingerPoolThreads = 1;

    ForceIpV4 = GetBool("YT_FORCE_IPV4");
    ForceIpV6 = GetBool("YT_FORCE_IPV6");
    UseHosts = GetBool("YT_USE_HOSTS", true);

    LoadToken();
    LoadSpec();
    LoadTimings();

    CacheUploadDeduplicationMode = GetUploadingDeduplicationMode("YT_UPLOAD_DEDUPLICATION", EUploadDeduplicationMode::Host);

    RetryCount = Max(GetInt("YT_RETRY_COUNT", 10), 1);
    ReadRetryCount = Max(GetInt("YT_READ_RETRY_COUNT", 30), 1);
    StartOperationRetryCount = Max(GetInt("YT_START_OPERATION_RETRY_COUNT", 30), 1);

    RemoteTempFilesDirectory = GetEnv("YT_FILE_STORAGE",
        "//tmp/yt_wrapper/file_storage");
    RemoteTempTablesDirectory = GetEnv("YT_TEMP_TABLES_STORAGE",
        "//tmp/yt_wrapper/table_storage");
    RemoteTempTablesDirectory = GetEnv("YT_TEMP_DIR",
        RemoteTempTablesDirectory);

    InferTableSchema = false;

    UseClientProtobuf = GetBool("YT_USE_CLIENT_PROTOBUF", false);
    NodeReaderFormat = ENodeReaderFormat::Auto;
    ProtobufFormatWithDescriptors = true;

    MountSandboxInTmpfs = GetBool("YT_MOUNT_SANDBOX_IN_TMPFS");

    ApiFilePathOptions = LoadApiFilePathOptions(GetEnv("YT_API_FILE_PATH_OPTIONS", "{}"));

    ConnectionPoolSize = GetInt("YT_CONNECTION_POOL_SIZE", 16);

    TraceHttpRequestsMode = FromString<ETraceHttpRequestsMode>(to_lower(GetEnv("YT_TRACE_HTTP_REQUESTS", "never")));

    CommandsWithFraming = {
        "read_table",
        "get_table_columnar_statistics",
        "get_job_input",
        "concatenate",
        "partition_tables",
    };
}

TConfig::TConfig()
{
    Reset();
}

TConfigPtr TConfig::Get()
{
    struct TConfigHolder
    {
        TConfigHolder()
            : Config(::MakeIntrusive<TConfig>())
        { }

        TConfigPtr Config;
    };

    return Singleton<TConfigHolder>()->Config;
}

////////////////////////////////////////////////////////////////////////////////

TProcessState::TProcessState()
{
    try {
        FqdnHostName = ::FQDNHostName();
    } catch (const yexception& e) {
        try {
            FqdnHostName = ::HostName();
        } catch (const yexception& e) {
            ythrow yexception() << "Cannot get fqdn and host name: " << e.what();
        }
    }

    try {
        UserName = ::GetUsername();
    } catch (const yexception& e) {
#ifdef _win_
        ythrow yexception() << "Cannot get user name: " << e.what();
#else
        UserName = "u" + ToString(geteuid());
#endif
    }

    Pid = static_cast<int>(getpid());

    if (!ClientVersion) {
        ClientVersion = ::TStringBuilder() << "YT C++ native " << GetProgramCommitId();
    }
}

static TString CensorString(TString input)
{
    static const TString prefix = "AQAD-";
    if (input.find(prefix) == TString::npos) {
        return input;
    } else {
        return TString(input.size(), '*');
    }
}

void TProcessState::SetCommandLine(int argc, const char* argv[])
{
    for (int i = 0; i < argc; ++i) {
        CommandLine.push_back(argv[i]);
        CensoredCommandLine.push_back(CensorString(CommandLine.back()));
    }
}

TProcessState* TProcessState::Get()
{
    return Singleton<TProcessState>();
}

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT