summaryrefslogtreecommitdiffstats
path: root/vespa-hadoop/src/main/java/com/yahoo/vespa/hadoop/pig/VespaStorage.java
blob: a564dfac25d58f517752c9104b4664f2cdc27c4e (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hadoop.pig;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.vespa.hadoop.mapreduce.VespaOutputFormat;
import com.yahoo.vespa.hadoop.mapreduce.util.TupleTools;
import com.yahoo.vespa.hadoop.mapreduce.util.VespaConfiguration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.OutputFormat;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.pig.ResourceSchema;
import org.apache.pig.StoreFunc;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.impl.util.UDFContext;

import java.io.*;
import java.util.Base64;
import java.util.Map;
import java.util.Properties;

/**
 * A small Pig UDF wrapper around the Vespa http client for
 * feeding data into a Vespa endpoint.
 *
 * @author lesters
 */
@SuppressWarnings("rawtypes")
public class VespaStorage extends StoreFunc {

    private final boolean createDocOp;
    private final String template;
    private final VespaDocumentOperation.Operation operation;

    private String signature = null;
    private RecordWriter recordWriter = null;
    private ResourceSchema resourceSchema = null;

    private static final String PROPERTY_CREATE_DOC_OP = "create-document-operation";
    private static final String PROPERTY_ID_TEMPLATE = "docid";
    private static final String PROPERTY_OPERATION = "operation";
    private static final String PROPERTY_RESOURCE_SCHEMA = "resource_schema";

    Properties properties = new Properties();

    public VespaStorage() {
        createDocOp = false;
        template = null;
        operation = null;
    }

    public VespaStorage(String... params) {
        properties = VespaConfiguration.loadProperties(params);
        createDocOp = Boolean.parseBoolean(properties.getProperty(PROPERTY_CREATE_DOC_OP, "false"));
        operation = VespaDocumentOperation.Operation.fromString(properties.getProperty(PROPERTY_OPERATION, "put"));
        template = properties.getProperty(PROPERTY_ID_TEMPLATE);
    }


    @Override
    public OutputFormat getOutputFormat() throws IOException {
        return new VespaOutputFormat(properties);
    }


    @Override
    public void setStoreLocation(String endpoint, Job job) throws IOException {
        properties.setProperty(VespaConfiguration.ENDPOINT, endpoint);
    }


    @Override
    public void prepareToWrite(RecordWriter recordWriter) throws IOException {
        this.recordWriter = recordWriter;
        this.resourceSchema = getResourceSchema();
    }


    @SuppressWarnings("unchecked")
    @Override
    public void putNext(Tuple tuple) throws IOException {
        if (tuple == null || tuple.size() == 0) {
            return;
        }

        String data = null;
        if (createDocOp) {
            data = createDocumentOperation(tuple);
        } else if (!tuple.isNull(0)) {
            data = tuple.get(0).toString(); // assume single field with correctly formatted doc op.
        }

        if (data == null || data.length() == 0) {
            return;
        }

        try {
            recordWriter.write(0, data);
        } catch (InterruptedException e) {
            throw new IOException(e);
        }
    }


    @Override
    public void checkSchema(ResourceSchema resourceSchema) throws IOException {
        setResourceSchema(resourceSchema);
    }


    @Override
    public String relToAbsPathForStoreLocation(String endpoint, Path path) throws IOException {
        return endpoint;
    }


    @Override
    public void setStoreFuncUDFContextSignature(String s) {
        this.signature = s;
    }


    @Override
    public void cleanupOnFailure(String s, Job job) throws IOException {
    }


    @Override
    public void cleanupOnSuccess(String s, Job job) throws IOException {
    }


    private ResourceSchema getResourceSchema() throws IOException {
        Properties properties = getUDFProperties();
        return base64Deserialize(properties.getProperty(PROPERTY_RESOURCE_SCHEMA));
    }


    private void setResourceSchema(ResourceSchema schema) throws IOException {
        Properties properties = getUDFProperties();
        if (properties.getProperty(PROPERTY_RESOURCE_SCHEMA) == null) {
            properties.setProperty(PROPERTY_RESOURCE_SCHEMA, base64Serialize(schema));
        }
    }


    private Properties getUDFProperties() {
        String[] context = { signature };
        return UDFContext.getUDFContext().getUDFProperties(getClass(), context);
    }


    private String createDocumentOperation(Tuple tuple) throws IOException {
        if (tuple == null || tuple.size() == 0) {
            return null;
        }
        if (resourceSchema == null) {
            return null;
        }

        Map<String, Object> fields = TupleTools.tupleMap(resourceSchema, tuple);
        String docId = TupleTools.toString(fields, template);

        Schema schema = Schema.getPigSchema(resourceSchema);
        return VespaDocumentOperation.create(operation, docId, fields, properties, schema);
    }

    public static String base64Serialize(ResourceSchema resourceSchema) throws IOException {
        byte[] bytes = new ObjectMapper().writeValueAsBytes(resourceSchema);
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static ResourceSchema  base64Deserialize(String s) throws IOException {
        byte[] data = Base64.getDecoder().decode(s);
        return new ObjectMapper().readValue(data, ResourceSchema.class);
    }
}