aboutsummaryrefslogtreecommitdiffstats
path: root/site-manager/src/main/java/org/onap/policy/common/sitemanager/Main.java
blob: a415c2291f5ddd71af72192745b71aadbc2365dc (plain)
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/*-
 * ============LICENSE_START=======================================================
 * site-manager
 * ================================================================================
 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.common.sitemanager;

/*
 * Site Manager argument list:
 *
 * none - dump help information show - dump information about all nodes ([site, nodetype,
 * resourceName], adminState, opState, availStatus, standbyStatus) The first 3 determine the sort
 * order. setAdminState [ -s <site> | -r <resourceName> ] <new-state> lock [ -s <site> | -r
 * <resourceName> ] unlock [ -s <site> | -r <resourceName> ]
 */

import static org.onap.policy.common.sitemanager.utils.Constants.OPERATIONAL_PERSISTENCE_UNIT;
import static org.onap.policy.common.sitemanager.utils.Constants.SITE_MANAGER_PROPERTIES_PROPERTY_NAME;
import static org.onap.policy.common.sitemanager.utils.ErrorMessages.HELP_STRING;
import static org.onap.policy.common.sitemanager.utils.ErrorMessages.NO_MATCHING_ENTRIES;
import static org.onap.policy.common.sitemanager.utils.ExtraCommandLineArgument.LOCK;
import static org.onap.policy.common.sitemanager.utils.ExtraCommandLineArgument.SET_ADMIN_STATE;
import static org.onap.policy.common.sitemanager.utils.ExtraCommandLineArgument.UNLOCK;
import static org.onap.policy.common.sitemanager.utils.JmxOpProcessor.jmxOp;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;

import org.onap.policy.common.im.jpa.ResourceRegistrationEntity;
import org.onap.policy.common.im.jpa.StateManagementEntity;
import org.onap.policy.common.sitemanager.data.service.DatabaseAccessService;
import org.onap.policy.common.sitemanager.data.service.DatabaseAccessServiceImpl;
import org.onap.policy.common.sitemanager.exception.IllegalCommandLineArgumentException;
import org.onap.policy.common.sitemanager.exception.MissingPropertyException;
import org.onap.policy.common.sitemanager.exception.NoMatchingEntryFoundException;
import org.onap.policy.common.sitemanager.exception.PropertyFileProcessingException;
import org.onap.policy.common.sitemanager.utils.CommandLineHelper;
import org.onap.policy.common.sitemanager.utils.PersistenceUnitPropertiesProvider;
import org.onap.policy.common.sitemanager.utils.Printable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class contains the main entry point for Site Manager.
 */
public class Main {

    private static final Logger logger = LoggerFactory.getLogger(Main.class.getName());

    // table mapping 'resourceName' to 'StateManagmentEntity'
    static Map<String, StateManagementEntity> stateManagementTable = new HashMap<>();

    // table mapping 'resourceName' to 'StateManagmentEntity'
    static Map<String, ResourceRegistrationEntity> resourceRegistrationTable = new HashMap<>();

    /**
     * Print out help information regarding command arguments.
     */
    private static String getHelpString() {
        return HELP_STRING;
    }

    /**
     * This is the main entry point.
     *
     * @param args these are command-line arguments to 'siteManager'
     */
    public static void main(final String[] args) {
        final Printable printable = new PrintableImpl();
        new Main().process(args, printable);
    }

    /**
     * Process command-line arguments.
     * 
     * @param args args these are command-line arguments to 'siteManager'
     * @param printable {@link Printable} callback to print statement
     */
    public void process(final String[] args, final Printable printable) {
        try {
            final CommandLineHelper commandLineHelper = new CommandLineHelper(args, printable);

            if (commandLineHelper.isHelpArgumentSet()) {
                printable.println(getHelpString());
                System.exit(0);
            }

            if (!commandLineHelper.isValid()) {
                printable.println(getHelpString());
                System.exit(2);
            }
            process(commandLineHelper, printable);
        } catch (final IllegalCommandLineArgumentException illegalCommandLineArgumentException) {
            printable.println(illegalCommandLineArgumentException.getMessage());
            printable.println(getHelpString());
            System.exit(1);
        } catch (final PropertyFileProcessingException | MissingPropertyException exception) {
            System.exit(3);
        } catch (final NoMatchingEntryFoundException exception) {
            System.exit(4);
        }
    }

