001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.docker;
018
019import java.io.IOException;
020import java.net.URL;
021import java.util.List;
022import java.util.Map;
023
024import org.apache.logging.log4j.Logger;
025import org.apache.logging.log4j.core.LogEvent;
026import org.apache.logging.log4j.core.config.plugins.Plugin;
027import org.apache.logging.log4j.core.lookup.AbstractLookup;
028import org.apache.logging.log4j.core.lookup.StrLookup;
029import org.apache.logging.log4j.core.util.NetUtils;
030import org.apache.logging.log4j.docker.model.Container;
031import org.apache.logging.log4j.docker.model.Network;
032import org.apache.logging.log4j.status.StatusLogger;
033import org.apache.logging.log4j.util.PropertiesUtil;
034import com.fasterxml.jackson.core.type.TypeReference;
035import com.fasterxml.jackson.databind.ObjectMapper;
036
037/**
038 * Lookups up keys for for a Docker container.
039 */
040@Plugin(name = "docker", category = StrLookup.CATEGORY)
041public class DockerLookup extends AbstractLookup {
042
043    private static final Logger LOGGER = StatusLogger.getLogger();
044    private static final String DOCKER_URI = "DOCKER_URI";
045    private static final String HTTP = "http";
046    private final Container container;
047
048    /**
049     * Constructs a new instance.
050     */
051    public DockerLookup() {
052        String baseUri = System.getenv(DOCKER_URI);
053        if (baseUri == null) {
054            PropertiesUtil props = PropertiesUtil.getProperties();
055            baseUri = props.getStringProperty(DOCKER_URI);
056        }
057        if (baseUri == null) {
058            LOGGER.warn("No Docker URI provided. Docker information is unavailable");
059            container = null;
060            return;
061        }
062        Container current = null;
063        try {
064            URL url= new URL(baseUri + "/containers/json");
065            if (url.getProtocol().equals(HTTP)) {
066                String macAddr = NetUtils.getMacAddressString();
067                ObjectMapper objectMapper = new ObjectMapper();
068                List<Container> containerList = objectMapper.readValue(url, new TypeReference<List<Container>>(){});
069
070                for (Container container : containerList) {
071                    if (macAddr != null && container.getNetworkSettings() != null) {
072                        Map<String, Network> networks = container.getNetworkSettings().getNetworks();
073                        if (networks != null) {
074                            for (Network network: networks.values()) {
075                                if (macAddr.equals(network.getMacAddress())) {
076                                    current = container;
077                                    break;
078                                }
079                            }
080                        }
081                    }
082                    if (current != null) {
083                        break;
084                    }
085                }
086            }
087            if (current == null) {
088                LOGGER.warn("Unable to determine current container");
089            }
090        } catch (IOException ioe) {
091            LOGGER.warn("Unable to read container information: " + ioe.getMessage());
092        }
093        container = current;
094    }
095
096    @Override
097    public String lookup(LogEvent event, String key) {
098        if (container == null) {
099            return null;
100        }
101        switch (key) {
102            case "shortContainerId": {
103                return container.getId().substring(0, 12);
104            }
105            case "containerId": {
106                return container.getId();
107            }
108            case "containerName": {
109                if (container.getNames().size() > 1) {
110                    return container.getNames().toString();
111                }
112                return container.getNames().get(0);
113            }
114            case "shortImageId": {
115                return container.getImageId().substring(0, 12);
116            }
117            case "imageId": {
118                return container.getImageId();
119            }
120            case "imageName": {
121                return container.getImage();
122            }
123            default:
124                return null;
125        }
126    }
127}