1   /*
2    * Copyright 2022 LINE Corporation
3    *
4    * LINE Corporation licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package com.linecorp.centraldogma.server.internal.mirror;
18  
19  import static com.google.common.base.MoreObjects.firstNonNull;
20  
21  import java.io.File;
22  
23  import com.google.common.collect.ImmutableList;
24  
25  import com.linecorp.centraldogma.server.command.CommandExecutor;
26  import com.linecorp.centraldogma.server.mirror.Mirror;
27  
28  import io.micrometer.core.instrument.Counter;
29  import io.micrometer.core.instrument.MeterRegistry;
30  import io.micrometer.core.instrument.Tag;
31  
32  final class MirroringTask {
33  
34      private static Iterable<Tag> generateTags(Mirror mirror, String projectName) {
35          return ImmutableList.of(
36                  Tag.of("project", projectName),
37                  Tag.of("direction", mirror.direction().name()),
38                  Tag.of("remoteBranch", firstNonNull(mirror.remoteBranch(), "")),
39                  Tag.of("remotePath", mirror.remotePath()),
40                  Tag.of("localRepo", mirror.localRepo().name()),
41                  Tag.of("localPath", mirror.localPath()));
42      }
43  
44      private final MeterRegistry meterRegistry;
45      private final Mirror mirror;
46      private final Iterable<Tag> tags;
47  
48      MirroringTask(Mirror mirror, String projectName, MeterRegistry meterRegistry) {
49          this.mirror = mirror;
50          this.meterRegistry = meterRegistry;
51          tags = generateTags(mirror, projectName);
52      }
53  
54      private Counter counter(boolean success) {
55          return Counter.builder("mirroring.result")
56                        .tags(tags)
57                        .tag("success", Boolean.toString(success))
58                        .register(meterRegistry);
59      }
60  
61      void run(File workDir, CommandExecutor executor, int maxNumFiles, long maxNumBytes) {
62          try {
63              meterRegistry.timer("mirroring.task", tags)
64                           .record(() -> mirror.mirror(workDir, executor, maxNumFiles, maxNumBytes));
65              counter(true).increment();
66          } catch (Exception e) {
67              counter(false).increment();
68              throw e;
69          }
70      }
71  }