    private void process(final CommandLineHelper cmd, final Printable printable) {
        // fetch options, and remaining arguments
        final String sOption = cmd.getSite();
        final String rOption = cmd.getResourceName();
        final List<String> argList = cmd.getArgList();

        final String arg0 = argList.get(0);

        // read in properties used to access the database
        final String propertiesFileName = System.getProperty(SITE_MANAGER_PROPERTIES_PROPERTY_NAME);
        final Properties properties = PersistenceUnitPropertiesProvider.getProperties(propertiesFileName, printable);

        try (final DatabaseAccessService accessService =
                getDatabaseAccessService(OPERATIONAL_PERSISTENCE_UNIT, properties)) {

            final List<StateManagementEntity> stateManagementResultList =
                    accessService.getStateManagementEntities(rOption, sOption);
            final List<ResourceRegistrationEntity> resourceRegistrationResultList =
                    accessService.getResourceRegistrationEntities(rOption, sOption);

            // perform 'StateManagementEntity' query, and place matching entries
            // in 'stateManagementTable'
            for (final StateManagementEntity stateManagementEntity : stateManagementResultList) {
                stateManagementTable.put(stateManagementEntity.getResourceName(), stateManagementEntity);
            }

            // perform 'ResourceRegistrationQuery', and place matching entries
            // in 'resourceRegistrationTable' ONLY if there is also an associated
            // 'stateManagementTable' entry
            for (final ResourceRegistrationEntity resourceRegistrationEntity : resourceRegistrationResultList) {
                final String resourceName = resourceRegistrationEntity.getResourceName();
                if (stateManagementTable.get(resourceName) != null) {
                    // only include entries that have a corresponding
                    // state table entry -- silently ignore the rest
                    resourceRegistrationTable.put(resourceName, resourceRegistrationEntity);
                }
            }

            if (resourceRegistrationTable.isEmpty()) {
                final String message = arg0 + NO_MATCHING_ENTRIES;
                printable.println(message);
                throw new NoMatchingEntryFoundException(message);
            }

            if (SET_ADMIN_STATE.getValue().equalsIgnoreCase(arg0)) {
                // update admin state on all of the nodes
                final String adminState = argList.get(1);
                // iterate over all matching 'ResourceRegistrationEntity' instances
                for (final ResourceRegistrationEntity r : resourceRegistrationTable.values()) {
                    // we know the corresponding 'StateManagementEntity' exists --
                    // 'ResourceRegistrationEntity' entries without a matching
                    // 'StateManagementEntity' entry were not placed in the table
                    final StateManagementEntity s = stateManagementTable.get(r.getResourceName());

                    // update the admin state, and save the changes
                    s.setAdminState(adminState);
                }
                accessService.persist(stateManagementTable.values());

            } else if (LOCK.getValue().equalsIgnoreCase(arg0) || UNLOCK.getValue().equalsIgnoreCase(arg0)) {
                // these use the JMX interface
                for (final ResourceRegistrationEntity r : resourceRegistrationTable.values()) {
                    // lock or unlock the entity
                    jmxOp(arg0, r, printable);

                    // change should be reflected in 'adminState'
                    accessService.refreshEntity(stateManagementTable.get(r.getResourceName()));
                }
            }
        } catch (final NoMatchingEntryFoundException exception) {
            throw exception;
        } catch (final Exception exception) {
            printable.println(exception.getMessage());
        }

        // display all entries
        display();
    }

    /**
     * Compare two strings, either of which may be null.
     *
     * @param first the first string
     * @param second the second string
     * 
     * @return a negative value if s1 is less then s2, 0 if they are equal, and positive if s1 is
     *         greater then s2
     */
    private static int stringCompare(final String first, final String second) {
        if (first == null ^ second == null) {
            return (first == null) ? -1 : 1;
        }

        if (first == null && second == null) {
            return 0;
        }

        return first.compareTo(second);
    }

    /**
     * Update an array of 'length' fields using an array of Strings, any of which may be 'null'.
     * This method is used to determine the field width of each column in a tabular dump.
     *
     * @param current this is an array of length 7, containing the current maximum lengths of each
     *        column in the tabular dump
     * @param values this is an array of length 7, containing the current String entry for each
     *        column
     */
    private static void updateLengths(final int[] current, final String[] values) {
        for (int i = 0; i < 7; i++) {
            final String str = values[i];
            final int newLength = (str == null ? 4 : str.length());
            if (current[i] < newLength) {
                // this column needs to be expanded
                current[i] = newLength;
            }
        }
    }

    /**
     * Ordered display -- dump out all of the entries in log.
     */
    static void display() {
        final Set<String[]> treeset = new TreeSet<>((final String[] r1, final String[] r2) -> {
            int rval = 0;

            // the first 3 columns are 'Site', 'NodeType', and 'ResourceName',
            // and are used to sort the entries
            for (int i = 0; i < 3; i += 1) {
                if ((rval = stringCompare(r1[i], r2[i])) != 0) {
                    break;
                }
            }
            return (rval);
        });

        final String[] labels = new String[] {"Site", "NodeType", "ResourceName", "AdminState", "OpState",
            "AvailStatus", "StandbyStatus"};
        final String[] underlines = new String[] {"----", "--------", "------------", "----------", "-------",
            "-----------", "-------------"};

        // each column needs to be at least wide enough to fit the column label
        final int[] lengths = new int[labels.length];
        updateLengths(lengths, labels);

        // Go through the 'resourceRegistrationTable', and generate the
        // associated table row. Maximum column widths are updated, and the
        // entry is inserted into tree, which has the effect of sorting the
        // entries.
        for (final ResourceRegistrationEntity r : resourceRegistrationTable.values()) {
            final StateManagementEntity s = stateManagementTable.get(r.getResourceName());

            // these are the entries to be displayed for this row
            final String[] values = new String[] {r.getSite(), r.getNodeType(), r.getResourceName(), s.getAdminState(),
                s.getOpState(), s.getAvailStatus(), s.getStandbyStatus()};

            treeset.add(values);
            updateLengths(lengths, values);
        }

        // generate format string
        final StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 7; i += 1) {
            sb.append('%').append(i + 1).append("$-").append(lengths[i]).append("s ");
        }
        sb.setCharAt(sb.length() - 1, '\n');
        final String formatString = sb.toString();

        // display column headers
        logger.info(formatString, (Object[]) labels);
        logger.info(formatString, (Object[]) underlines);

        // display all of the rows
        for (final String[] values : treeset) {
            logger.info(formatString, (Object[]) values);
        }
    }

    DatabaseAccessService getDatabaseAccessService(final String persistenceUnitName, final Properties properties) {
        return new DatabaseAccessServiceImpl(persistenceUnitName, properties);
    }

    private static class PrintableImpl implements Printable {

        @Override
        public void println(final String value) {
            System.out.println(value);
        }
    }
}