Move invoice generation to billing bucket and improve emailing

This moves the new pipeline's invoice generation to the billing bucket, under the 'invoices/yyyy-MM' subdirectory.

This also changes the invoice e-mail to use a multipart message that attaches the invoice to the e-mail, to guarantee the correct MIME type and download.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=181746191
This commit is contained in:
larryruili 2018-01-12 08:18:49 -08:00 committed by Ben McIlwain
parent 5726f1dc4e
commit a42f18798e
16 changed files with 477 additions and 133 deletions

View file

@ -14,15 +14,29 @@
package google.registry.billing;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.common.collect.ImmutableList;
import com.google.common.io.CharStreams;
import google.registry.billing.BillingModule.InvoiceDirectoryPrefix;
import google.registry.config.RegistryConfig.Config;
import google.registry.gcs.GcsUtils;
import google.registry.util.FormattingLogger;
import google.registry.util.Retrier;
import google.registry.util.SendEmailService;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.inject.Inject;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import org.joda.time.YearMonth;
/** Utility functions for sending emails involving monthly invoices. */
@ -31,55 +45,104 @@ class BillingEmailUtils {
private final SendEmailService emailService;
private final YearMonth yearMonth;
private final String alertSenderAddress;
private final String alertRecipientAddress;
private final ImmutableList<String> invoiceEmailRecipients;
// TODO(larryruili): Replace this bucket after verifying 2017-12 output.
private final String beamBucketUrl;
private final String billingBucket;
private final String invoiceDirectoryPrefix;
private final GcsUtils gcsUtils;
private final Retrier retrier;
@Inject
BillingEmailUtils(
SendEmailService emailService,
YearMonth yearMonth,
@Config("alertSenderEmailAddress") String alertSenderAddress,
@Config("alertRecipientEmailAddress") String alertRecipientAddress,
@Config("invoiceEmailRecipients") ImmutableList<String> invoiceEmailRecipients,
@Config("apacheBeamBucketUrl") String beamBucketUrl) {
@Config("billingBucket") String billingBucket,
@InvoiceDirectoryPrefix String invoiceDirectoryPrefix,
GcsUtils gcsUtils,
Retrier retrier) {
this.emailService = emailService;
this.yearMonth = yearMonth;
this.alertSenderAddress = alertSenderAddress;
this.alertRecipientAddress = alertRecipientAddress;
this.invoiceEmailRecipients = invoiceEmailRecipients;
this.beamBucketUrl = beamBucketUrl;
this.billingBucket = billingBucket;
this.invoiceDirectoryPrefix = invoiceDirectoryPrefix;
this.gcsUtils = gcsUtils;
this.retrier = retrier;
}
private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass();
/**
* Sends a link to the generated overall invoice in GCS.
*
* <p>Note the users receiving the e-mail should have access to the object or bucket, via an
* authorization mechanism such as IAM.
*/
void emailInvoiceLink() {
// TODO(larryruili): Add read permissions for appropriate buckets.
try {
String beamBucket = beamBucketUrl.replaceFirst("gs://", "");
Message msg = emailService.createMessage();
msg.setFrom(new InternetAddress(alertSenderAddress));
for (String recipient : invoiceEmailRecipients) {
msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
}
msg.setSubject(String.format("Domain Registry invoice data %s", yearMonth.toString()));
msg.setText(
String.format(
"Link to invoice on GCS:\nhttps://storage.cloud.google.com/%s/%s",
beamBucket,
/** Sends an e-mail to all expected recipients with an attached overall invoice from GCS. */
void emailOverallInvoice() {
retrier.callWithRetry(
() -> {
String invoiceFile =
String.format(
"%s%s-%s.csv",
BillingModule.RESULTS_DIRECTORY_PREFIX,
BillingModule.OVERALL_INVOICE_PREFIX,
yearMonth.toString())));
emailService.sendMessage(msg);
} catch (MessagingException e) {
// TODO(larryruili): Replace with retrier with final failure email settings.
logger.warning(e, "E-mail service failed due to %s");
}
"%s-%s.csv", BillingModule.OVERALL_INVOICE_PREFIX, yearMonth.toString());
GcsFilename invoiceFilename =
new GcsFilename(billingBucket, invoiceDirectoryPrefix + invoiceFile);
try (InputStream in = gcsUtils.openInputStream(invoiceFilename)) {
Message msg = emailService.createMessage();
msg.setFrom(new InternetAddress(alertSenderAddress));
for (String recipient : invoiceEmailRecipients) {
msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
}
msg.setSubject(String.format("Domain Registry invoice data %s", yearMonth.toString()));
Multipart multipart = new MimeMultipart();
BodyPart textPart = new MimeBodyPart();
textPart.setText(
String.format(
"Attached is the %s invoice for the domain registry.", yearMonth.toString()));
multipart.addBodyPart(textPart);
BodyPart invoicePart = new MimeBodyPart();
String invoiceData = CharStreams.toString(new InputStreamReader(in, UTF_8));
invoicePart.setContent(invoiceData, "text/csv; charset=utf-8");
invoicePart.setFileName(invoiceFile);
multipart.addBodyPart(invoicePart);
msg.setContent(multipart);
msg.saveChanges();
emailService.sendMessage(msg);
}
},
new Retrier.FailureReporter() {
@Override
public void beforeRetry(Throwable thrown, int failures, int maxAttempts) {}
@Override
public void afterFinalFailure(Throwable thrown, int failures) {
sendAlertEmail(
String.format("Emailing invoice failed due to %s", thrown.getMessage()));
}
},
IOException.class,
MessagingException.class);
}
/** Sends an e-mail to the provided alert e-mail address indicating a billing failure. */
void sendAlertEmail(String body) {
retrier.callWithRetry(
() -> {
Message msg = emailService.createMessage();
msg.setFrom(new InternetAddress(alertSenderAddress));
msg.addRecipient(RecipientType.TO, new InternetAddress(alertRecipientAddress));
msg.setSubject(String.format("Billing Pipeline Alert: %s", yearMonth.toString()));
msg.setText(body);
emailService.sendMessage(msg);
return null;
},
new Retrier.FailureReporter() {
@Override
public void beforeRetry(Throwable thrown, int failures, int maxAttempts) {}
@Override
public void afterFinalFailure(Throwable thrown, int failures) {
logger.severe(thrown, "The alert e-mail system failed.");
}
},
MessagingException.class);
}
}

