summaryrefslogtreecommitdiffstats
path: root/vespalog/src/main/java/com/yahoo/log/Util.java
blob: 062d6acf960b50321cf5c4cb5ffb0fbe8d50977a (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
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.log;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;

/**
 *
 * @author  Bjorn Borud
 * @author arnej27959
 *
 */
public class Util {

    /**
     * We do not have direct access to the <code>gethostname</code>
     * system call, so we have to fake it.
     */
    public static String getHostName () {
        String hostname = "-";
        try {
            Process p = Runtime.getRuntime().exec("hostname");
            BufferedReader r = new BufferedReader(
                    new InputStreamReader(p.getInputStream(), "UTF-8"));
            hostname = r.readLine();
            if (hostname != null) {
                return hostname;
            }
        }
        catch (java.io.IOException e) {}
        try {
            hostname = InetAddress.getLocalHost().getHostName();
            return hostname;
        }
        catch (java.net.UnknownHostException e) {}
        return "-";
    }

    /**
     * Emulate the getpid() system call
     **/
    public static String getPID() {
        try {
            Process p = Runtime.getRuntime().exec(
                    new String[] {"perl", "-e", "print getppid().\"\\n\";"}
            );
            BufferedReader r = new BufferedReader(
                    new InputStreamReader(p.getInputStream(), "UTF-8"));
            String line = r.readLine();
            p.destroy();
            int pid = Integer.parseInt(line);
            if (pid > 0) {
                return Integer.toString(pid);
            }
        } catch(Exception e) {
            // any problem handled by return below
        }
        return "-";
    }
}