001package com.pingidentity.util;
002
003import com.unboundid.directory.sdk.common.api.ManageExtensionPlugin;
004import com.unboundid.directory.sdk.common.types.ExtensionBundle;
005import com.unboundid.directory.sdk.common.types.InstallExtensionDetails;
006import com.unboundid.directory.sdk.common.types.PostManageExtensionPluginResult;
007import com.unboundid.directory.sdk.common.types.UpdateExtensionDetails;
008
009import java.io.File;
010import java.io.IOException;
011import java.nio.charset.Charset;
012import java.nio.charset.StandardCharsets;
013import java.nio.file.*;
014import java.nio.file.attribute.BasicFileAttributes;
015import java.nio.file.attribute.FileTime;
016
017import static com.pingidentity.arno.LOG.out;
018import static java.nio.file.FileVisitResult.CONTINUE;
019import static java.nio.file.FileVisitResult.SKIP_SUBTREE;
020import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
021
022/**
023 * Created by arnaudlacour on 5/17/17.
024 */
025public class Installer extends ManageExtensionPlugin
026{
027    /**
028     * Returns the extension name
029     * @return the extension name
030     */
031    @Override
032    public String getExtensionName()
033    {
034        return "Generic Extension Installer";
035    }
036    
037    /**
038     * Provides descriptions for the extension
039     * @return an array of descriptive paragraphs
040     */
041    @Override
042    public String[] getExtensionDescription()
043    {
044        return new String[]{"Installs the extension this installer is bundled with"};
045    }
046    
047    /**
048     * Performs the necessary processing after the extension has been updated
049     * @param details the extension bundle details
050     * @return SUCCESS if the update was successful
051     */
052    @Override
053    public PostManageExtensionPluginResult postUpdate(UpdateExtensionDetails details)
054    {
055        File instanceRoot = details.getExtensionBundle().getExtensionBundleDir().getParentFile().getParentFile();
056        String confBatch = details.getExtensionBundle().getConfigDir() + "/update.dsconfig";
057        File configurationBatchFile = new File(confBatch);
058        if (configurationBatchFile.exists() && configurationBatchFile.isFile())
059        {
060            System.out.println();
061            System.out.println("You can get started more quickly by running this command: ");
062            System.out.println(instanceRoot.toString() + "/bin/dsconfig --no-prompt --batch-file " + confBatch);
063        }
064        return PostManageExtensionPluginResult.SUCCESS;
065    }
066    
067    /**
068     * Performs the necessary processing after the extension has been installed
069     * This currently includes things like laying down schema files, updating documentation, attempting to open
070     * a browser to the extension documentation page and displaying the appropriate commands to run
071     * @param details the extension bundle details
072     * @return SUCCESS if the install was successful
073     */
074    @Override
075    public PostManageExtensionPluginResult postInstall(
076            InstallExtensionDetails details)
077    {
078        File instanceRoot = details.getExtensionBundle().getExtensionBundleDir().getParentFile().getParentFile();
079        
080        /* copy schema files included in the extension if any */
081        copySchema(details, instanceRoot);
082        
083        /* copy the documentation so it can be readily available for users */
084        copyDocumentation(instanceRoot, details);
085        
086        /* Update the docs index to add a link for convenience */
087        updateIndex(instanceRoot, details);
088        
089        /* if there is a browser to be opened, attempt to open the documentation directly */
090        openBrowser(details.getExtensionBundle());
091        
092        
093        String confBatch = details.getExtensionBundle().getConfigDir() + "/install.dsconfig";
094        File configurationBatchFile = new File(confBatch);
095        if (configurationBatchFile.exists() && configurationBatchFile.isFile())
096        {
097            System.out.println();
098            System.out.println("You can get started more quickly by running this command: ");
099            System.out.println(instanceRoot.toString() + "/bin/dsconfig --no-prompt --batch-file " + confBatch);
100            System.out.println("Executing this command will create basic configuration objects.");
101        }
102        return PostManageExtensionPluginResult.SUCCESS;
103    }
104    
105    /**
106     * This method performs the necessary processing to copy schema to the instance
107     *
108     * @param details      the extension details
109     * @param instanceRoot the instance root
110     */
111    private void copySchema(final InstallExtensionDetails details, File instanceRoot)
112    {
113        System.out.println();
114        System.out.println("Schema preparation");
115        String schemaAddress = details.getExtensionBundle().getConfigDir() + "/schema";
116        File schemaDirectory = new File(schemaAddress);
117        if (schemaDirectory.exists() && schemaDirectory.isDirectory())
118        {
119            Path schemaSourcePath = Paths.get(schemaAddress);
120            try
121            {
122                DirectoryStream<Path>
123                        schemaDirectoryStream = Files.newDirectoryStream(
124                        schemaSourcePath, "??-*.ldif");
125                for (Path schemaFile : schemaDirectoryStream)
126                {
127                    try
128                    {
129                        System.out.println("Copying schema file " + schemaFile.toString());
130                        Files.copy(schemaFile, Paths.get(instanceRoot + "/config/schema/" + schemaFile.getFileName())
131                                , REPLACE_EXISTING);
132                    } catch (IOException e)
133                    {
134                        System.out.println(e.getMessage());
135                    }
136                }
137            } catch (IOException e)
138            {
139                System.out.println(e.getMessage());
140            }
141        }
142        System.out.println("Schema preparation: done.");
143    }
144    
145    /**
146     * This method performs the necessary processing to attempt opening a browser window for the user at
147     * installation time and pop the documentation up.
148     *
149     * @param bundle the extension bundle to get the information from
150     */
151    private void openBrowser(final ExtensionBundle bundle)
152    {
153        System.out.println();
154        System.out.println("Documentation convenience");
155        String docUrl = "file://" + bundle.getDocumentationDir() + "/index.html";
156        System.out.println("You may find the documentation for this extension here:");
157        System.out.println(docUrl);
158        String OS = System.getProperty("os.name").toLowerCase();
159        try
160        {
161            if (OS.contains("mac"))
162            {
163                Runtime.getRuntime().exec("open " + docUrl);
164            } else if (OS.contains("win"))
165            {
166                Runtime.getRuntime().exec("cmd /c start " + docUrl);
167            } else if (OS.contains("nux"))
168            {
169                Runtime.getRuntime().exec("xdg-open " + docUrl);
170            }
171        } catch (IOException e)
172        {
173        }
174        System.out.println("Documentation convenience: done.");
175    }
176    
177    
178    /**
179     * This method performs the necessary processing to attempt copying the documentation bundled with the extension
180     * into a folder that can be reached by the docs servlet
181     *
182     * @param instanceRoot     the instance installation root file
183     * @param extensionDetails the extension detail information
184     */
185    private void copyDocumentation(final File instanceRoot,
186                                   InstallExtensionDetails extensionDetails)
187    {
188        System.out.println();
189        System.out.println("Documentation preparation");
190        
191        String extensionNewDocRoot = instanceRoot + "/docs/extensions/" + extensionDetails.getExtensionBundle()
192                .getBundleId();
193        
194        File newDocDir = new File(extensionNewDocRoot);
195        newDocDir.mkdirs();
196        
197        Path srcDocPath = Paths.get(extensionDetails.getExtensionBundle().getDocumentationDir().getPath());
198        Path dstDocPath = Paths.get(extensionNewDocRoot);
199        
200        TreeCopier tc = new TreeCopier(srcDocPath, dstDocPath);
201        try
202        {
203            Files.walkFileTree(srcDocPath, tc);
204        } catch (IOException e)
205        {
206            System.out.println(e);
207        }
208        System.out.println("Documentation preparation: done.");
209    }
210    
211    /**
212     * This method performs the necessary processing to attempt updating the default documentation html page to
213     * add a
214     * direct link to the freshly copied extension documentation.
215     * Avoids duplicating links when updating the same extension version, for example during development
216     *
217     * @param extensionDetails the bundle details
218     */
219    private void updateIndex(final File syncRoot, InstallExtensionDetails extensionDetails)
220    {
221        System.out.println();
222        System.out.println("Documentation index update");
223        
224        Path path = Paths.get(syncRoot.getPath() + "/docs/index.html");
225
226        if (path.toFile().exists() ) {
227            Charset charset = StandardCharsets.UTF_8;
228            String content;
229            try {
230                content = new String(Files.readAllBytes(path), charset);
231                String bundleId = extensionDetails.getExtensionBundle().getBundleId();
232                if (!content.contains("extensions/" + bundleId)) {
233                    content = content.replaceAll("product.", "product.\n<BR><BR><BR><A HREF=\"extensions/" + bundleId +
234                            "/\">" + extensionDetails.getExtensionBundle().getTitle() + " " + extensionDetails
235                            .getExtensionBundle().getVersion
236                                    () + "</A>");
237                    Files.write(path, content.getBytes(charset));
238                }
239            } catch (IOException e) {
240                System.out.println(e);
241            }
242            System.out.println("Documentation index update: done.");
243        } else {
244            System.out.println("Documentation index update: skipped.");
245        }
246    }
247    
248    /**
249     * Copy source file to target location. If {@code prompt} is true then
250     * prompt user to overwrite target if it exists. The {@code preserve}
251     * parameter determines if file attributes should be copied/preserved.
252     */
253    static void copyFile(Path source, Path target)
254    {
255        CopyOption[] options = new CopyOption[]{REPLACE_EXISTING};
256        if (Files.notExists(target))
257        {
258            try
259            {
260                Files.copy(source, target, options);
261            } catch (IOException x)
262            {
263                System.err.format("Unable to copy: %s: %s%n", source, x);
264            }
265        }
266    }
267    
268    /**
269     * A {@code FileVisitor} that copies a file-tree ("cp -r")
270     */
271    static class TreeCopier implements FileVisitor<Path>
272    {
273        private final Path source;
274        private final Path target;
275        
276        TreeCopier(Path source, Path target)
277        {
278            this.source = source;
279            this.target = target;
280        }
281        
282        @Override
283        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
284        {
285            // before visiting entries in a directory we copy the directory
286            // (okay if directory already exists).
287            CopyOption[] options = new CopyOption[0];
288            
289            Path newdir = target.resolve(source.relativize(dir));
290            try
291            {
292                Files.copy(dir, newdir, options);
293            } catch (FileAlreadyExistsException x)
294            {
295                // ignore
296            } catch (IOException x)
297            {
298                System.err.format("Unable to create: %s: %s%n", newdir, x);
299                return SKIP_SUBTREE;
300            }
301            return CONTINUE;
302        }
303        
304        @Override
305        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
306        {
307            copyFile(file, target.resolve(source.relativize(file)));
308            return CONTINUE;
309        }
310        
311        @Override
312        public FileVisitResult postVisitDirectory(Path dir, IOException exc)
313        {
314            // fix up modification time of directory when done
315            if (exc == null)
316            {
317                Path newdir = target.resolve(source.relativize(dir));
318                try
319                {
320                    FileTime time = Files.getLastModifiedTime(dir);
321                    Files.setLastModifiedTime(newdir, time);
322                } catch (IOException x)
323                {
324                    System.err.format("Unable to copy all attributes to: %s: %s%n", newdir, x);
325                }
326            }
327            return CONTINUE;
328        }
329        
330        @Override
331        public FileVisitResult visitFileFailed(Path file, IOException exc)
332        {
333            if (exc instanceof FileSystemLoopException)
334            {
335                System.err.println("cycle detected: " + file);
336            } else
337            {
338                System.err.format("Unable to copy: %s: %s%n", file, exc);
339            }
340            return CONTINUE;
341        }
342    }
343}