View file

@ -15,6 +15,7 @@
package google.registry.billing;
import static google.registry.request.RequestParameters.extractRequiredParameter;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential;
import com.google.api.client.http.HttpTransport;
@ -25,9 +26,13 @@ import dagger.Module;
import dagger.Provides;
import google.registry.config.RegistryConfig.Config;
import google.registry.request.Parameter;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.util.Set;
import java.util.function.Function;
import javax.inject.Qualifier;
import javax.servlet.http.HttpServletRequest;
import org.joda.time.YearMonth;
/** Module for dependencies required by monthly billing actions. */
@Module
@ -35,13 +40,12 @@ public final class BillingModule {
public static final String DETAIL_REPORT_PREFIX = "invoice_details";
public static final String OVERALL_INVOICE_PREFIX = "CRR-INV";
public static final String INVOICES_DIRECTORY = "invoices";
static final String PARAM_JOB_ID = "jobId";
static final String PARAM_DIRECTORY_PREFIX = "directoryPrefix";
static final String PARAM_YEAR_MONTH = "yearMonth";
static final String BILLING_QUEUE = "billing";
static final String CRON_QUEUE = "retryable-cron-tasks";
// TODO(larryruili): Replace with invoices/yyyy-MM after verifying 2017-12 invoice.
static final String RESULTS_DIRECTORY_PREFIX = "results/";
private static final String CLOUD_PLATFORM_SCOPE =
"https://www.googleapis.com/auth/cloud-platform";
@ -53,11 +57,10 @@ public final class BillingModule {
return extractRequiredParameter(req, PARAM_JOB_ID);
}
/** Provides the subdirectory under a GCS bucket that we copy detail reports from. */
@Provides
@Parameter(PARAM_DIRECTORY_PREFIX)
static String provideDirectoryPrefix(HttpServletRequest req) {
return extractRequiredParameter(req, PARAM_DIRECTORY_PREFIX);
@InvoiceDirectoryPrefix
static String provideDirectoryPrefix(YearMonth yearMonth) {
return String.format("%s/%s/", INVOICES_DIRECTORY, yearMonth.toString());
}
/** Constructs a {@link Dataflow} API client with default settings. */
@ -75,4 +78,10 @@ public final class BillingModule {
.setApplicationName(String.format("%s billing", projectId))
.build();
}
/** Dagger qualifier for the subdirectory we stage to/upload from. */
@Qualifier
@Documented
@Retention(RUNTIME)
@interface InvoiceDirectoryPrefix{}
}

View file

@ -22,11 +22,11 @@ import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;
import com.google.common.net.MediaType;
import google.registry.billing.BillingModule.InvoiceDirectoryPrefix;
import google.registry.config.RegistryConfig.Config;
import google.registry.gcs.GcsUtils;
import google.registry.model.registrar.Registrar;
import google.registry.request.Action;
import google.registry.request.Parameter;
import google.registry.request.Response;
import google.registry.request.auth.Auth;
import google.registry.storage.drive.DriveConnection;
@ -45,39 +45,39 @@ public final class CopyDetailReportsAction implements Runnable {
private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass();
// TODO(larryruili): Replace this bucket with the billing bucket after verifying 2017-12 output.
private final String beamBucketUrl;
private final String folderPrefix;
private final String billingBucket;
private final String invoiceDirectoryPrefix;
private final DriveConnection driveConnection;
private final GcsUtils gcsUtils;
private final Retrier retrier;
private final Response response;
private final BillingEmailUtils emailUtils;
@Inject
CopyDetailReportsAction(
@Config("apacheBeamBucketUrl") String beamBucketUrl,
@Parameter(BillingModule.PARAM_DIRECTORY_PREFIX) String folderPrefix,
@Config("billingBucket") String billingBucket,
@InvoiceDirectoryPrefix String invoiceDirectoryPrefix,
DriveConnection driveConnection,
GcsUtils gcsUtils,
Retrier retrier,
Response response) {
this.beamBucketUrl = beamBucketUrl;
this.folderPrefix = folderPrefix;
Response response,
BillingEmailUtils emailUtils) {
this.billingBucket = billingBucket;
this.invoiceDirectoryPrefix = invoiceDirectoryPrefix;
this.driveConnection = driveConnection;
this.gcsUtils = gcsUtils;
this.retrier = retrier;
this.response = response;
this.emailUtils = emailUtils;
}
@Override
public void run() {
// Strip the URL prefix from the beam bucket
String beamBucket = beamBucketUrl.replace("gs://", "");
ImmutableList<String> detailReportObjectNames;
try {
detailReportObjectNames =
gcsUtils
.listFolderObjects(beamBucket, folderPrefix)
.listFolderObjects(billingBucket, invoiceDirectoryPrefix)
.stream()
.filter(objectName -> objectName.startsWith(BillingModule.DETAIL_REPORT_PREFIX))
.collect(ImmutableList.toImmutableList());
@ -93,7 +93,6 @@ public final class CopyDetailReportsAction implements Runnable {
// TODO(larryruili): Determine a safer way of enforcing this.
String registrarId = detailReportName.split("_")[3];
Optional<Registrar> registrar = Registrar.loadByClientId(registrarId);
// TODO(larryruili): Send an email alert if any report fails to be copied for any reason.
if (!registrar.isPresent()) {
logger.warningfmt(
"Registrar %s not found in database for file %s", registrar, detailReportName);
@ -109,7 +108,7 @@ public final class CopyDetailReportsAction implements Runnable {
() -> {
try (InputStream input =
gcsUtils.openInputStream(
new GcsFilename(beamBucket, folderPrefix + detailReportName))) {
new GcsFilename(billingBucket, invoiceDirectoryPrefix + detailReportName))) {
driveConnection.createFile(
detailReportName,
MediaType.CSV_UTF_8,
@ -117,7 +116,19 @@ public final class CopyDetailReportsAction implements Runnable {
ByteStreams.toByteArray(input));
logger.infofmt(
"Published detail report for %s to folder %s using GCS file gs://%s/%s.",
registrarId, driveFolderId, beamBucket, detailReportName);
registrarId, driveFolderId, billingBucket, detailReportName);
}
},
new Retrier.FailureReporter() {
@Override
public void beforeRetry(Throwable thrown, int failures, int maxAttempts) {}
@Override
public void afterFinalFailure(Throwable thrown, int failures) {
emailUtils.sendAlertEmail(
String.format(
"Warning: CopyDetailReportsAction failed.\nEncountered: %s on file: %s",
thrown.getMessage(), detailReportName));
}
},
IOException.class);

View file

@ -53,22 +53,28 @@ public class GenerateInvoicesAction implements Runnable {
private final String projectId;
private final String beamBucketUrl;
private final String invoiceTemplateUrl;
private final YearMonth yearMonth;
private final Dataflow dataflow;
private final Response response;
private final BillingEmailUtils emailUtils;
@Inject
GenerateInvoicesAction(
@Config("projectId") String projectId,
@Config("apacheBeamBucketUrl") String beamBucketUrl,
@Config("invoiceTemplateUrl") String invoiceTemplateUrl,
YearMonth yearMonth,
Dataflow dataflow,
Response response) {
Response response,
BillingEmailUtils emailUtils) {
this.projectId = projectId;
this.beamBucketUrl = beamBucketUrl;
this.invoiceTemplateUrl = invoiceTemplateUrl;
this.yearMonth = yearMonth;
this.dataflow = dataflow;
this.response = response;
this.emailUtils = emailUtils;
}
@Override
@ -88,13 +94,14 @@ public class GenerateInvoicesAction implements Runnable {
.projects()
.templates()
.launch(projectId, params)
.setGcsPath(beamBucketUrl + "/templates/invoicing")
.setGcsPath(invoiceTemplateUrl)
.execute();
logger.infofmt("Got response: %s", launchResponse.getJob().toPrettyString());
String jobId = launchResponse.getJob().getId();
enqueuePublishTask(jobId);
} catch (IOException e) {
logger.warningfmt("Template Launch failed due to: %s", e.getMessage());
emailUtils.sendAlertEmail(String.format("Template Launch failed due to %s", e.getMessage()));
response.setStatus(SC_INTERNAL_SERVER_ERROR);
response.setContentType(MediaType.PLAIN_TEXT_UTF_8);
response.setPayload(String.format("Template launch failed: %s", e.getMessage()));
@ -111,7 +118,9 @@ public class GenerateInvoicesAction implements Runnable {
.method(TaskOptions.Method.POST)
// Dataflow jobs tend to take about 10 minutes to complete.
.countdownMillis(Duration.standardMinutes(10).getMillis())
.param(BillingModule.PARAM_JOB_ID, jobId);
.param(BillingModule.PARAM_JOB_ID, jobId)
// Need to pass this through to ensure transitive yearMonth dependencies are satisfied.
.param(BillingModule.PARAM_YEAR_MONTH, yearMonth.toString());
QueueFactory.getQueue(BillingModule.BILLING_QUEUE).add(publishTask);
}
}

View file

@ -33,6 +33,7 @@ import google.registry.request.auth.Auth;
import google.registry.util.FormattingLogger;
import java.io.IOException;
import javax.inject.Inject;
import org.joda.time.YearMonth;
/**
* Uploads the results of the {@link google.registry.beam.InvoicingPipeline}.
@ -55,6 +56,7 @@ public class PublishInvoicesAction implements Runnable {
private final BillingEmailUtils emailUtils;
private final Dataflow dataflow;
private final Response response;
private final YearMonth yearMonth;
@Inject
PublishInvoicesAction(
@ -62,12 +64,14 @@ public class PublishInvoicesAction implements Runnable {
@Parameter(BillingModule.PARAM_JOB_ID) String jobId,
BillingEmailUtils emailUtils,
Dataflow dataflow,
Response response) {
Response response,
YearMonth yearMonth) {
this.projectId = projectId;
this.jobId = jobId;
this.emailUtils = emailUtils;
this.dataflow = dataflow;
this.response = response;
this.yearMonth = yearMonth;
}
static final String PATH = "/_dr/task/publishInvoices";
@ -83,12 +87,13 @@ public class PublishInvoicesAction implements Runnable {
logger.infofmt("Dataflow job %s finished successfully, publishing results.", jobId);
response.setStatus(SC_OK);
enqueueCopyDetailReportsTask();
emailUtils.emailInvoiceLink();
emailUtils.emailOverallInvoice();
break;
case JOB_FAILED:
logger.severefmt("Dataflow job %s finished unsuccessfully.", jobId);
response.setStatus(SC_NO_CONTENT);
// TODO(larryruili): Email failure message
emailUtils.sendAlertEmail(
String.format("Dataflow job %s ended in status failure.", jobId));
break;
default:
logger.infofmt("Job in non-terminal state %s, retrying:", state);
@ -96,18 +101,18 @@ public class PublishInvoicesAction implements Runnable {
break;
}
} catch (IOException e) {
emailUtils.sendAlertEmail(String.format("Publish action failed due to %s", e.getMessage()));
response.setStatus(SC_INTERNAL_SERVER_ERROR);
response.setContentType(MediaType.PLAIN_TEXT_UTF_8);
response.setPayload(String.format("Template launch failed: %s", e.getMessage()));
}
}
private static void enqueueCopyDetailReportsTask() {
private void enqueueCopyDetailReportsTask() {
TaskOptions copyDetailTask =
TaskOptions.Builder.withUrl(CopyDetailReportsAction.PATH)
.method(TaskOptions.Method.POST)
.param(
BillingModule.PARAM_DIRECTORY_PREFIX, BillingModule.RESULTS_DIRECTORY_PREFIX);
.param(BillingModule.PARAM_YEAR_MONTH, yearMonth.toString());
QueueFactory.getQueue(BillingModule.CRON_QUEUE).add(copyDetailTask);
}
}