jdk/src/share/classes/com/sun/servicetag/Registry.java
changeset 1327 912486b03832
child 5506 202f599c92aa
equal deleted inserted replaced
1324:f1f7222489a4 1327:912486b03832
       
     1 /*
       
     2  * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Sun designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Sun in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
       
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
       
    23  * have any questions.
       
    24  */
       
    25 
       
    26 package com.sun.servicetag;
       
    27 
       
    28 import java.io.*;
       
    29 import java.util.ArrayList;
       
    30 import java.util.Date;
       
    31 import java.util.HashSet;
       
    32 import java.util.List;
       
    33 import java.util.Properties;
       
    34 import java.util.Set;
       
    35 
       
    36 import static com.sun.servicetag.Util.*;
       
    37 import static com.sun.servicetag.RegistrationDocument.*;
       
    38 
       
    39 /**
       
    40  * A service tag registry is a XML-based registry containing
       
    41  * the list of {@link ServiceTag service tags} installed in the system.
       
    42  * The {@code Registry} class provides interfaces
       
    43  * to add, remove, update, and get a service tag from a service tag
       
    44  * registry.
       
    45  * This {@code Registry} class may not be supported
       
    46  * on all systems. The {@link #isSupported} method
       
    47  * can be called to determine if it is supported.
       
    48  * <p>
       
    49  * A registry may implement restrictions to only allow certain users
       
    50  * to {@link #updateServiceTag update} and
       
    51  * to {@link #removeServiceTag remove} a service tag record. Typically,
       
    52  * only the owner of the service tag, the owner of the registry
       
    53  * and superuser are authorized to update or remove a service tag in
       
    54  * the registry.
       
    55  *
       
    56  * @see <a href="https://sn-tools.central.sun.com/twiki/bin/view/ServiceTags/ServiceTagDevGuideHelper">
       
    57  * Service Tag User Guide</a>
       
    58  */
       
    59 public class Registry {
       
    60 
       
    61     private static final String STCLIENT_SOLARIS = "/usr/bin/stclient";
       
    62     private static final String STCLIENT_LINUX = "/opt/sun/servicetag/bin/stclient";
       
    63     // stclient exit value (see sthelper.h)
       
    64     private static final int ST_ERR_NOT_AUTH = 245;
       
    65     private static final int ST_ERR_REC_NOT_FOUND = 225;
       
    66 
       
    67     // The stclient output has to be an exported interface
       
    68     private static final String INSTANCE_URN_DESC = "Product instance URN=";
       
    69     private static boolean initialized = false;
       
    70     private static boolean supportsHelperClass = true; // default
       
    71     private static File stclient = null;
       
    72     private static String stclientPath = null;
       
    73     private static Registry registry = new Registry();
       
    74 
       
    75     // System properties for testing
       
    76     private static String SVCTAG_STCLIENT_CMD = "servicetag.stclient.cmd";
       
    77     private static String SVCTAG_STHELPER_SUPPORTED = "servicetag.sthelper.supported";
       
    78 
       
    79     private Registry() {
       
    80     }
       
    81 
       
    82     private synchronized static String getSTclient() {
       
    83         if (!initialized) {
       
    84             // the system property always overrides the default setting
       
    85             if (System.getProperty(SVCTAG_STHELPER_SUPPORTED) != null) {
       
    86                 supportsHelperClass = Boolean.getBoolean(SVCTAG_STHELPER_SUPPORTED);
       
    87             }
       
    88 
       
    89             // This is only used for testing
       
    90             stclientPath = System.getProperty(SVCTAG_STCLIENT_CMD);
       
    91             if (stclientPath != null) {
       
    92                 return stclientPath;
       
    93             }
       
    94 
       
    95             // Initialization to determine the platform's stclient pathname
       
    96             String os = System.getProperty("os.name");
       
    97             if (os.equals("SunOS")) {
       
    98                 stclient = new File(STCLIENT_SOLARIS);
       
    99             } else if (os.equals("Linux")) {
       
   100                 stclient = new File(STCLIENT_LINUX);
       
   101             } else if (os.startsWith("Windows")) {
       
   102                 stclient = getWindowsStClientFile();
       
   103             } else {
       
   104                 if (isVerbose()) {
       
   105                     System.out.println("Running on non-Sun JDK");
       
   106                 }
       
   107             }
       
   108             initialized = true;
       
   109         }
       
   110 
       
   111         // com.sun.servicetag package has to be compiled with JDK 5 as well
       
   112         // JDK 5 doesn't support the File.canExecute() method.
       
   113         // Risk not checking isExecute() for the stclient command is very low.
       
   114 
       
   115         if (stclientPath == null && stclient != null && stclient.exists()) {
       
   116             stclientPath = stclient.getAbsolutePath();
       
   117         }
       
   118         return stclientPath;
       
   119     }
       
   120 
       
   121     /**
       
   122      * Returns the system service tag registry. The {@code Registry} class
       
   123      * may not be supported on some platforms; use the {@link #isSupported}
       
   124      * method to determine if it is supported.
       
   125      *
       
   126      * @return the {@code Registry} object for the system service tag registry.
       
   127      *
       
   128      * @throws UnsupportedOperationException if the {@code Registry} class is
       
   129      * not supported.
       
   130      */
       
   131     public static Registry getSystemRegistry() {
       
   132         if (isSupported()) {
       
   133             return registry;
       
   134         } else {
       
   135             throw new UnsupportedOperationException("Registry class is not supported");
       
   136         }
       
   137     }
       
   138 
       
   139     /**
       
   140      * Returns {@code true} if the {@code Registry} class is supported on this system.
       
   141      *
       
   142      * @return {@code true} if the {@code Registry} class is supported;
       
   143      * otherwise, return {@code false}.
       
   144      */
       
   145     public static boolean isSupported() {
       
   146         return (getSTclient() != null && supportsHelperClass);
       
   147     }
       
   148 
       
   149     private static List<String> getCommandList() {
       
   150         // Set up the arguments to call stclient
       
   151         List<String> command = new ArrayList<String>();
       
   152         if (System.getProperty(SVCTAG_STCLIENT_CMD) != null) {
       
   153             // This is for jtreg testing use. This will be set to something
       
   154             // like:
       
   155             // $JAVA_HOME/bin/java -cp $TEST_DIR \
       
   156             //    -Dstclient.registry.path=$TEST_DIR/registry.xml \
       
   157             //    SvcTagClient
       
   158             //
       
   159             // On Windows, the JAVA_HOME and TEST_DIR path could contain
       
   160             // space e.g. c:\Program Files\Java\jdk1.6.0_05\bin\java.
       
   161             // The SVCTAG_STCLIENT_CMD must be set with a list of
       
   162             // space-separated parameters.  If a parameter contains spaces,
       
   163             // it must be quoted with '"'.
       
   164 
       
   165             String cmd = getSTclient();
       
   166             int len = cmd.length();
       
   167             int i = 0;
       
   168             while (i < len) {
       
   169                 char separator = ' ';
       
   170                 if (cmd.charAt(i) == '"') {
       
   171                     separator = '"';
       
   172                     i++;
       
   173                 }
       
   174                 // look for the separator or matched the closing '"'
       
   175                 int j;
       
   176                 for (j = i+1; j < len; j++) {
       
   177                     if (cmd.charAt(j) == separator) {
       
   178                         break;
       
   179                     }
       
   180                 }
       
   181 
       
   182                 if (i == j-1) {
       
   183                     // add an empty parameter
       
   184                     command.add("\"\"");
       
   185                 } else {
       
   186                     // double quotes and space are not included
       
   187                     command.add(cmd.substring(i,j));
       
   188                 }
       
   189 
       
   190                 // skip spaces
       
   191                 for (i = j+1; i < len; i++) {
       
   192                     if (!Character.isSpaceChar(cmd.charAt(i))) {
       
   193                         break;
       
   194                     }
       
   195                 }
       
   196             }
       
   197             if (isVerbose()) {
       
   198                 System.out.println("Command list:");
       
   199                 for (String s : command) {
       
   200                     System.out.println(s);
       
   201                 }
       
   202             }
       
   203         } else {
       
   204             command.add(getSTclient());
       
   205         }
       
   206         return command;
       
   207     }
       
   208 
       
   209     // Returns null if the service tag record not found;
       
   210     // or throw UnauthorizedAccessException or IOException
       
   211     // based on the exitValue.
       
   212     private static ServiceTag checkReturnError(int exitValue,
       
   213                                                String output,
       
   214                                                ServiceTag st) throws IOException {
       
   215         switch (exitValue) {
       
   216             case ST_ERR_REC_NOT_FOUND:
       
   217                 return null;
       
   218             case ST_ERR_NOT_AUTH:
       
   219                 if (st != null) {
       
   220                     throw new UnauthorizedAccessException(
       
   221                         "Not authorized to access " + st.getInstanceURN() +
       
   222                         " installer_uid=" + st.getInstallerUID());
       
   223                 } else  {
       
   224                     throw new UnauthorizedAccessException(
       
   225                         "Not authorized:" + output);
       
   226                 }
       
   227             default:
       
   228                 throw new IOException("stclient exits with error" +
       
   229                      " (" + exitValue + ")\n" + output);
       
   230         }
       
   231     }
       
   232 
       
   233     /**
       
   234      * Adds a service tag to this registry.
       
   235      * If the given service tag has an empty <tt>instance_urn</tt>,
       
   236      * this helper class will generate a URN and place it in the
       
   237      * copy of the service tag in this registry.
       
   238      * This method will return the {@code ServiceTag} representing
       
   239      * the service tag entry to this registry.
       
   240      *
       
   241      * @param st {@code ServiceTag} object
       
   242      * @return a {@code ServiceTag} object representing the service tag
       
   243      *         entry to this registry.
       
   244      *
       
   245      * @throws IllegalArgumentException if a service tag of the same
       
   246      * <tt>instance_urn</tt> already exists in this registry.
       
   247      *
       
   248      * @throws java.io.IOException if an I/O error occurs in this operation.
       
   249      */
       
   250     public ServiceTag addServiceTag(ServiceTag st) throws IOException {
       
   251         List<String> command = getCommandList();
       
   252         command.add("-a");
       
   253         if (st.getInstanceURN().length() > 0) {
       
   254             ServiceTag sysSvcTag = getServiceTag(st.getInstanceURN());
       
   255             if (sysSvcTag != null) {
       
   256                 throw new IllegalArgumentException("Instance_urn = " +
       
   257                     st.getInstanceURN() + " already exists");
       
   258             }
       
   259             command.add("-i");
       
   260             command.add(st.getInstanceURN());
       
   261         }
       
   262         command.add("-p");
       
   263         command.add(st.getProductName());
       
   264         command.add("-e");
       
   265         command.add(st.getProductVersion());
       
   266         command.add("-t");
       
   267         command.add(st.getProductURN());
       
   268         if (st.getProductParentURN().length() > 0) {
       
   269             command.add("-F");
       
   270             command.add(st.getProductParentURN());
       
   271         }
       
   272         command.add("-P");
       
   273         command.add(st.getProductParent());
       
   274         if (st.getProductDefinedInstanceID().length() > 0) {
       
   275             command.add("-I");
       
   276             command.add(st.getProductDefinedInstanceID());
       
   277         }
       
   278         command.add("-m");
       
   279         command.add(st.getProductVendor());
       
   280         command.add("-A");
       
   281         command.add(st.getPlatformArch());
       
   282         command.add("-z");
       
   283         command.add(st.getContainer());
       
   284         command.add("-S");
       
   285         command.add(st.getSource());
       
   286 
       
   287         BufferedReader in = null;
       
   288         try {
       
   289             ProcessBuilder pb = new ProcessBuilder(command);
       
   290             Process p = pb.start();
       
   291             String output = commandOutput(p);
       
   292             if (isVerbose()) {
       
   293                 System.out.println("Output from stclient -a command:");
       
   294                 System.out.println(output);
       
   295             }
       
   296             String urn = "";
       
   297             if (p.exitValue() == 0) {
       
   298                 // Obtain the instance urn from the stclient output
       
   299                 in = new BufferedReader(new StringReader(output));
       
   300                 String line = null;
       
   301                 while ((line = in.readLine()) != null) {
       
   302                     line = line.trim();
       
   303                     if (line.startsWith(INSTANCE_URN_DESC)) {
       
   304                         urn = line.substring(INSTANCE_URN_DESC.length());
       
   305                         break;
       
   306                     }
       
   307                 }
       
   308                 if (urn.length() == 0) {
       
   309                     throw new IOException("Error in creating service tag:\n" +
       
   310                         output);
       
   311                 }
       
   312                 return getServiceTag(urn);
       
   313             } else {
       
   314                 return checkReturnError(p.exitValue(), output, st);
       
   315             }
       
   316         } finally {
       
   317             if (in != null) {
       
   318                 in.close();
       
   319             }
       
   320         }
       
   321     }
       
   322 
       
   323     /**
       
   324      * Removes a service tag of the given <tt>instance_urn</tt> from this
       
   325      * registry.
       
   326      *
       
   327      * @param instanceURN the <tt>instance_urn</tt> of the service tag
       
   328      *        to be removed.
       
   329      *
       
   330      * @return the {@code ServiceTag} object removed from this registry;
       
   331      * or {@code null} if the service tag does not exist in this registry.
       
   332      *
       
   333      * @throws UnauthorizedAccessException if the user is not authorized to
       
   334      * remove the service tag of the given <tt>instance_urn</tt>
       
   335      * from this registry.
       
   336      *
       
   337      * @throws java.io.IOException if an I/O error occurs in this operation.
       
   338      */
       
   339     public ServiceTag removeServiceTag(String instanceURN) throws IOException {
       
   340         ServiceTag st = getServiceTag(instanceURN);
       
   341         if (st == null) {
       
   342             return null;
       
   343         }
       
   344 
       
   345         List<String> command = getCommandList();
       
   346         command.add("-d");
       
   347         command.add("-i");
       
   348         command.add(instanceURN);
       
   349 
       
   350         ProcessBuilder pb = new ProcessBuilder(command);
       
   351         Process p = pb.start();
       
   352         String output = commandOutput(p);
       
   353         if (isVerbose()) {
       
   354             System.out.println("Output from stclient -d command:");
       
   355             System.out.println(output);
       
   356         }
       
   357         if (p.exitValue() == 0) {
       
   358             return st;
       
   359         } else {
       
   360             return checkReturnError(p.exitValue(), output, st);
       
   361         }
       
   362     }
       
   363 
       
   364     /**
       
   365      * Updates the <tt>product_defined_instance_id</tt> in the service tag
       
   366      * of the specified <tt>instance_urn</tt> in this registry.
       
   367      *
       
   368      * @param instanceURN the <tt>instance_urn</tt> of the service tag to be updated.
       
   369      * @param productDefinedInstanceID the value of the
       
   370      * <tt>product_defined_instance_id</tt> to be set.
       
   371      *
       
   372      * @return the updated {@code ServiceTag} object;
       
   373      * or {@code null} if the service tag does not exist in this
       
   374      * registry.
       
   375      *
       
   376      * @throws UnauthorizedAccessException if the user is not authorized to
       
   377      * update the service tag from this registry.
       
   378      *
       
   379      * @throws IOException if an I/O error occurs in this operation.
       
   380      */
       
   381     public ServiceTag updateServiceTag(String instanceURN,
       
   382                                        String productDefinedInstanceID)
       
   383             throws IOException {
       
   384         ServiceTag svcTag = getServiceTag(instanceURN);
       
   385         if (svcTag == null) {
       
   386             return null;
       
   387         }
       
   388 
       
   389         List<String> command = getCommandList();
       
   390         command.add("-u");
       
   391         command.add("-i");
       
   392         command.add(instanceURN);
       
   393         command.add("-I");
       
   394         if (productDefinedInstanceID.length() > 0) {
       
   395             command.add(productDefinedInstanceID);
       
   396         } else {
       
   397             command.add("\"\"");
       
   398         }
       
   399 
       
   400         ProcessBuilder pb = new ProcessBuilder(command);
       
   401         Process p = pb.start();
       
   402         String output = commandOutput(p);
       
   403         if (isVerbose()) {
       
   404             System.out.println("Output from stclient -u command:");
       
   405             System.out.println(output);
       
   406         }
       
   407 
       
   408         if (p.exitValue() == 0) {
       
   409             return getServiceTag(instanceURN);
       
   410         } else {
       
   411             return checkReturnError(p.exitValue(), output, svcTag);
       
   412         }
       
   413     }
       
   414 
       
   415     /**
       
   416      * Returns a {@code ServiceTag} object of the given  <tt>instance_urn</tt>
       
   417      * in this registry.
       
   418      *
       
   419      * @param instanceURN the  <tt>instance_urn</tt> of the service tag
       
   420      * @return a {@code ServiceTag} object of the given <tt>instance_urn</tt>
       
   421      * in this registry; or {@code null} if not found.
       
   422      *
       
   423      * @throws java.io.IOException if an I/O error occurs in this operation.
       
   424      */
       
   425     public ServiceTag getServiceTag(String instanceURN) throws IOException {
       
   426         if (instanceURN == null) {
       
   427             throw new NullPointerException("instanceURN is null");
       
   428         }
       
   429 
       
   430         List<String> command = getCommandList();
       
   431         command.add("-g");
       
   432         command.add("-i");
       
   433         command.add(instanceURN);
       
   434 
       
   435         ProcessBuilder pb = new ProcessBuilder(command);
       
   436         Process p = pb.start();
       
   437         String output = commandOutput(p);
       
   438         if (isVerbose()) {
       
   439             System.out.println("Output from stclient -g command:");
       
   440             System.out.println(output);
       
   441         }
       
   442         if (p.exitValue() == 0) {
       
   443             return parseServiceTag(output);
       
   444         } else {
       
   445             return checkReturnError(p.exitValue(), output, null);
       
   446         }
       
   447     }
       
   448 
       
   449     private ServiceTag parseServiceTag(String output) throws IOException {
       
   450         BufferedReader in = null;
       
   451         try {
       
   452             Properties props = new Properties();
       
   453             // parse the service tag output from stclient
       
   454             in = new BufferedReader(new StringReader(output));
       
   455             String line = null;
       
   456             while ((line = in.readLine()) != null) {
       
   457                 if ((line = line.trim()).length() > 0) {
       
   458                     String[] ss = line.trim().split("=", 2);
       
   459                     if (ss.length == 2) {
       
   460                         props.setProperty(ss[0].trim(), ss[1].trim());
       
   461                     } else {
       
   462                         props.setProperty(ss[0].trim(), "");
       
   463                     }
       
   464                 }
       
   465             }
       
   466 
       
   467             String urn = props.getProperty(ST_NODE_INSTANCE_URN);
       
   468             String productName = props.getProperty(ST_NODE_PRODUCT_NAME);
       
   469             String productVersion = props.getProperty(ST_NODE_PRODUCT_VERSION);
       
   470             String productURN = props.getProperty(ST_NODE_PRODUCT_URN);
       
   471             String productParent = props.getProperty(ST_NODE_PRODUCT_PARENT);
       
   472             String productParentURN = props.getProperty(ST_NODE_PRODUCT_PARENT_URN);
       
   473             String productDefinedInstanceID =
       
   474                 props.getProperty(ST_NODE_PRODUCT_DEFINED_INST_ID);
       
   475             String productVendor = props.getProperty(ST_NODE_PRODUCT_VENDOR);
       
   476             String platformArch = props.getProperty(ST_NODE_PLATFORM_ARCH);
       
   477             String container = props.getProperty(ST_NODE_CONTAINER);
       
   478             String source = props.getProperty(ST_NODE_SOURCE);
       
   479             int installerUID =
       
   480                 Util.getIntValue(props.getProperty(ST_NODE_INSTALLER_UID));
       
   481             Date timestamp =
       
   482                 Util.parseTimestamp(props.getProperty(ST_NODE_TIMESTAMP));
       
   483 
       
   484             return new ServiceTag(urn,
       
   485                                   productName,
       
   486                                   productVersion,
       
   487                                   productURN,
       
   488                                   productParent,
       
   489                                   productParentURN,
       
   490                                   productDefinedInstanceID,
       
   491                                   productVendor,
       
   492                                   platformArch,
       
   493                                   container,
       
   494                                   source,
       
   495                                   installerUID,
       
   496                                   timestamp);
       
   497         } finally {
       
   498             if (in != null) {
       
   499                 in.close();
       
   500             }
       
   501         }
       
   502 
       
   503     }
       
   504 
       
   505     /**
       
   506      * Returns the service tags of the specified
       
   507      * <tt>product_urn</tt> in this registry.
       
   508      *
       
   509      * @param productURN the  <tt>product_urn</tt> to look up
       
   510      * @return a {@code Set} of {@code ServiceTag} objects
       
   511      * of the specified <tt>product_urn</tt> in this registry.
       
   512      *
       
   513      * @throws java.io.IOException if an I/O error occurs in this operation.
       
   514      */
       
   515     public Set<ServiceTag> findServiceTags(String productURN) throws IOException {
       
   516         if (productURN == null) {
       
   517             throw new NullPointerException("productURN is null");
       
   518         }
       
   519 
       
   520         List<String> command = getCommandList();
       
   521         command.add("-f");
       
   522         command.add("-t");
       
   523         command.add(productURN);
       
   524 
       
   525         BufferedReader in = null;
       
   526         try {
       
   527             ProcessBuilder pb = new ProcessBuilder(command);
       
   528             Process p = pb.start();
       
   529             String output = commandOutput(p);
       
   530 
       
   531             Set<ServiceTag> instances = new HashSet<ServiceTag>();
       
   532             if (p.exitValue() == 0) {
       
   533                 // parse the service tag output from stclient
       
   534                 in = new BufferedReader(new StringReader(output));
       
   535                 String line = null;
       
   536                 while ((line = in.readLine()) != null) {
       
   537                     String s = line.trim();
       
   538                     if (s.startsWith("urn:st:")) {
       
   539                         instances.add(getServiceTag(s));
       
   540                     }
       
   541                 }
       
   542             } else {
       
   543                 checkReturnError(p.exitValue(), output, null);
       
   544             }
       
   545             return instances;
       
   546         } finally {
       
   547             if (in != null) {
       
   548                 in.close();
       
   549             }
       
   550         }
       
   551     }
       
   552 }