View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.shardingsphere.infra.instance;
19  
20  import lombok.AccessLevel;
21  import lombok.Getter;
22  import lombok.RequiredArgsConstructor;
23  import org.apache.shardingsphere.infra.config.mode.ModeConfiguration;
24  import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaData;
25  import org.apache.shardingsphere.infra.instance.metadata.InstanceType;
26  import org.apache.shardingsphere.infra.instance.mode.ModeContextManager;
27  import org.apache.shardingsphere.infra.instance.workerid.WorkerIdGenerator;
28  import org.apache.shardingsphere.infra.lock.LockContext;
29  import org.apache.shardingsphere.infra.util.eventbus.EventBusContext;
30  
31  import java.util.Collection;
32  import java.util.LinkedHashMap;
33  import java.util.LinkedList;
34  import java.util.Map;
35  import java.util.Optional;
36  import java.util.Properties;
37  
38  /**
39   * Instance context.
40   */
41  @RequiredArgsConstructor
42  @Getter
43  public final class InstanceContext {
44      
45      private final ComputeNodeInstance instance;
46      
47      @Getter(AccessLevel.NONE)
48      private final WorkerIdGenerator workerIdGenerator;
49      
50      private final ModeConfiguration modeConfiguration;
51      
52      private final ModeContextManager modeContextManager;
53      
54      @SuppressWarnings("rawtypes")
55      private final LockContext lockContext;
56      
57      private final EventBusContext eventBusContext;
58      
59      private final Collection<ComputeNodeInstance> allClusterInstances = new LinkedList<>();
60      
61      /**
62       * Update instance status.
63       *
64       * @param instanceId instance id
65       * @param status status
66       */
67      public void updateInstanceStatus(final String instanceId, final String status) {
68          if (instance.getMetaData().getId().equals(instanceId)) {
69              instance.switchState(status);
70          }
71          updateRelatedComputeNodeInstancesStatus(instanceId, status);
72      }
73      
74      private void updateRelatedComputeNodeInstancesStatus(final String instanceId, final String status) {
75          for (ComputeNodeInstance each : allClusterInstances) {
76              if (each.getMetaData().getId().equals(instanceId)) {
77                  each.switchState(status);
78              }
79          }
80      }
81      
82      /**
83       * Update instance worker id.
84       *
85       * @param instanceId instance id
86       * @param workerId worker id
87       */
88      public void updateWorkerId(final String instanceId, final Integer workerId) {
89          if (instance.getMetaData().getId().equals(instanceId)) {
90              instance.setWorkerId(workerId);
91          }
92          allClusterInstances.stream().filter(each -> each.getMetaData().getId().equals(instanceId)).forEach(each -> each.setWorkerId(workerId));
93      }
94      
95      /**
96       * Update instance label.
97       * 
98       * @param instanceId instance id
99       * @param labels collection of label
100      */
101     public void updateLabel(final String instanceId, final Collection<String> labels) {
102         if (instance.getMetaData().getId().equals(instanceId)) {
103             instance.setLabels(labels);
104         }
105         allClusterInstances.stream().filter(each -> each.getMetaData().getId().equals(instanceId)).forEach(each -> each.setLabels(labels));
106     }
107     
108     /**
109      * Get worker id.
110      *
111      * @return worker id
112      */
113     public int getWorkerId() {
114         return instance.getWorkerId();
115     }
116     
117     /**
118      * Generate worker id.
119      *
120      * @param props properties
121      * @return worker id
122      */
123     public int generateWorkerId(final Properties props) {
124         int result = workerIdGenerator.generate(props);
125         instance.setWorkerId(result);
126         return result;
127     }
128     
129     /**
130      * Add compute node instance.
131      * 
132      * @param instance compute node instance
133      */
134     public void addComputeNodeInstance(final ComputeNodeInstance instance) {
135         allClusterInstances.removeIf(each -> each.getMetaData().getId().equalsIgnoreCase(instance.getMetaData().getId()));
136         allClusterInstances.add(instance);
137     }
138     
139     /**
140      * Delete compute node instance.
141      *
142      * @param instance compute node instance
143      */
144     public void deleteComputeNodeInstance(final ComputeNodeInstance instance) {
145         allClusterInstances.removeIf(each -> each.getMetaData().getId().equalsIgnoreCase(instance.getMetaData().getId()));
146     }
147     
148     /**
149      * Get compute node instances by instance type and labels.
150      *
151      * @param instanceType instance type
152      * @param labels collection of contained label
153      * @return compute node instances
154      */
155     public Map<String, InstanceMetaData> getAllClusterInstances(final InstanceType instanceType, final Collection<String> labels) {
156         Map<String, InstanceMetaData> result = new LinkedHashMap<>(allClusterInstances.size(), 1F);
157         for (ComputeNodeInstance each : allClusterInstances) {
158             if (each.getMetaData().getType() == instanceType && labels.stream().anyMatch(((Collection<String>) each.getLabels())::contains)) {
159                 result.put(each.getMetaData().getId(), each.getMetaData());
160             }
161         }
162         return result;
163     }
164     
165     /**
166      * Get compute node instance by instance id.
167      * 
168      * @param instanceId instance id
169      * @return compute node instance
170      */
171     public Optional<ComputeNodeInstance> getComputeNodeInstanceById(final String instanceId) {
172         return allClusterInstances.stream().filter(each -> instanceId.equals(each.getCurrentInstanceId())).findFirst();
173     }
174     
175     /**
176      * Is cluster instance or not.
177      * 
178      * @return true if is cluster, else false
179      */
180     public boolean isCluster() {
181         return "Cluster".equals(modeConfiguration.getType());
182     }
183 }