repo
stringlengths
5
75
commit
stringlengths
40
40
message
stringlengths
6
18.2k
diff
stringlengths
60
262k
antlr/antlrcs
5cd68fb596ca4a44ac0d54307e09396125114cb3
CSharp target: Generate XML documentation during the build
diff --git a/Antlr3.Runtime.Debug/Antlr3.Runtime.Debug.csproj b/Antlr3.Runtime.Debug/Antlr3.Runtime.Debug.csproj index a2d3d9c..9c52017 100644 --- a/Antlr3.Runtime.Debug/Antlr3.Runtime.Debug.csproj +++ b/Antlr3.Runtime.Debug/Antlr3.Runtime.Debug.csproj @@ -1,77 +1,79 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.30729</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{5EE27A90-B023-42C9-AAF1-52B0424C5D0B}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Antlr.Runtime.Debug</RootNamespace> <AssemblyName>Antlr3.Runtime.Debug</AssemblyName> <TargetFrameworkVersion>v2.0</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <SignAssembly>true</SignAssembly> <AssemblyOriginatorKeyFile>..\..\..\..\..\..\..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> + <DocumentationFile>bin\Debug\Antlr3.Runtime.Debug.xml</DocumentationFile> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> + <DocumentationFile>bin\Release\Antlr3.Runtime.Debug.xml</DocumentationFile> </PropertyGroup> <ItemGroup> <Reference Include="System" /> </ItemGroup> <ItemGroup> <Compile Include="BlankDebugEventListener.cs" /> <Compile Include="DebugEventHub.cs" /> <Compile Include="DebugEventListenerConstants.cs" /> <Compile Include="DebugEventRepeater.cs" /> <Compile Include="DebugEventSocketProxy.cs" /> <Compile Include="DebugParser.cs" /> <Compile Include="DebugTokenStream.cs" /> <Compile Include="DebugTreeAdaptor.cs" /> <Compile Include="DebugTreeNodeStream.cs" /> <Compile Include="DebugTreeParser.cs" /> <Compile Include="JavaExtensions\ExceptionExtensions.cs" /> <Compile Include="Misc\DoubleKeyMap`3.cs" /> <Compile Include="Misc\Stats.cs" /> <None Include="..\..\..\..\..\..\..\..\..\keys\antlr\Key.snk"> <Link>Key.snk</Link> </None> <None Include="ParserDebugger.cs" /> <Compile Include="ParseTreeBuilder.cs" /> <Compile Include="Profiler.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="RemoteDebugEventSocketListener.cs" /> <Compile Include="TraceDebugEventListener.cs" /> <Compile Include="Tracer.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Antlr3.Runtime\Antlr3.Runtime.csproj"> <Project>{8FDC0A87-9005-4D5A-AB75-E55CEB575559}</Project> <Name>Antlr3.Runtime</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file diff --git a/Antlr3.Runtime/Antlr3.Runtime.csproj b/Antlr3.Runtime/Antlr3.Runtime.csproj index c17ae73..5da739f 100644 --- a/Antlr3.Runtime/Antlr3.Runtime.csproj +++ b/Antlr3.Runtime/Antlr3.Runtime.csproj @@ -1,141 +1,143 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.30729</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{8FDC0A87-9005-4D5A-AB75-E55CEB575559}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Antlr.Runtime</RootNamespace> <AssemblyName>Antlr3.Runtime</AssemblyName> <TargetFrameworkVersion>v2.0</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <SignAssembly>true</SignAssembly> <AssemblyOriginatorKeyFile>..\..\..\..\..\..\..\..\..\keys\antlr\Key.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> + <DocumentationFile>bin\Debug\Antlr3.Runtime.xml</DocumentationFile> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> + <DocumentationFile>bin\Release\Antlr3.Runtime.xml</DocumentationFile> </PropertyGroup> <ItemGroup> <Reference Include="System" /> </ItemGroup> <ItemGroup> <Compile Include="ANTLRFileStream.cs" /> <Compile Include="ANTLRInputStream.cs" /> <Compile Include="ANTLRReaderStream.cs" /> <Compile Include="ANTLRStringStream.cs" /> <Compile Include="AstParserRuleReturnScope`2.cs" /> <Compile Include="BaseRecognizer.cs" /> <Compile Include="BitSet.cs" /> <Compile Include="BufferedTokenStream.cs" /> <Compile Include="CharStreamConstants.cs" /> <Compile Include="CharStreamState.cs" /> <Compile Include="ClassicToken.cs" /> <Compile Include="CommonToken.cs" /> <Compile Include="CommonTokenStream.cs" /> <Compile Include="Debug\IDebugEventListener.cs" /> <Compile Include="DFA.cs" /> <Compile Include="EarlyExitException.cs" /> <Compile Include="FailedPredicateException.cs" /> <Compile Include="GrammarRuleAttribute.cs" /> <Compile Include="IAstRuleReturnScope.cs" /> <Compile Include="IAstRuleReturnScope`1.cs" /> <Compile Include="ICharStream.cs" /> <Compile Include="IIntStream.cs" /> <Compile Include="IRuleReturnScope.cs" /> <Compile Include="IRuleReturnScope`1.cs" /> <Compile Include="ITemplateRuleReturnScope.cs" /> <Compile Include="ITemplateRuleReturnScope`1.cs" /> <Compile Include="IToken.cs" /> <Compile Include="ITokenSource.cs" /> <Compile Include="ITokenStream.cs" /> <Compile Include="ITokenStreamInformation.cs" /> <Compile Include="LegacyCommonTokenStream.cs" /> <Compile Include="Lexer.cs" /> <Compile Include="Misc\FastQueue.cs" /> <Compile Include="Misc\FunctionDelegates.cs" /> <Compile Include="Misc\ListStack`1.cs" /> <Compile Include="Misc\LookaheadStream.cs" /> <Compile Include="MismatchedNotSetException.cs" /> <Compile Include="MismatchedRangeException.cs" /> <Compile Include="MismatchedSetException.cs" /> <Compile Include="MismatchedTokenException.cs" /> <Compile Include="MismatchedTreeNodeException.cs" /> <Compile Include="MissingTokenException.cs" /> <Compile Include="NoViableAltException.cs" /> <Compile Include="Parser.cs" /> <Compile Include="ParserRuleReturnScope.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="RecognitionException.cs" /> <Compile Include="RecognizerSharedState.cs" /> <Compile Include="TemplateParserRuleReturnScope`2.cs" /> <Compile Include="TokenChannels.cs" /> <Compile Include="TokenRewriteStream.cs" /> <Compile Include="Tokens.cs" /> <Compile Include="TokenTypes.cs" /> <Compile Include="Tree\AstTreeRuleReturnScope`2.cs" /> <Compile Include="Tree\BaseTree.cs" /> <Compile Include="Tree\BaseTreeAdaptor.cs" /> <Compile Include="Tree\AntlrRuntime_BaseTreeDebugView.cs" /> <Compile Include="Tree\BufferedTreeNodeStream.cs" /> <Compile Include="Tree\CommonErrorNode.cs" /> <Compile Include="Tree\CommonTree.cs" /> <Compile Include="Tree\CommonTreeAdaptor.cs" /> <Compile Include="Tree\CommonTreeNodeStream.cs" /> <Compile Include="Tree\DotTreeGenerator.cs" /> <Compile Include="Tree\IPositionTrackingStream.cs" /> <Compile Include="Tree\ITree.cs" /> <Compile Include="Tree\ITreeAdaptor.cs" /> <Compile Include="Tree\ITreeNodeStream.cs" /> <Compile Include="Tree\ITreeVisitorAction.cs" /> <Compile Include="Tree\ParseTree.cs" /> <Compile Include="Tree\RewriteCardinalityException.cs" /> <Compile Include="Tree\RewriteEarlyExitException.cs" /> <Compile Include="Tree\RewriteEmptyStreamException.cs" /> <Compile Include="Tree\RewriteRuleElementStream.cs" /> <Compile Include="Tree\RewriteRuleNodeStream.cs" /> <Compile Include="Tree\RewriteRuleSubtreeStream.cs" /> <Compile Include="Tree\RewriteRuleTokenStream.cs" /> <Compile Include="Tree\TemplateTreeRuleReturnScope`2.cs" /> <Compile Include="Tree\TreeFilter.cs" /> <Compile Include="Tree\TreeIterator.cs" /> <Compile Include="Tree\TreeParser.cs" /> <Compile Include="Tree\TreePatternLexer.cs" /> <Compile Include="Tree\TreePatternParser.cs" /> <Compile Include="Tree\TreeRewriter.cs" /> <Compile Include="Tree\TreeRuleReturnScope`1.cs" /> <Compile Include="Tree\TreeVisitor.cs" /> <Compile Include="Tree\TreeWizard.cs" /> <Compile Include="UnbufferedTokenStream.cs" /> <Compile Include="UnwantedTokenException.cs" /> </ItemGroup> <ItemGroup> <None Include="..\..\..\..\..\..\..\..\..\keys\antlr\Key.snk"> <Link>Key.snk</Link> </None> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file
antlr/antlrcs
844a2eae17cbcfc05176b8c33c5f3c42b95ea5c0
CSharp targets: Updated assembly info for build 3.5.0.2
diff --git a/Antlr3.Runtime.Visualizer/Properties/AssemblyInfo.cs b/Antlr3.Runtime.Visualizer/Properties/AssemblyInfo.cs index 80aef28..d64b2b6 100644 --- a/Antlr3.Runtime.Visualizer/Properties/AssemblyInfo.cs +++ b/Antlr3.Runtime.Visualizer/Properties/AssemblyInfo.cs @@ -1,87 +1,87 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Antlr3.Runtime.Visualizer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tunnel Vision Laboratories, LLC")] [assembly: AssemblyProduct("Antlr3.Runtime.Visualizer")] [assembly: AssemblyCopyright("Copyright © Sam Harwell 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.StringTemplate/Properties/AssemblyInfo.cs b/Antlr3.StringTemplate/Properties/AssemblyInfo.cs index 8f05fc6..3b57849 100644 --- a/Antlr3.StringTemplate/Properties/AssemblyInfo.cs +++ b/Antlr3.StringTemplate/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.StringTemplate" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.StringTemplate" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant( true )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "a4b023e1-07a4-48c5-b095-1e1beb854b3d" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Targets/Antlr3.Targets.ActionScript/Properties/AssemblyInfo.cs b/Antlr3.Targets/Antlr3.Targets.ActionScript/Properties/AssemblyInfo.cs index 963b348..1651a14 100644 --- a/Antlr3.Targets/Antlr3.Targets.ActionScript/Properties/AssemblyInfo.cs +++ b/Antlr3.Targets/Antlr3.Targets.ActionScript/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Targets.ActionScript" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Targets.ActionScript" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "aa95e5e0-ddff-4ced-a130-69b0cd02f755" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Targets/Antlr3.Targets.C/Properties/AssemblyInfo.cs b/Antlr3.Targets/Antlr3.Targets.C/Properties/AssemblyInfo.cs index de43eae..0d91b41 100644 --- a/Antlr3.Targets/Antlr3.Targets.C/Properties/AssemblyInfo.cs +++ b/Antlr3.Targets/Antlr3.Targets.C/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Targets.C" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Targets.C" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "b8dcb19a-ffa0-4d55-8fd2-747d6c70c8ae" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Targets/Antlr3.Targets.CSharp2/Properties/AssemblyInfo.cs b/Antlr3.Targets/Antlr3.Targets.CSharp2/Properties/AssemblyInfo.cs index 6ddb1d8..ce620f8 100644 --- a/Antlr3.Targets/Antlr3.Targets.CSharp2/Properties/AssemblyInfo.cs +++ b/Antlr3.Targets/Antlr3.Targets.CSharp2/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Targets.CSharp2" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Targets.CSharp2" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "c30b57a2-68f1-44ec-b14b-3436d52a6233" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Targets/Antlr3.Targets.CSharp3/Properties/AssemblyInfo.cs b/Antlr3.Targets/Antlr3.Targets.CSharp3/Properties/AssemblyInfo.cs index a01d58b..c17122c 100644 --- a/Antlr3.Targets/Antlr3.Targets.CSharp3/Properties/AssemblyInfo.cs +++ b/Antlr3.Targets/Antlr3.Targets.CSharp3/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Target.CSharp3" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Target.CSharp3" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "efdd8135-be27-45be-8fd2-9070ff9df797" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Targets/Antlr3.Targets.Cpp/Properties/AssemblyInfo.cs b/Antlr3.Targets/Antlr3.Targets.Cpp/Properties/AssemblyInfo.cs index 9d0cafb..6203146 100644 --- a/Antlr3.Targets/Antlr3.Targets.Cpp/Properties/AssemblyInfo.cs +++ b/Antlr3.Targets/Antlr3.Targets.Cpp/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Targets.Cpp" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Targets.Cpp" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "8e891174-fb0e-45c6-953d-d847b757bcc9" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Targets/Antlr3.Targets.Delphi/Properties/AssemblyInfo.cs b/Antlr3.Targets/Antlr3.Targets.Delphi/Properties/AssemblyInfo.cs index eedce0f..9ae99ac 100644 --- a/Antlr3.Targets/Antlr3.Targets.Delphi/Properties/AssemblyInfo.cs +++ b/Antlr3.Targets/Antlr3.Targets.Delphi/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Targets.Delphi" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Targets.Delphi" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "0987d253-96de-4d56-9387-dc6f4293a374" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Targets/Antlr3.Targets.Java/Properties/AssemblyInfo.cs b/Antlr3.Targets/Antlr3.Targets.Java/Properties/AssemblyInfo.cs index c042e55..70afdf8 100644 --- a/Antlr3.Targets/Antlr3.Targets.Java/Properties/AssemblyInfo.cs +++ b/Antlr3.Targets/Antlr3.Targets.Java/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Targets.Java" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Targets.Java" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "2388a4ff-439f-48b3-80fd-364f7bccfb9d" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Targets/Antlr3.Targets.JavaScript/Properties/AssemblyInfo.cs b/Antlr3.Targets/Antlr3.Targets.JavaScript/Properties/AssemblyInfo.cs index ef2f59e..3ec4309 100644 --- a/Antlr3.Targets/Antlr3.Targets.JavaScript/Properties/AssemblyInfo.cs +++ b/Antlr3.Targets/Antlr3.Targets.JavaScript/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Targets.JavaScript" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Targets.JavaScript" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "4fbc2549-85b3-43fa-8994-cb4ac111a33c" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Targets/Antlr3.Targets.ObjC/Properties/AssemblyInfo.cs b/Antlr3.Targets/Antlr3.Targets.ObjC/Properties/AssemblyInfo.cs index f3d4f6e..1420590 100644 --- a/Antlr3.Targets/Antlr3.Targets.ObjC/Properties/AssemblyInfo.cs +++ b/Antlr3.Targets/Antlr3.Targets.ObjC/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Targets.ObjC" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Targets.ObjC" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "a8b15bc5-58a3-49d3-982d-051730d2bd79" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Targets/Antlr3.Targets.Perl5/Properties/AssemblyInfo.cs b/Antlr3.Targets/Antlr3.Targets.Perl5/Properties/AssemblyInfo.cs index eddb254..1c7d398 100644 --- a/Antlr3.Targets/Antlr3.Targets.Perl5/Properties/AssemblyInfo.cs +++ b/Antlr3.Targets/Antlr3.Targets.Perl5/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Targets.Perl5" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Targets.Perl5" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "3d2be877-baf6-4b83-961a-b91aed7b8258" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Targets/Antlr3.Targets.Python/Properties/AssemblyInfo.cs b/Antlr3.Targets/Antlr3.Targets.Python/Properties/AssemblyInfo.cs index 25aef8b..8e43403 100644 --- a/Antlr3.Targets/Antlr3.Targets.Python/Properties/AssemblyInfo.cs +++ b/Antlr3.Targets/Antlr3.Targets.Python/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Targets.Python" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Targets.Python" )] [assembly: AssemblyCopyright("Copyright © Sam Harwell 2013")] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "e40e91d9-3120-4442-86d8-33571ee23495" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Targets/Antlr3.Targets.Python3/Properties/AssemblyInfo.cs b/Antlr3.Targets/Antlr3.Targets.Python3/Properties/AssemblyInfo.cs index 25aef8b..8e43403 100644 --- a/Antlr3.Targets/Antlr3.Targets.Python3/Properties/AssemblyInfo.cs +++ b/Antlr3.Targets/Antlr3.Targets.Python3/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Targets.Python" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Targets.Python" )] [assembly: AssemblyCopyright("Copyright © Sam Harwell 2013")] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "e40e91d9-3120-4442-86d8-33571ee23495" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Targets/Antlr3.Targets.Ruby/Properties/AssemblyInfo.cs b/Antlr3.Targets/Antlr3.Targets.Ruby/Properties/AssemblyInfo.cs index 3008512..6eca3e9 100644 --- a/Antlr3.Targets/Antlr3.Targets.Ruby/Properties/AssemblyInfo.cs +++ b/Antlr3.Targets/Antlr3.Targets.Ruby/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Targets.Ruby" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Targets.Ruby" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "9471023a-b241-4aed-a706-c8e8fa621dbf" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Test/Properties/AssemblyInfo.cs b/Antlr3.Test/Properties/AssemblyInfo.cs index 106cd32..e293dcc 100644 --- a/Antlr3.Test/Properties/AssemblyInfo.cs +++ b/Antlr3.Test/Properties/AssemblyInfo.cs @@ -1,67 +1,67 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "AntlrUnitTests" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Pixel Mine, Inc." )] [assembly: AssemblyProduct( "AntlrUnitTests" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM componenets. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "a0f4c939-114e-4512-8eb1-fad6056493aa" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3/Properties/AssemblyInfo.cs b/Antlr3/Properties/AssemblyInfo.cs index 20c4a90..9e79585 100644 --- a/Antlr3/Properties/AssemblyInfo.cs +++ b/Antlr3/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3" )] [assembly: AssemblyCopyright("Copyright © Sam Harwell 2013")] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "1f192196-5fb0-4eea-91a1-e9249dd45317" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/AntlrBuildTask/Antlr3.targets b/AntlrBuildTask/Antlr3.targets index 70b7c57..c5f5c70 100644 --- a/AntlrBuildTask/Antlr3.targets +++ b/AntlrBuildTask/Antlr3.targets @@ -1,169 +1,169 @@ <!-- [The "BSD licence"] Copyright (c) 2011 Sam Harwell All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <BuildSystem>MSBuild</BuildSystem> - <TaskVersion>3.5.0.1</TaskVersion> + <TaskVersion>3.5.0.2</TaskVersion> <TaskKeyToken>eb42632606e9261f</TaskKeyToken> <AntlrBuildTaskAssemblyName Condition="'$(AntlrBuildTaskAssemblyName)'==''">AntlrBuildTask, Version=$(TaskVersion), Culture=neutral, PublicKeyToken=$(TaskKeyToken)</AntlrBuildTaskAssemblyName> </PropertyGroup> <PropertyGroup> <LoadTimeSensitiveTargets> $(LoadTimeSensitiveTargets); AntlrCompile; </LoadTimeSensitiveTargets> <LoadTimeSensitiveProperties> $(LoadTimeSensitiveProperties); AntlrCompileDependsOn; </LoadTimeSensitiveProperties> </PropertyGroup> <PropertyGroup> <AntlrBuildTaskLocation Condition="'$(AntlrBuildTaskPath)'==''">$(MSBuildBinPath)</AntlrBuildTaskLocation> <AntlrBuildTaskLocation Condition="'$(AntlrBuildTaskPath)'!=''">$(AntlrBuildTaskPath)</AntlrBuildTaskLocation> <AntlrToolLocation Condition="'$(AntlrToolPath)'==''">$(MSBuildBinPath)\Antlr3\Antlr3.exe</AntlrToolLocation> <AntlrToolLocation Condition="'$(AntlrToolPath)'!=''">$(AntlrToolPath)</AntlrToolLocation> </PropertyGroup> <PropertyGroup> <AntlrGenCodeFileNames Condition="'$(AntlrGenCodeFileNames)'==''">$(MSBuildProjectFile).AntlrGeneratedCodeFileListAbsolute.txt</AntlrGenCodeFileNames> </PropertyGroup> <UsingTask Condition="'$(AntlrBuildTaskPath)'==''" TaskName="Antlr3.Build.Tasks.AntlrClassGenerationTask" AssemblyName="$(AntlrBuildTaskAssemblyName)" /> <UsingTask Condition="'$(AntlrBuildTaskPath)'!=''" TaskName="Antlr3.Build.Tasks.AntlrClassGenerationTask" AssemblyFile="$(AntlrBuildTaskPath)\AntlrBuildTask.dll" /> <PropertyGroup> <PrepareResourcesDependsOn> AntlrCompile; AntlrCompileAddFilesGenerated; $(PrepareResourcesDependsOn) </PrepareResourcesDependsOn> </PropertyGroup> <PropertyGroup> <AntlrCompileDependsOn> AntlrCompileReadGeneratedFileList </AntlrCompileDependsOn> </PropertyGroup> <ItemGroup Condition="'$(BuildingInsideVisualStudio)'=='true'"> <AvailableItemName Include="Antlr3" /> <AvailableItemName Include="AntlrTokens" /> <AvailableItemName Include="AntlrAbstractGrammar" /> </ItemGroup> <ItemDefinitionGroup> <Antlr3> <Generator>MSBuild:Compile</Generator> <TargetLanguage/> <DebugGrammar>false</DebugGrammar> <ProfileGrammar>false</ProfileGrammar> </Antlr3> </ItemDefinitionGroup> <Target Name="AntlrCompileReadGeneratedFileList"> <ReadLinesFromFile File="$(IntermediateOutputPath)$(AntlrGenCodeFileNames)"> <Output TaskParameter="Lines" ItemName="AntlrOutputCodeFilesList"/> </ReadLinesFromFile> </Target> <PropertyGroup> <!-- Add grammar compilation to the CoreCompileDependsOn so that the IDE inproc compilers (particularly VB) can "see" the generated source files. --> <CoreCompileDependsOn Condition="'$(BuildingInsideVisualStudio)' == 'true' "> DesignTimeGrammarCompilation; $(CoreCompileDependsOn) </CoreCompileDependsOn> </PropertyGroup> <Target Name="DesignTimeGrammarCompilation"> <!-- Only if we are not actually performing a compile i.e. we are in design mode --> <CallTarget Condition="'$(BuildingProject)' != 'true'" Targets="AntlrCompile" /> </Target> <Target Name="AntlrCompile" DependsOnTargets="$(AntlrCompileDependsOn)" Condition="'@(Antlr3)' != ''" Inputs="@(Antlr3);@(AntlrTokens);@(AntlrAbstractGrammar)" Outputs="@(AntlrOutputCodeFilesList); $(IntermediateOutputPath)$(AntlrGenCodeFileNames);"> <ItemGroup> <AntlrGeneratedCodeFiles Remove="@(AntlrGeneratedCodeFiles)" /> </ItemGroup> <PropertyGroup> <_IntellisenseOnlyCompile>false</_IntellisenseOnlyCompile> <_IntellisenseOnlyCompile Condition="'$(BuildingProject)' != 'true'">true</_IntellisenseOnlyCompile> </PropertyGroup> <AntlrClassGenerationTask AntlrToolPath="$(AntlrToolLocation)" BuildTaskPath="$(AntlrBuildTaskLocation)" OutputPath="$(IntermediateOutputPath)" TargetLanguage="%(Antlr3.TargetLanguage)" SourceCodeFiles="@(Antlr3)" ContinueOnError="$(_IntellisenseOnlyCompile)" TokensFiles="@(AntlrTokens)" AbstractGrammarFiles="@(AntlrAbstractGrammar)" LanguageSourceExtensions="$(DefaultLanguageSourceExtension)" DebugGrammar="%(Antlr3.DebugGrammar)" ProfileGrammar="%(Antlr3.ProfileGrammar)"> <Output ItemName="AntlrGeneratedCodeFiles" TaskParameter="GeneratedCodeFiles" /> </AntlrClassGenerationTask> <WriteLinesToFile Condition="'$(_IntellisenseOnlyCompile)' != 'true'" File="$(IntermediateOutputPath)$(AntlrGenCodeFileNames)" Lines="@(AntlrGeneratedCodeFiles)" Overwrite="true"/> </Target> <Target Name="AntlrCompileAddFilesGenerated" AfterTargets="AntlrCompile" Condition="'@(Antlr3)' != ''"> <ItemGroup> <AntlrGeneratedCodeFiles Condition="'@(AntlrGeneratedCodeFiles)' == ''" Include="@(AntlrOutputCodeFilesList)" /> </ItemGroup> <ItemGroup> <FileWrites Include="@(AntlrGeneratedCodeFiles); $(IntermediateOutputPath)$(AntlrGenCodeFileNames);" /> </ItemGroup> <ItemGroup> <Compile Include="@(AntlrGeneratedCodeFiles)" /> <!-- The WinFX "GenerateTemporaryTargetAssembly" target requires generated code files be added here. --> <_GeneratedCodeFiles Include="@(AntlrGeneratedCodeFiles)" /> </ItemGroup> </Target> </Project> diff --git a/AntlrBuildTask/Properties/AssemblyInfo.cs b/AntlrBuildTask/Properties/AssemblyInfo.cs index aba34e6..08851b1 100644 --- a/AntlrBuildTask/Properties/AssemblyInfo.cs +++ b/AntlrBuildTask/Properties/AssemblyInfo.cs @@ -1,70 +1,70 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2010 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AntlrBuildTask")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tunnel Vision Laboratories, LLC")] [assembly: AssemblyProduct("AntlrBuildTask")] [assembly: AssemblyCopyright("Copyright © Sam Harwell 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2028affe-3dfd-4164-9faf-2959ec04f7f7")] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. * 3. Revision is the Perforce changelist number associated with the release. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Reference/antlr3 b/Reference/antlr3 index 69fb819..16284da 160000 --- a/Reference/antlr3 +++ b/Reference/antlr3 @@ -1 +1 @@ -Subproject commit 69fb819c6ab81f5520273e8bc2f378e67db6c61c +Subproject commit 16284da4436bcb57f339db01e81c4bea94663fff
antlr/antlrcs
eaec59a4f0cf9266d52c76d32bfc34b4020bc1c6
CSharp targets: Updated assembly info for build 3.5.0.2
diff --git a/Antlr3.Runtime.Debug/Properties/AssemblyInfo.cs b/Antlr3.Runtime.Debug/Properties/AssemblyInfo.cs index a3f2477..038cddb 100644 --- a/Antlr3.Runtime.Debug/Properties/AssemblyInfo.cs +++ b/Antlr3.Runtime.Debug/Properties/AssemblyInfo.cs @@ -1,70 +1,70 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Runtime.Debug" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Runtime.Debug" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant( true )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "9f8fa018-6766-404c-9e72-551407e1b173" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. * 3. Revision is the Perforce changelist number associated with the release. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Runtime.JavaExtensions/Properties/AssemblyInfo.cs b/Antlr3.Runtime.JavaExtensions/Properties/AssemblyInfo.cs index 9439e35..00e66a9 100644 --- a/Antlr3.Runtime.JavaExtensions/Properties/AssemblyInfo.cs +++ b/Antlr3.Runtime.JavaExtensions/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2010 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Runtime.JavaExtensions" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Runtime.JavaExtensions" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant( true )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "ad48c7f7-0b1d-4b1e-9602-83425cb5699f" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Runtime.Test/Properties/AssemblyInfo.cs b/Antlr3.Runtime.Test/Properties/AssemblyInfo.cs index 7437eda..1e0fc38 100644 --- a/Antlr3.Runtime.Test/Properties/AssemblyInfo.cs +++ b/Antlr3.Runtime.Test/Properties/AssemblyInfo.cs @@ -1,70 +1,70 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Runtime.Test" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Pixel Mine, Inc." )] [assembly: AssemblyProduct( "Antlr3.Runtime.Test" )] [assembly: AssemblyCopyright("Copyright © Sam Harwell 2013")] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant( true )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "1352b15b-eded-4380-9122-acde32f7ff38" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. * 3. Revision is the Perforce changelist number associated with the release. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")] diff --git a/Antlr3.Runtime/Properties/AssemblyInfo.cs b/Antlr3.Runtime/Properties/AssemblyInfo.cs index 42f80e7..cc3425f 100644 --- a/Antlr3.Runtime/Properties/AssemblyInfo.cs +++ b/Antlr3.Runtime/Properties/AssemblyInfo.cs @@ -1,72 +1,72 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Runtime" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Runtime" )] [assembly: AssemblyCopyright("Copyright © Sam Harwell 2013")] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant( true )] [assembly: AllowPartiallyTrustedCallers] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "7a0b4db7-f127-4cf5-ac2c-e294957efcd6" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. * 3. Revision is the Perforce changelist number associated with the release. */ -[assembly: AssemblyVersion("3.5.0.1")] -[assembly: AssemblyFileVersion("3.5.0.1")] +[assembly: AssemblyVersion("3.5.0.2")] +[assembly: AssemblyFileVersion("3.5.0.2")]
antlr/antlrcs
7b573f8dc419d907251878795c01cdee833baeb7
C# port: Fix CommonTreeNodeStream implementation of IPositionTrackingStream
diff --git a/Antlr3.Runtime/Misc/LookaheadStream.cs b/Antlr3.Runtime/Misc/LookaheadStream.cs index 38c26a8..14454a8 100644 --- a/Antlr3.Runtime/Misc/LookaheadStream.cs +++ b/Antlr3.Runtime/Misc/LookaheadStream.cs @@ -1,271 +1,271 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr.Runtime.Misc { using ArgumentException = System.ArgumentException; using Debug = System.Diagnostics.Debug; using InvalidOperationException = System.InvalidOperationException; using NotSupportedException = System.NotSupportedException; using ArgumentOutOfRangeException = System.ArgumentOutOfRangeException; /** <summary> * A lookahead queue that knows how to mark/release locations in the buffer for * backtracking purposes. Any markers force the {@link FastQueue} superclass to * keep all elements until no more markers; then can reset to avoid growing a * huge buffer. * </summary> */ public abstract class LookaheadStream<T> : FastQueue<T> where T : class { /** Absolute token index. It's the index of the symbol about to be * read via {@code LT(1)}. Goes from 0 to numtokens. */ private int _currentElementIndex = 0; /** * This is the {@code LT(-1)} element for the first element in {@link #data}. */ private T _previousElement; /** Track object returned by nextElement upon end of stream; * Return it later when they ask for LT passed end of input. */ T _eof = null; /** <summary>Track the last mark() call result value for use in rewind().</summary> */ int _lastMarker; /** <summary>tracks how deep mark() calls are nested</summary> */ int _markDepth; public T EndOfFile { get { return _eof; } protected set { _eof = value; } } public T PreviousElement { get { return _previousElement; } } - public override void Clear() + public virtual void Reset() { - base.Clear(); + Clear(); _currentElementIndex = 0; _p = 0; _previousElement = null; } /** <summary> * Implement nextElement to supply a stream of elements to this * lookahead buffer. Return EOF upon end of the stream we're pulling from. * </summary> */ public abstract T NextElement(); public abstract bool IsEndOfFile(T o); /** <summary> * Get and remove first element in queue; override * {@link FastQueue#remove()}; it's the same, just checks for backtracking. * </summary> */ public override T Dequeue() { T o = this[0]; _p++; // have we hit end of buffer and not backtracking? if ( _p == _data.Count && _markDepth == 0 ) { _previousElement = o; // if so, it's an opportunity to start filling at index 0 again Clear(); // size goes to 0, but retains memory } return o; } /** <summary>Make sure we have at least one element to remove, even if EOF</summary> */ public virtual void Consume() { SyncAhead(1); Dequeue(); _currentElementIndex++; } /** <summary> * Make sure we have 'need' elements from current position p. Last valid * p index is data.size()-1. p+need-1 is the data index 'need' elements * ahead. If we need 1 element, (p+1-1)==p must be &lt; data.size(). * </summary> */ protected virtual void SyncAhead( int need ) { int n = ( _p + need - 1 ) - _data.Count + 1; // how many more elements we need? if ( n > 0 ) Fill( n ); // out of elements? } /** <summary>add n elements to buffer</summary> */ public virtual void Fill( int n ) { for ( int i = 0; i < n; i++ ) { T o = NextElement(); if ( IsEndOfFile(o) ) _eof = o; _data.Add( o ); } } /** <summary>Size of entire stream is unknown; we only know buffer size from FastQueue</summary> */ public override int Count { get { throw new System.NotSupportedException( "streams are of unknown size" ); } } public virtual T LT( int k ) { if ( k == 0 ) { return null; } if ( k < 0 ) { return LB(-k); } SyncAhead( k ); if ((_p + k - 1) > _data.Count) return _eof; return this[k - 1]; } public virtual int Index { get { return _currentElementIndex; } } public virtual int Mark() { _markDepth++; _lastMarker = _p; // track where we are in buffer, not absolute token index return _lastMarker; } public virtual void Release( int marker ) { if (_markDepth == 0) throw new InvalidOperationException(); _markDepth--; } public virtual void Rewind( int marker ) { _markDepth--; int delta = _p - marker; _currentElementIndex -= delta; _p = marker; } public virtual void Rewind() { // rewind but do not release marker int delta = _p - _lastMarker; _currentElementIndex -= delta; _p = _lastMarker; } /** <summary> * Seek to a 0-indexed absolute token index. Normally used to seek backwards * in the buffer. Does not force loading of nodes. * </summary> * <remarks> * To preserve backward compatibility, this method allows seeking past the * end of the currently buffered data. In this case, the input pointer will * be moved but the data will only actually be loaded upon the next call to * {@link #consume} or {@link #LT} for {@code k>0}. * </remarks> */ public virtual void Seek( int index ) { if (index < 0) throw new ArgumentOutOfRangeException("index"); int delta = _currentElementIndex - index; if (_p - delta < 0) throw new NotSupportedException("can't seek before the beginning of this stream's buffer"); _p -= delta; _currentElementIndex = index; } protected virtual T LB(int k) { Debug.Assert(k > 0); int index = _p - k; if (index == -1) return _previousElement; // if k>0 then we know index < data.size(). avoid the double-check for // performance. if (index >= 0 /*&& index < data.size()*/) return _data[index]; if (index < -1) throw new NotSupportedException("can't look more than one token before the beginning of this stream's buffer"); throw new NotSupportedException("can't look past the end of this stream's buffer using LB(int)"); } } } diff --git a/Antlr3.Runtime/Tree/CommonTreeNodeStream.cs b/Antlr3.Runtime/Tree/CommonTreeNodeStream.cs index 1764d1e..f9cb0a7 100644 --- a/Antlr3.Runtime/Tree/CommonTreeNodeStream.cs +++ b/Antlr3.Runtime/Tree/CommonTreeNodeStream.cs @@ -1,312 +1,312 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr.Runtime.Tree { using System.Collections.Generic; using Antlr.Runtime.Misc; using StringBuilder = System.Text.StringBuilder; [System.Serializable] public class CommonTreeNodeStream : LookaheadStream<object>, ITreeNodeStream, IPositionTrackingStream { public const int DEFAULT_INITIAL_BUFFER_SIZE = 100; public const int INITIAL_CALL_STACK_SIZE = 10; /** <summary>Pull nodes from which tree?</summary> */ private readonly object _root; /** <summary>If this tree (root) was created from a token stream, track it.</summary> */ protected ITokenStream tokens; /** <summary>What tree adaptor was used to build these trees</summary> */ [System.NonSerialized] private ITreeAdaptor _adaptor; /** The tree iterator we are using */ private readonly TreeIterator _it; /** <summary>Stack of indexes used for push/pop calls</summary> */ private Stack<int> _calls; /** <summary>Tree (nil A B C) trees like flat A B C streams</summary> */ private bool _hasNilRoot = false; /** <summary>Tracks tree depth. Level=0 means we're at root node level.</summary> */ private int _level = 0; /** * Tracks the last node before the start of {@link #data} which contains * position information to provide information for error reporting. This is * tracked in addition to {@link #prevElement} which may or may not contain * position information. * * @see #hasPositionInformation * @see RecognitionException#extractInformationFromTreeNodeStream */ private object _previousLocationElement; public CommonTreeNodeStream( object tree ) : this( new CommonTreeAdaptor(), tree ) { } public CommonTreeNodeStream( ITreeAdaptor adaptor, object tree ) { this._root = tree; this._adaptor = adaptor; _it = new TreeIterator( adaptor, _root ); } #region Properties public virtual string SourceName { get { if ( TokenStream == null ) return null; return TokenStream.SourceName; } } public virtual ITokenStream TokenStream { get { return tokens; } set { tokens = value; } } public virtual ITreeAdaptor TreeAdaptor { get { return _adaptor; } set { _adaptor = value; } } public virtual object TreeSource { get { return _root; } } public virtual bool UniqueNavigationNodes { get { return false; } set { } } #endregion - public virtual void Reset() + public override void Reset() { - base.Clear(); + base.Reset(); _it.Reset(); _hasNilRoot = false; _level = 0; _previousLocationElement = null; if ( _calls != null ) _calls.Clear(); } public override object NextElement() { _it.MoveNext(); object t = _it.Current; //System.out.println("pulled "+adaptor.getType(t)); if ( t == _it.up ) { _level--; if ( _level == 0 && _hasNilRoot ) { _it.MoveNext(); return _it.Current; // don't give last UP; get EOF } } else if ( t == _it.down ) { _level++; } if ( _level == 0 && TreeAdaptor.IsNil( t ) ) { // if nil root, scarf nil, DOWN _hasNilRoot = true; _it.MoveNext(); t = _it.Current; // t is now DOWN, so get first real node next _level++; _it.MoveNext(); t = _it.Current; } return t; } public override object Dequeue() { object result = base.Dequeue(); if (_p == 0 && HasPositionInformation(PreviousElement)) _previousLocationElement = PreviousElement; return result; } public override bool IsEndOfFile(object o) { return TreeAdaptor.GetType(o) == CharStreamConstants.EndOfFile; } public virtual int LA( int i ) { return TreeAdaptor.GetType( LT( i ) ); } /** Make stream jump to a new location, saving old location. * Switch back with pop(). */ public virtual void Push( int index ) { if ( _calls == null ) _calls = new Stack<int>(); _calls.Push( _p ); // save current index Seek( index ); } /** Seek back to previous index saved during last push() call. * Return top of stack (return index). */ public virtual int Pop() { int ret = _calls.Pop(); Seek( ret ); return ret; } /** * Returns an element containing position information. If {@code allowApproximateLocation} is {@code false}, then * this method will return the {@code LT(1)} element if it contains position information, and otherwise return {@code null}. * If {@code allowApproximateLocation} is {@code true}, then this method will return the last known element containing position information. * * @see #hasPositionInformation */ public object GetKnownPositionElement(bool allowApproximateLocation) { object node = _data[_p]; if (HasPositionInformation(node)) return node; if (!allowApproximateLocation) return null; for (int index = _p - 1; index >= 0; index--) { node = _data[index]; if (HasPositionInformation(node)) return node; } return _previousLocationElement; } public bool HasPositionInformation(object node) { IToken token = TreeAdaptor.GetToken(node); if (token == null) return false; if (token.Line <= 0) return false; return true; } #region Tree rewrite interface public virtual void ReplaceChildren( object parent, int startChildIndex, int stopChildIndex, object t ) { if ( parent != null ) { TreeAdaptor.ReplaceChildren( parent, startChildIndex, stopChildIndex, t ); } } #endregion public virtual string ToString( object start, object stop ) { // we'll have to walk from start to stop in tree; we're not keeping // a complete node stream buffer return "n/a"; } /** <summary>For debugging; destructive: moves tree iterator to end.</summary> */ public virtual string ToTokenTypeString() { Reset(); StringBuilder buf = new StringBuilder(); object o = LT( 1 ); int type = TreeAdaptor.GetType( o ); while ( type != TokenTypes.EndOfFile ) { buf.Append( " " ); buf.Append( type ); Consume(); o = LT( 1 ); type = TreeAdaptor.GetType( o ); } return buf.ToString(); } } }
antlr/antlrcs
e7fbcb06818789bcf1f0e6106fdf9421d2cc8c5c
CSharp: simplify project file
diff --git a/Antlr3.Runtime.Test/Antlr3.Runtime.Test.csproj b/Antlr3.Runtime.Test/Antlr3.Runtime.Test.csproj index 07a907e..75c4cac 100644 --- a/Antlr3.Runtime.Test/Antlr3.Runtime.Test.csproj +++ b/Antlr3.Runtime.Test/Antlr3.Runtime.Test.csproj @@ -1,215 +1,187 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.30729</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{19B965DE-5100-4064-A580-159644F6980E}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Antlr3.Runtime.Test</RootNamespace> <AssemblyName>Antlr3.Runtime.Test</AssemblyName> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Numerics" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\..\..\..\Antlr3.StringTemplate\Antlr3.StringTemplate.csproj"> <Project>{B5910BE2-DE21-4AA9-95C1-486F42B9E794}</Project> <Name>Antlr3.StringTemplate</Name> </ProjectReference> <ProjectReference Include="..\Antlr3.Runtime.Debug\Antlr3.Runtime.Debug.csproj"> <Project>{5EE27A90-B023-42C9-AAF1-52B0424C5D0B}</Project> <Name>Antlr3.Runtime.Debug</Name> </ProjectReference> <ProjectReference Include="..\Antlr3.Runtime.JavaExtensions\Antlr3.Runtime.JavaExtensions.csproj"> <Project>{A7EEC557-EB14-451C-9616-B7A61F4ECE69}</Project> <Name>Antlr3.Runtime.JavaExtensions</Name> </ProjectReference> <ProjectReference Include="..\Antlr3.Runtime\Antlr3.Runtime.csproj"> <Project>{8FDC0A87-9005-4D5A-AB75-E55CEB575559}</Project> <Name>Antlr3.Runtime</Name> </ProjectReference> </ItemGroup> <ItemGroup> - <Antlr3 Include="SimpleExpression.g3"> - <Generator>MSBuild:Compile</Generator> - </Antlr3> - <Antlr3 Include="FastSimpleExpression.g3"> - <Generator>MSBuild:Compile</Generator> - </Antlr3> - <None Include="JavaCompat\Expr.g3"> - <Generator>MSBuild:Compile</Generator> - </None> + <Antlr3 Include="SimpleExpression.g3" /> + <Antlr3 Include="FastSimpleExpression.g3" /> + <None Include="JavaCompat\Expr.g3" /> <Antlr3 Include="BuildOptions\DebugGrammar.g3"> <!--<GrammarOptions>-debug</GrammarOptions>--> - <Generator>MSBuild:Compile</Generator> </Antlr3> <Antlr3 Include="BuildOptions\DebugTreeGrammar.g3"> <!--<GrammarOptions>-debug</GrammarOptions>--> - <Generator>MSBuild:Compile</Generator> - </Antlr3> - <Antlr3 Include="StringTemplateOutput.g3"> - <Generator>MSBuild:Compile</Generator> - </Antlr3> - <Antlr3 Include="TestActionFeatures.g3"> - <Generator>MSBuild:Compile</Generator> - </Antlr3> - <Antlr3 Include="SemanticPredicateReduction.g3"> - <Generator>MSBuild:Compile</Generator> - </Antlr3> - <Antlr3 Include="Composition\Reduce.g3"> - <Generator>MSBuild:Compile</Generator> - </Antlr3> - <Antlr3 Include="Composition\Simplify.g3"> - <Generator>MSBuild:Compile</Generator> - </Antlr3> - <Antlr3 Include="Composition\VecMath.g3"> - <Generator>MSBuild:Compile</Generator> </Antlr3> + <Antlr3 Include="StringTemplateOutput.g3" /> + <Antlr3 Include="TestActionFeatures.g3" /> + <Antlr3 Include="SemanticPredicateReduction.g3" /> + <Antlr3 Include="Composition\Reduce.g3" /> + <Antlr3 Include="Composition\Simplify.g3" /> + <Antlr3 Include="Composition\VecMath.g3" /> <AntlrAbstractGrammar Include="Composition\VecMath_Lexer.g3"> <Generator>MSBuild:Compile</Generator> </AntlrAbstractGrammar> <AntlrAbstractGrammar Include="Composition\VecMath_Parser.g3"> <Generator>MSBuild:Compile</Generator> </AntlrAbstractGrammar> - <Antlr3 Include="PreprocessorLexer.g3"> - <Generator>MSBuild:Compile</Generator> - </Antlr3> - <Antlr3 Include="SynpredTreeParser.g3"> - <Generator>MSBuild:Compile</Generator> - </Antlr3> + <Antlr3 Include="PreprocessorLexer.g3" /> + <Antlr3 Include="SynpredTreeParser.g3" /> </ItemGroup> <ItemGroup> <Compile Include="Composition\Program.cs" /> <Compile Include="PreprocessorLexer.g3.cs"> <DependentUpon>PreprocessorLexer.g3</DependentUpon> </Compile> <Compile Include="PreprocessorTests.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="SemanticPredicateReduction.g3.lexer.cs"> <DependentUpon>SemanticPredicateReduction.g3</DependentUpon> </Compile> <Compile Include="SemanticPredicateReduction.g3.parser.cs"> <DependentUpon>SemanticPredicateReduction.g3</DependentUpon> </Compile> <Compile Include="SimpleExpressionLexerHelper.cs"> <DependentUpon>SimpleExpression.g3</DependentUpon> </Compile> <Compile Include="SimpleExpressionParserHelper.cs"> <DependentUpon>SimpleExpression.g3</DependentUpon> </Compile> <Compile Include="FastSimpleExpressionLexerHelper.cs"> <DependentUpon>FastSimpleExpression.g3</DependentUpon> </Compile> <Compile Include="FastSimpleExpressionParserHelper.cs"> <DependentUpon>FastSimpleExpression.g3</DependentUpon> </Compile> <Compile Include="BuildOptions\DebugGrammarLexerHelper.cs"> <DependentUpon>DebugGrammar.g3</DependentUpon> </Compile> <Compile Include="BuildOptions\DebugGrammarParserHelper.cs"> <DependentUpon>DebugGrammar.g3</DependentUpon> </Compile> <Compile Include="BuildOptions\DebugTreeGrammarHelper.cs"> <DependentUpon>DebugTreeGrammar.g3</DependentUpon> </Compile> <Compile Include="SlimParsing\ITokenSource`1.cs" /> <Compile Include="SlimParsing\ITokenStream`1.cs" /> <Compile Include="SlimParsing\SlimLexer.cs" /> <Compile Include="SlimParsing\SlimStringStream.cs" /> <Compile Include="SlimParsing\SlimToken.cs" /> <Compile Include="SlimParsing\SlimTokenStream.cs" /> <Compile Include="SlimParsing\Tree\ITreeAdaptor`1.cs" /> <Compile Include="SlimParsing\Tree\ITreeFactory.cs" /> <Compile Include="SlimParsing\Tree\ITreeNodeStream`1.cs" /> <Compile Include="StringTemplateOutput.g3.lexer.cs"> <DependentUpon>StringTemplateOutput.g3</DependentUpon> </Compile> <Compile Include="StringTemplateOutput.g3.parser.cs"> <DependentUpon>StringTemplateOutput.g3</DependentUpon> </Compile> <Compile Include="SynpredTreeParser.g3.cs"> <DependentUpon>SynpredTreeParser.g3</DependentUpon> </Compile> <Compile Include="TestActionFeatures.g3.lexer.cs"> <DependentUpon>TestActionFeatures.g3</DependentUpon> </Compile> <Compile Include="TestActionFeatures.g3.parser.cs"> <DependentUpon>TestActionFeatures.g3</DependentUpon> </Compile> <Compile Include="TestDotTreeGenerator.cs" /> <Compile Include="TestExpressionFeatures.g3.lexer.cs"> <DependentUpon>TestExpressionFeatures.g3</DependentUpon> </Compile> <Compile Include="TestExpressionFeatures.g3.parser.cs"> <DependentUpon>TestExpressionFeatures.g3</DependentUpon> </Compile> <Compile Include="TestFastLexer.cs" /> </ItemGroup> <ItemGroup> <None Include="BuildOptions\ProfileGrammar.g3"> <!--<GrammarOptions>-profile</GrammarOptions>--> - <Generator>MSBuild:Compile</Generator> </None> <None Include="BuildOptions\ProfileGrammarLexerHelper.cs"> <DependentUpon>ProfileGrammar.g3</DependentUpon> </None> <None Include="BuildOptions\ProfileGrammarParserHelper.cs"> <DependentUpon>ProfileGrammar.g3</DependentUpon> </None> - <None Include="TestExpressionFeatures.g3"> - <Generator>MSBuild:Compile</Generator> - </None> + <None Include="TestExpressionFeatures.g3" /> </ItemGroup> <ItemGroup> <None Include="BuildOptions\ProfileTreeGrammar.g3"> <!--<GrammarOptions>-profile</GrammarOptions>--> - <Generator>MSBuild:Compile</Generator> </None> <None Include="BuildOptions\ProfileTreeGrammarHelper.cs"> <DependentUpon>ProfileTreeGrammar.g3</DependentUpon> </None> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <PropertyGroup> <!-- Folder containing AntlrBuildTask.dll --> <AntlrBuildTaskPath>$(ProjectDir)..\..\..\..\..\..\bin\Bootstrap</AntlrBuildTaskPath> <!-- Path to the ANTLR Tool itself. --> <AntlrToolPath>$(ProjectDir)..\..\..\..\..\..\bin\Bootstrap\Antlr3.exe</AntlrToolPath> </PropertyGroup> <Import Project="$(ProjectDir)..\..\..\..\..\..\bin\Bootstrap\Antlr3.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project> \ No newline at end of file
antlr/antlrcs
880bcec0c5840ce5dc20c9fe2ef6d417426a56fa
Specify Generator for Antlr3 items as MSBuild:Compile so users don't need to specify it manually
diff --git a/ANTLRCSharpDocumentation.docx b/ANTLRCSharpDocumentation.docx index e319cb9..5b3e977 100644 Binary files a/ANTLRCSharpDocumentation.docx and b/ANTLRCSharpDocumentation.docx differ diff --git a/AntlrBuildTask/Antlr3.targets b/AntlrBuildTask/Antlr3.targets index 1d75124..70b7c57 100644 --- a/AntlrBuildTask/Antlr3.targets +++ b/AntlrBuildTask/Antlr3.targets @@ -1,168 +1,169 @@ <!-- [The "BSD licence"] Copyright (c) 2011 Sam Harwell All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <BuildSystem>MSBuild</BuildSystem> <TaskVersion>3.5.0.1</TaskVersion> <TaskKeyToken>eb42632606e9261f</TaskKeyToken> <AntlrBuildTaskAssemblyName Condition="'$(AntlrBuildTaskAssemblyName)'==''">AntlrBuildTask, Version=$(TaskVersion), Culture=neutral, PublicKeyToken=$(TaskKeyToken)</AntlrBuildTaskAssemblyName> </PropertyGroup> <PropertyGroup> <LoadTimeSensitiveTargets> $(LoadTimeSensitiveTargets); AntlrCompile; </LoadTimeSensitiveTargets> <LoadTimeSensitiveProperties> $(LoadTimeSensitiveProperties); AntlrCompileDependsOn; </LoadTimeSensitiveProperties> </PropertyGroup> <PropertyGroup> <AntlrBuildTaskLocation Condition="'$(AntlrBuildTaskPath)'==''">$(MSBuildBinPath)</AntlrBuildTaskLocation> <AntlrBuildTaskLocation Condition="'$(AntlrBuildTaskPath)'!=''">$(AntlrBuildTaskPath)</AntlrBuildTaskLocation> <AntlrToolLocation Condition="'$(AntlrToolPath)'==''">$(MSBuildBinPath)\Antlr3\Antlr3.exe</AntlrToolLocation> <AntlrToolLocation Condition="'$(AntlrToolPath)'!=''">$(AntlrToolPath)</AntlrToolLocation> </PropertyGroup> <PropertyGroup> <AntlrGenCodeFileNames Condition="'$(AntlrGenCodeFileNames)'==''">$(MSBuildProjectFile).AntlrGeneratedCodeFileListAbsolute.txt</AntlrGenCodeFileNames> </PropertyGroup> <UsingTask Condition="'$(AntlrBuildTaskPath)'==''" TaskName="Antlr3.Build.Tasks.AntlrClassGenerationTask" AssemblyName="$(AntlrBuildTaskAssemblyName)" /> <UsingTask Condition="'$(AntlrBuildTaskPath)'!=''" TaskName="Antlr3.Build.Tasks.AntlrClassGenerationTask" AssemblyFile="$(AntlrBuildTaskPath)\AntlrBuildTask.dll" /> <PropertyGroup> <PrepareResourcesDependsOn> AntlrCompile; AntlrCompileAddFilesGenerated; $(PrepareResourcesDependsOn) </PrepareResourcesDependsOn> </PropertyGroup> <PropertyGroup> <AntlrCompileDependsOn> AntlrCompileReadGeneratedFileList </AntlrCompileDependsOn> </PropertyGroup> <ItemGroup Condition="'$(BuildingInsideVisualStudio)'=='true'"> <AvailableItemName Include="Antlr3" /> <AvailableItemName Include="AntlrTokens" /> <AvailableItemName Include="AntlrAbstractGrammar" /> </ItemGroup> <ItemDefinitionGroup> <Antlr3> + <Generator>MSBuild:Compile</Generator> <TargetLanguage/> <DebugGrammar>false</DebugGrammar> <ProfileGrammar>false</ProfileGrammar> </Antlr3> </ItemDefinitionGroup> <Target Name="AntlrCompileReadGeneratedFileList"> <ReadLinesFromFile File="$(IntermediateOutputPath)$(AntlrGenCodeFileNames)"> <Output TaskParameter="Lines" ItemName="AntlrOutputCodeFilesList"/> </ReadLinesFromFile> </Target> <PropertyGroup> <!-- Add grammar compilation to the CoreCompileDependsOn so that the IDE inproc compilers (particularly VB) can "see" the generated source files. --> <CoreCompileDependsOn Condition="'$(BuildingInsideVisualStudio)' == 'true' "> DesignTimeGrammarCompilation; $(CoreCompileDependsOn) </CoreCompileDependsOn> </PropertyGroup> <Target Name="DesignTimeGrammarCompilation"> <!-- Only if we are not actually performing a compile i.e. we are in design mode --> <CallTarget Condition="'$(BuildingProject)' != 'true'" Targets="AntlrCompile" /> </Target> <Target Name="AntlrCompile" DependsOnTargets="$(AntlrCompileDependsOn)" Condition="'@(Antlr3)' != ''" Inputs="@(Antlr3);@(AntlrTokens);@(AntlrAbstractGrammar)" Outputs="@(AntlrOutputCodeFilesList); $(IntermediateOutputPath)$(AntlrGenCodeFileNames);"> <ItemGroup> <AntlrGeneratedCodeFiles Remove="@(AntlrGeneratedCodeFiles)" /> </ItemGroup> <PropertyGroup> <_IntellisenseOnlyCompile>false</_IntellisenseOnlyCompile> <_IntellisenseOnlyCompile Condition="'$(BuildingProject)' != 'true'">true</_IntellisenseOnlyCompile> </PropertyGroup> <AntlrClassGenerationTask AntlrToolPath="$(AntlrToolLocation)" BuildTaskPath="$(AntlrBuildTaskLocation)" OutputPath="$(IntermediateOutputPath)" TargetLanguage="%(Antlr3.TargetLanguage)" SourceCodeFiles="@(Antlr3)" ContinueOnError="$(_IntellisenseOnlyCompile)" TokensFiles="@(AntlrTokens)" AbstractGrammarFiles="@(AntlrAbstractGrammar)" LanguageSourceExtensions="$(DefaultLanguageSourceExtension)" DebugGrammar="%(Antlr3.DebugGrammar)" ProfileGrammar="%(Antlr3.ProfileGrammar)"> <Output ItemName="AntlrGeneratedCodeFiles" TaskParameter="GeneratedCodeFiles" /> </AntlrClassGenerationTask> <WriteLinesToFile Condition="'$(_IntellisenseOnlyCompile)' != 'true'" File="$(IntermediateOutputPath)$(AntlrGenCodeFileNames)" Lines="@(AntlrGeneratedCodeFiles)" Overwrite="true"/> </Target> <Target Name="AntlrCompileAddFilesGenerated" AfterTargets="AntlrCompile" Condition="'@(Antlr3)' != ''"> <ItemGroup> <AntlrGeneratedCodeFiles Condition="'@(AntlrGeneratedCodeFiles)' == ''" Include="@(AntlrOutputCodeFilesList)" /> </ItemGroup> <ItemGroup> <FileWrites Include="@(AntlrGeneratedCodeFiles); $(IntermediateOutputPath)$(AntlrGenCodeFileNames);" /> </ItemGroup> <ItemGroup> <Compile Include="@(AntlrGeneratedCodeFiles)" /> <!-- The WinFX "GenerateTemporaryTargetAssembly" target requires generated code files be added here. --> <_GeneratedCodeFiles Include="@(AntlrGeneratedCodeFiles)" /> </ItemGroup> </Target> </Project>
antlr/antlrcs
c2db3bd1b54e2918e9df1ba115a809fcccccf23d
CSharp targets: Updated assembly info for build 3.5.0.1
diff --git a/Antlr3.Runtime.Debug/Properties/AssemblyInfo.cs b/Antlr3.Runtime.Debug/Properties/AssemblyInfo.cs index 5473727..a3f2477 100644 --- a/Antlr3.Runtime.Debug/Properties/AssemblyInfo.cs +++ b/Antlr3.Runtime.Debug/Properties/AssemblyInfo.cs @@ -1,70 +1,70 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Runtime.Debug" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Runtime.Debug" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant( true )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "9f8fa018-6766-404c-9e72-551407e1b173" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. * 3. Revision is the Perforce changelist number associated with the release. */ -[assembly: AssemblyVersion("3.5.0.0")] -[assembly: AssemblyFileVersion("3.5.0.0")] +[assembly: AssemblyVersion("3.5.0.1")] +[assembly: AssemblyFileVersion("3.5.0.1")] diff --git a/Antlr3.Runtime.JavaExtensions/Properties/AssemblyInfo.cs b/Antlr3.Runtime.JavaExtensions/Properties/AssemblyInfo.cs index 0908b03..9439e35 100644 --- a/Antlr3.Runtime.JavaExtensions/Properties/AssemblyInfo.cs +++ b/Antlr3.Runtime.JavaExtensions/Properties/AssemblyInfo.cs @@ -1,69 +1,69 @@ /* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2010 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Runtime.JavaExtensions" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Runtime.JavaExtensions" )] [assembly: AssemblyCopyright( "Copyright © Sam Harwell 2013" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant( true )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "ad48c7f7-0b1d-4b1e-9602-83425cb5699f" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. */ -[assembly: AssemblyVersion("3.5.0.0")] -[assembly: AssemblyFileVersion("3.5.0.0")] +[assembly: AssemblyVersion("3.5.0.1")] +[assembly: AssemblyFileVersion("3.5.0.1")] diff --git a/Antlr3.Runtime.Test/Properties/AssemblyInfo.cs b/Antlr3.Runtime.Test/Properties/AssemblyInfo.cs index df467a2..7437eda 100644 --- a/Antlr3.Runtime.Test/Properties/AssemblyInfo.cs +++ b/Antlr3.Runtime.Test/Properties/AssemblyInfo.cs @@ -1,70 +1,70 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Runtime.Test" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Pixel Mine, Inc." )] [assembly: AssemblyProduct( "Antlr3.Runtime.Test" )] [assembly: AssemblyCopyright("Copyright © Sam Harwell 2013")] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant( true )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "1352b15b-eded-4380-9122-acde32f7ff38" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. * 3. Revision is the Perforce changelist number associated with the release. */ -[assembly: AssemblyVersion("3.5.0.0")] -[assembly: AssemblyFileVersion("3.5.0.0")] +[assembly: AssemblyVersion("3.5.0.1")] +[assembly: AssemblyFileVersion("3.5.0.1")] diff --git a/Antlr3.Runtime/Properties/AssemblyInfo.cs b/Antlr3.Runtime/Properties/AssemblyInfo.cs index 5172174..42f80e7 100644 --- a/Antlr3.Runtime/Properties/AssemblyInfo.cs +++ b/Antlr3.Runtime/Properties/AssemblyInfo.cs @@ -1,72 +1,72 @@ /* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Runtime.InteropServices; using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "Antlr3.Runtime" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Tunnel Vision Laboratories, LLC" )] [assembly: AssemblyProduct( "Antlr3.Runtime" )] [assembly: AssemblyCopyright("Copyright © Sam Harwell 2013")] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] [assembly: CLSCompliant( true )] [assembly: AllowPartiallyTrustedCallers] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "7a0b4db7-f127-4cf5-ac2c-e294957efcd6" )] /* Version information for an assembly consists of four values in the following order: * * Major.Minor.Build.Revision * * These values are updated according to the following: * 1. Major.Minor follows the ANTLR release schedule * 2. Build is incremented each time the C# port is packaged for release (regardless * of whether it's an incremental or nightly). The value resets to zero whenever * the Major or Minor version is incremented. * 3. Revision is the Perforce changelist number associated with the release. */ -[assembly: AssemblyVersion("3.5.0.0")] -[assembly: AssemblyFileVersion("3.5.0.0")] +[assembly: AssemblyVersion("3.5.0.1")] +[assembly: AssemblyFileVersion("3.5.0.1")]
jcasts/sunshine
dd22e5cf331ae0eea539de3c960ef6e551b81436
bumped version for release
diff --git a/History.rdoc b/History.rdoc index 2b96585..c6aa222 100644 --- a/History.rdoc +++ b/History.rdoc @@ -1,389 +1,395 @@ +=== 1.2.4 / 2011-02-23 + +* Bugfixes: + + * Removed "IDLE" from the output. + === 1.2.3 / 2011-02-11 * Bugfixes: * Completely removed the Healthcheck implementation. * Removed superfluous App#upload_tasks method. * Changed Apache#bin from apachectl to apache2ctl. * Made RsyncRepo available for remote checkout only. * Lots of rdoc updates. === 1.2.2 / 2010-10-13 * Bugfixes: * Added support for ruby 1.9.2 === 1.2.1 / 2010-10-05 * Improvements: * Added customizable behaviors for sigint and failures during deploys. * Added Sunshine irb shell to work directly with deploying apps. * Added ability to launch a pseudo terminal from a RemoteShell. * Added exit code to CmdError. * Added exclude paths for checkout by copy. * Bugfixes: * Fixed custom scripts. * Fixed deploy env defaults. * Removed Shell#update_timeout as it was unnecessary. * RemoteShell rsync recurses by default. * Fixed start and stop script permissions when calling sunshine commands. === 1.2.0 / 2010-09-08 * Improvements: * Added better support for custom env/start/stop/restart scripts. * Added scripts sunshine command to call custom scripts remotely. * Deploy env defaults to ENV 'DEPLOY_ENV', 'env', 'RACK_ENV', or 'RAILS_ENV'. * Bugfixes: * ServerApp#run_geminstaller no longer defaults to using sudo. * Added better extensible package manager checking to ServerApp. * Fixed Cronjob functionality and added array support. === 1.1.2 / 2010-04-15 * Improvements: * Added array support to App#find. * Added auto registration of Dependency subclasses for scalability. * Added call to App#start in App#deploy. * Bugfixes: * Fixed bug where env wouldn't be applied correctly in control scripts. * Changed App#with_filter to actually change the App#server_apps attribute. * Shell#env_cmd now returns a flattened array. * Added actual check of running process to Daemon#status_cmd. === 1.1.1 / 2010-04-05 * Improvements: * Added Repo subclass registration for greater expandability. * Added support for checking out codebases locally then rsync-ing them. * Bugfixes: * Fixed RemoteShell login script lingering after disconnect. === 1.1.0 / 2010-04-02 * Improvements: * Support for server clustering with the ServerCluster class. * Added Daemon#status method. * Added the -R option for loading external libraries and gems. * Added support for Thin and MongrelRails. * Added Server support for max connections configuration. * Bugfixes: * Daemons no longer create control scripts if they aren't used. * Fixed Rsync repo to auto append "/" to urls for correct rsyncing. === 1.0.3 / 2010-03-26 * Improvements: * Added App#call method. * Added App#with_session and Shell#with_session to reduce login prompts. * Bugfixes: * Geminstaller now always installs with sudo. * Fixed permissions issues with running servers on ports < 1024. * Fixed healthcheck middleware. === 1.0.2 / 2010-03-25 * Bugfixes: * Fixed apache passenger dependency to run as sudo. * Fixed a bug in Repo::detect === 1.0.1 / 2010-03-25 * Bugfixes: * Added json dependency === 1.0.0 / 2010-03-25 * Improvements: * Added auto_dependencies config to turn on/off auto installing things. * Added healthcheck middleware support. * Added support for Apache2 and its passenger implementation. * Removed all Atti-specific code for public release. * Bugfixes: * Fixed Nginx passenger implementation. === 0.0.6 / 2010-03-19 * Major: * Removed DeployServerDispatcher. Dispatching now happens at the App level. * Moved Settler into Sunshine and renamed it to DependencyLib. * Improvements: * Added INT signal handling to exit deploys and close connections gracefully. * Added dependency installation methods apt_install, gem_install, tpkg_install and yum_install to App and ServerApp. * Extended functionality of ServerApp#upload_tasks. * ServerApp now support being instatiated with an App instance (for coordinated deploys) or just with an app name (for post-deploy usage). * Added a Sunshine rakefile template for task-based deploys. Available through: sunshine --rakefile [COPY_TO] * App#name gets auto-assigned by repo info if not provided. * Sunshine::web_directory used to determine App#deploy_path when missing. * Repo#detect now returns a Repo object instead of an array. * Added start/stop/restart/status methods to DeployServerApp. * ServerApp instances with unspecified roles get all roles by default. * App config files now use erb parsing. Any key/value passed the App constructor as a hash should be passed to the erb binding along with the deploy_env. * Added support to bundler for defining multiple dependencies with the same name, and different package managers. * Bugfixes: * Added setup checking to Daemon to only run setup when needed. * Moved healthcheck from App to ServerApp and improved the api. * Renamed DeployServerApp to ServerApp. * Renamed App#deploy_path and App#deploys_dir to App#root_path and App#deploys_path. * Renamed the 'deploy' command to 'run' to more accurately express it's use. * RsyncRepo#do_checkout fixed to match standard Repo#do_checkout methods. * Sunshine::DATA and Sunshine::PATH are now set when running standalone ruby deploy files. === 0.0.5 / 2010-02-26 * Sunshine::App: * Use of DeployServerDispatcher threading * Fixed control script creation to be deploy_server specific (takes roles into account) * Added AttiApp class for ATTi app deployment. * Constuctor supports :deploy_name option for nameable deploys. Defaults to the timestamp. * Auto-detects if the script's directory is a checked out repo and uses it if no repo information was given. * Support for running sass. * Sunshine::DeployServerDispatcher: * Added threading support * Sunshine::Repo: * Added support for detecting a repo type based on a path: Repo.detect [path [, console_or_deploy_server]] #=> [:git, "git://url/of/git/repo", {:tree => "master", ...}] * Moved info instance methods to the class * Support for git-svn: SvnRepo.git_svn? path * Changed the checkout_to method signature * Sunshine::Server: * Added support for ar_sendmail server. === 0.0.4 / 2010-02-12 * Added sudo functionality: * Support for :sudo option on Sunshine::App, Sunshine::Server, and Sunshine::DeployServer constructors, and attr_accessor :sudo * Settler Dependency classes support a default sudo value: Sunshine::Dependencies::Gem.sudo = true # use sudo Sunshine::Dependencies::Gem.sudo = "usr" # use sudo -u usr Sunshine::Dependencies::Gem.sudo = false # ensure sudo is off Sunshine::Dependencies::Gem.sudo = nil # use :call obj precedence * App supports passing a (yml) file object to the constructor. Useful for passing file DATA if desired: app = Sunshine::App.new Sunshine::DATA app.deploy!{|app| Sunshine::Rainbows.new(app).restart } __END__ #yaml for app goes here... * App class changes: * Changed the format of the App#checkout_path directory * Logrotate setup now has to be called explicitely * Commands functionality expanded: * Support for --sudo and --sudo=user on all Sunshine commands * Added --format option for control commands. Supports txt, yml, json. * Control scripts generated on the remote server now keep deploy-time shell_env variables: * Run commands with the --no-env option to run without deploy shell_env variables. * Run any script with the app's env variables using: /path/to/app/env some_command /path/to/app/env EXTRA_VAR=some_value some_command Supports all options the env command supports. * Dependency handling now supports apt. * DeployServers now support passing custom flags for ssh and rsync: deploy_server = DeployServer.new "svr.com", :rsync_flags => [...] deploy_server.call "some_command", :sudo => "user", :flags => '-C' deploy_server.upload "from", "to", :sudo => "user", :flags => ['--chmod=ugo=rwX', '-b'] deploy_server.download "from", "to", :flags => '--ignore-existing' * Repo implementation has significantly changed: * Added support for git repo. * Info about a repo is now retrieved with Repo#get_repo_info: repo.get_repo_info deploy_server, checkout_path * Repo constructor supports options hash with :flags option. === 0.0.3 / 2010-01-29 * Many small bugfixes * Tests, tests, and more tests * Changed DeployServer api * DeployServer#run is not longer supported, use DeployServer#call * Constructor supports a spaced delimited list for roles: DeployServer.new "myhost.com", :roles => "web db other" * Changed how deploy server yaml is parsed. Should parse to be valid on: DeployServer.new *parsed_yaml Example Given: :deploy_servers : - server1.com - - server2.com - - server3.com - :roles : web db other :ssh_flags : '-o ControlMaster=auto' === 0.0.2 / 2010-01-15 * Added Control Commands * add, deploy, list, restart, rm, start, stop * Application support * Changed VERSION file to info and its format to yaml * Deployed apps now have a start, stop and restart script * Added Crontab and log rotation support * Functional changes * Ditched net/ssh and net/scp for ssh and rsync through Open4 * Fixed and updated dependencies to use Yum * Support for sunshine user configuration in ~/.sunshine * Rake tasks * Support to run the app's rake tasks * Built in default ATTi rake tasks === 0.0.1 / 2009-11-18 * 1 major enhancement * First release! diff --git a/lib/sunshine.rb b/lib/sunshine.rb index ffee733..3d496d7 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,451 +1,451 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' require 'irb' require 'yaml' # Turn off EOF tracking to be able to prompt on deploy exceptions. HighLine.track_eof = false ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. - VERSION = '1.2.3' + VERSION = '1.2.4' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { 'auto_dependencies' => true, 'deploy_env' => :development, 'exception_behavior' => :revert, 'exclude_paths' => [], 'interactive' => true, 'level' => 'info', 'max_deploy_versions' => 5, 'remote_checkouts' => false, 'threads_enabled' => true, 'timeout' => 300, 'sigint_behavior' => :revert, 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end ## # Defines what to do when deploy raises an exception. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.exception_behavior @config['exception_behavior'] end ## # Array of paths or globs that should be excluded from the checkout. # Does not work with remote_checkouts enabled. def self.exclude_paths @config['exclude_paths'] end ## # Should sunshine ever ask for user input? True by default. # Overridden in the config or with the -a option. def self.interactive? @config['interactive'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end ## # Defines what to do when sigint is sent during deploys. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.sigint_behavior @config['sigint_behavior'] end ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end ## # Check if App objects should use threads when iterating over ServerApps. # Defaults to true, overridden with the 'threads_enabled' config. def self.use_threads? @config['threads_enabled'] end ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config create_default_config! load_config_file USER_CONFIG_FILE @config['deploy_env'] = ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] || @config['deploy_env'] @config end def self.create_default_config! unless File.file? USER_CONFIG_FILE File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" msg << DEFAULT_CONFIG.to_yaml self.exit 1, msg end end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset TrapStack.trap_signal :INT do |msg| $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" logger.info :INT, msg end TrapStack.add_trap "Disconnecting all remote shells." do RemoteShell.disconnect_all end require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' require 'sunshine/trap_stack' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies'
jcasts/sunshine
60c20e4624e3d164fb95b9fe8d5adb85c5fd7451
removed "IDLE" output
diff --git a/lib/sunshine/shell.rb b/lib/sunshine/shell.rb index 29bd759..b5d0aea 100644 --- a/lib/sunshine/shell.rb +++ b/lib/sunshine/shell.rb @@ -1,462 +1,461 @@ module Sunshine ## # The Shell class handles local input, output and execution to the shell. class Shell include Open4 LOCAL_USER = `whoami`.chomp LOCAL_HOST = `hostname`.chomp class << self # The message to match in stderr to determine logging in has failed. # Defaults to: # /^Sorry, try again./ attr_accessor :sudo_failed_matcher # The message to match in stderr to determine a password is required. # Defaults to: # /^Password:/ attr_accessor :sudo_prompt_matcher end self.sudo_failed_matcher = /^Sorry, try again./ self.sudo_prompt_matcher = /^Password:/ attr_reader :user, :host, :password, :input, :output, :mutex, :pid attr_accessor :env, :sudo, :timeout def initialize output = $stdout, options={} @output = output $stdin.sync @input = HighLine.new $stdin @user = LOCAL_USER @host = LOCAL_HOST @sudo = options[:sudo] @env = options[:env] || {} @password = options[:password] @timeout = options[:timeout] || Sunshine.timeout @idle_time = options[:idle_after] || 1 @mutex = @pid = nil end ## # Checks for equality def == shell @host == shell.host && @user == shell.user rescue false end ## # Prompt the user for input. def ask(*args, &block) sync{ @input.ask(*args, &block) } end ## # Prompt the user to agree. def agree(*args, &block) sync{ @input.agree(*args, &block) } end ## # Execute a command on the local system and return the output. def call cmd, options={}, &block Sunshine.logger.info @host, "Running: #{cmd}" do execute sudo_cmd(cmd, options), &block end end ## # Prompt the user to make a choice. def choose &block sync{ @input.choose(&block) } end ## # Close the output IO. (Required by the Logger class) def close @output.close end ## # Returns true. Compatibility method with RemoteShell. def connect true end ## # Returns true. Compatibility method with RemoteShell. def connected? true end ## # Returns true. Compatibility method with RemoteShell. def disconnect true end ## # Copies a file. Compatibility method with RemoteShell. def download from_path, to_path, options={}, &block Sunshine.logger.info @host, "Copying #{from_path} -> #{to_path}" do FileUtils.cp_r from_path, to_path end end alias upload download ## # Expands the path. Compatibility method with RemoteShell. def expand_path path File.expand_path path end ## # Checks if file exists. Compatibility method with RemoteShell. def file? filepath File.file? filepath end ## # Checks if timeout occurred. def timed_out? start_time=@cmd_activity, max_time=@timeout return unless max_time Time.now.to_f - start_time.to_f > max_time end ## # Update the time of the last command activity def update_activity @cmd_activity = Time.now end ## # Checks if shell is still receiving data. def idle? start_time=@cmd_activity, max_time=@idle_time timed_out? start_time, max_time end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " pid = fork do exec sudo_cmd(env_cmd(cmd)).to_a.join(" ") end Process.waitpid pid end end ## # Write a file. Compatibility method with RemoteShell. def make_file filepath, content, options={} File.open(filepath, "w+"){|f| f.write(content)} end ## # Get the name of the OS def os_name @os_name ||= call("uname -s").strip.downcase end ## # Prompt the user for a password def prompt_for_password host_info = [@user, @host].compact.join("@") @password = ask("#{host_info} Password:") do |q| q.echo = false end end ## # Build an env command if an env_hash is passed def env_cmd cmd, env_hash=@env if env_hash && !env_hash.empty? env_vars = env_hash.map{|e| e.join("=")} cmd = ["env", env_vars, cmd].flatten end cmd end ## # Wrap command in quotes and escape as needed. def quote_cmd cmd cmd = [*cmd].join(" ") "'#{cmd.gsub(/'/){|s| "'\\''"}}'" end ## # Build an sh -c command def sh_cmd cmd ["sh", "-c", quote_cmd(cmd)] end ## # Build a command with sudo. # If sudo_val is nil, it is considered to mean "pass-through" # and the default shell sudo will be used. # If sudo_val is false, the cmd will be returned unchanged. # If sudo_val is true, the returned command will be prefaced # with sudo -H # If sudo_val is a String, the command will be prefaced # with sudo -H -u string_value def sudo_cmd cmd, sudo_val=nil sudo_val = sudo_val[:sudo] if Hash === sudo_val sudo_val = @sudo if sudo_val.nil? case sudo_val when true ["sudo", "-H", cmd].flatten when String ["sudo", "-H", "-u", sudo_val, cmd].flatten else cmd end end ## # Force symlinking a directory. def symlink target, symlink_name call "ln -sfT #{target} #{symlink_name}" rescue false end ## # Synchronize a block with the current mutex if it exists. def sync if @mutex @mutex.synchronize{ yield } else yield end end ## # Returns true if command was run successfully, otherwise returns false. def system cmd, options=nil call(cmd, options) && true rescue false end ## # Execute a block while setting the shell's mutex. # Sets the mutex to its original value on exit. # Executing commands with a mutex is used for user prompts. def with_mutex mutex old_mutex, @mutex = @mutex, mutex yield @mutex = old_mutex end ## # Runs the passed block within a connection session. # If the shell is already connected, connecting and disconnecting # is ignored; otherwise, the session method will ensure that # the shell's connection gets closed after the block has been # executed. def with_session prev_connection = connected? connect unless prev_connection yield disconnect unless prev_connection end ## # Write string to stdout (by default). def write str @output.write str end alias << write ## # Execute a command with open4 and loop until the process exits. # The cmd argument may be a string or an array. If a block is passed, # it will be called when data is received and passed the stream type # and stream string value: # shell.execute "test -s 'blah' && echo 'true'" do |stream, str| # stream #=> :stdout # string #=> 'true' # end # # The method returns the output from the stdout stream by default, and # raises a CmdError if the exit status of the command is not zero. def execute cmd cmd = [cmd] unless Array === cmd @pid, inn, out, err = popen4(*cmd) inn.sync = true log_methods = {out => :debug, err => :error} result, status = process_streams(@pid, out, err) do |stream, data| stream_name = :out if stream == out stream_name = :err if stream == err stream_name = :inn if stream == inn Sunshine.logger.send log_methods[stream], "#{@host}:#{stream_name}", data # User blocks should run with sync threads to avoid badness. sync do yield(stream_name, data, inn) if block_given? end if password_required?(stream_name, data) then kill_process(@pid) unless Sunshine.interactive? send_password_to_stream(inn, data) end end raise_command_failed(status, cmd) unless status.success? result[out].join.chomp ensure inn.close rescue nil out.close rescue nil err.close rescue nil @pid = nil end private def raise_command_failed(status, cmd) err = CmdError.new status.exitstatus, [*cmd].join(" ") raise err end def password_required? stream_name, data stream_name == :err && data =~ Shell.sudo_prompt_matcher end def send_password_to_stream inn, data prompt_for_password if data =~ Shell.sudo_failed_matcher inn.puts @password || prompt_for_password end def kill_process pid, kill_type="KILL" begin Process.kill kill_type, pid Process.wait rescue end end def process_streams pid, *streams result = Hash.new{|h,k| h[k] = []} update_activity # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 - puts "#{@host} IDLE..." if idle? raise TimeoutError if timed_out? next if selected.nil? or selected.empty? selected.each do |stream| update_activity if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) yield(stream, data) result[stream] << data end end return result, status end end end
jcasts/sunshine
3ba784e32169f63a001de1147acf5e1d2f90f646
made readme and history into rdocs
diff --git a/History.txt b/History.rdoc similarity index 100% rename from History.txt rename to History.rdoc diff --git a/Manifest.txt b/Manifest.txt index 00adc0d..8897ed4 100644 --- a/Manifest.txt +++ b/Manifest.txt @@ -1,79 +1,79 @@ -History.txt +History.rdoc Manifest.txt -README.txt +README.rdoc Rakefile bin/sunshine examples/deploy_tasks.rake examples/standalone_deploy.rb examples/sunshine_deploy.rb lib/commands/add.rb lib/commands/default.rb lib/commands/list.rb lib/commands/restart.rb lib/commands/rm.rb lib/commands/run.rb lib/commands/script.rb lib/commands/start.rb lib/commands/stop.rb lib/sunshine.rb lib/sunshine/app.rb lib/sunshine/binder.rb lib/sunshine/crontab.rb lib/sunshine/daemon.rb lib/sunshine/daemons/apache.rb lib/sunshine/daemons/ar_sendmail.rb lib/sunshine/daemons/delayed_job.rb lib/sunshine/daemons/mongrel_rails.rb lib/sunshine/daemons/nginx.rb lib/sunshine/daemons/rainbows.rb lib/sunshine/daemons/server.rb lib/sunshine/daemons/server_cluster.rb lib/sunshine/daemons/thin.rb lib/sunshine/daemons/unicorn.rb lib/sunshine/dependencies.rb lib/sunshine/dependency_lib.rb lib/sunshine/exceptions.rb lib/sunshine/output.rb lib/sunshine/package_managers/apt.rb lib/sunshine/package_managers/dependency.rb lib/sunshine/package_managers/gem.rb lib/sunshine/package_managers/yum.rb lib/sunshine/remote_shell.rb lib/sunshine/repo.rb lib/sunshine/repos/git_repo.rb lib/sunshine/repos/rsync_repo.rb lib/sunshine/repos/svn_repo.rb lib/sunshine/server_app.rb lib/sunshine/shell.rb lib/sunshine/trap_stack.rb templates/apache/apache.conf.erb templates/mongrel_rails/mongrel_rails.conf.erb templates/nginx/nginx.conf.erb templates/nginx/nginx_optimize.conf templates/nginx/nginx_proxy.conf templates/rainbows/rainbows.conf.erb templates/sunshine/sunshine.rake templates/thin/thin.conf.erb templates/unicorn/unicorn.conf.erb test/fixtures/app_configs/test_app.yml test/fixtures/sunshine_test/test_upload test/helper_methods.rb test/mocks/mock_object.rb test/mocks/mock_open4.rb test/test_helper.rb test/unit/test_app.rb test/unit/test_binder.rb test/unit/test_crontab.rb test/unit/test_daemon.rb test/unit/test_git_repo.rb test/unit/test_nginx.rb test/unit/test_rainbows.rb test/unit/test_remote_shell.rb test/unit/test_repo.rb test/unit/test_server.rb test/unit/test_server_app.rb test/unit/test_server_cluster.rb test/unit/test_shell.rb test/unit/test_sunshine.rb test/unit/test_svn_repo.rb test/unit/test_unicorn.rb diff --git a/README.txt b/README.rdoc similarity index 100% rename from README.txt rename to README.rdoc diff --git a/Rakefile b/Rakefile index 23c6128..30972fa 100644 --- a/Rakefile +++ b/Rakefile @@ -1,47 +1,51 @@ # -*- ruby -*- require 'rubygems' require 'hoe' require 'rake' require 'rake/testtask' task :manifest do manifest_file = "Manifest.txt" gem_files = record_files do |f| next if f =~ /^(tmp|pkg|deploy_scripts)/ puts(f) true end gem_files.push(manifest_file) gem_files = gem_files.uniq.sort.join("\n") File.open(manifest_file, "w+") do |file| file.write gem_files end end def record_files(path="*", file_arr=[], &block) Dir[path].each do |child_path| if File.file?(child_path) next if block_given? && !yield(child_path) file_arr << child_path end record_files(child_path+"/*", file_arr, &block) if File.directory?(child_path) end return file_arr end Hoe.plugin :isolate Hoe.spec 'sunshine' do |p| developer('Jeremie Castagna', '[email protected]') + self.readme_file = "README.rdoc" + self.history_file = "History.rdoc" + self.extra_rdoc_files = FileList['*.rdoc'] + self.extra_deps << ['open4', '~> 1.0.1'] self.extra_deps << ['rainbow', '~> 1.0.4'] self.extra_deps << ['highline', '~> 1.5.1'] self.extra_deps << ['json', '~> 1.2.0'] end # vim: syntax=Ruby
jcasts/sunshine
6eed761b5a074091c561672030c9209d2b5d419b
removed extra timed_out method
diff --git a/lib/sunshine/shell.rb b/lib/sunshine/shell.rb index 5175986..29bd759 100644 --- a/lib/sunshine/shell.rb +++ b/lib/sunshine/shell.rb @@ -1,471 +1,462 @@ module Sunshine ## # The Shell class handles local input, output and execution to the shell. class Shell include Open4 LOCAL_USER = `whoami`.chomp LOCAL_HOST = `hostname`.chomp class << self # The message to match in stderr to determine logging in has failed. # Defaults to: # /^Sorry, try again./ attr_accessor :sudo_failed_matcher # The message to match in stderr to determine a password is required. # Defaults to: # /^Password:/ attr_accessor :sudo_prompt_matcher end self.sudo_failed_matcher = /^Sorry, try again./ self.sudo_prompt_matcher = /^Password:/ attr_reader :user, :host, :password, :input, :output, :mutex, :pid attr_accessor :env, :sudo, :timeout def initialize output = $stdout, options={} @output = output $stdin.sync @input = HighLine.new $stdin @user = LOCAL_USER @host = LOCAL_HOST @sudo = options[:sudo] @env = options[:env] || {} @password = options[:password] @timeout = options[:timeout] || Sunshine.timeout @idle_time = options[:idle_after] || 1 @mutex = @pid = nil end ## # Checks for equality def == shell @host == shell.host && @user == shell.user rescue false end ## # Prompt the user for input. def ask(*args, &block) sync{ @input.ask(*args, &block) } end ## # Prompt the user to agree. def agree(*args, &block) sync{ @input.agree(*args, &block) } end ## # Execute a command on the local system and return the output. def call cmd, options={}, &block Sunshine.logger.info @host, "Running: #{cmd}" do execute sudo_cmd(cmd, options), &block end end ## # Prompt the user to make a choice. def choose &block sync{ @input.choose(&block) } end ## # Close the output IO. (Required by the Logger class) def close @output.close end ## # Returns true. Compatibility method with RemoteShell. def connect true end ## # Returns true. Compatibility method with RemoteShell. def connected? true end ## # Returns true. Compatibility method with RemoteShell. def disconnect true end ## # Copies a file. Compatibility method with RemoteShell. def download from_path, to_path, options={}, &block Sunshine.logger.info @host, "Copying #{from_path} -> #{to_path}" do FileUtils.cp_r from_path, to_path end end alias upload download ## # Expands the path. Compatibility method with RemoteShell. def expand_path path File.expand_path path end ## # Checks if file exists. Compatibility method with RemoteShell. def file? filepath File.file? filepath end ## # Checks if timeout occurred. def timed_out? start_time=@cmd_activity, max_time=@timeout return unless max_time Time.now.to_f - start_time.to_f > max_time end ## # Update the time of the last command activity def update_activity @cmd_activity = Time.now end ## # Checks if shell is still receiving data. def idle? start_time=@cmd_activity, max_time=@idle_time timed_out? start_time, max_time end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " pid = fork do exec sudo_cmd(env_cmd(cmd)).to_a.join(" ") end Process.waitpid pid end end ## # Write a file. Compatibility method with RemoteShell. def make_file filepath, content, options={} File.open(filepath, "w+"){|f| f.write(content)} end ## # Get the name of the OS def os_name @os_name ||= call("uname -s").strip.downcase end ## # Prompt the user for a password def prompt_for_password host_info = [@user, @host].compact.join("@") @password = ask("#{host_info} Password:") do |q| q.echo = false end end ## # Build an env command if an env_hash is passed def env_cmd cmd, env_hash=@env if env_hash && !env_hash.empty? env_vars = env_hash.map{|e| e.join("=")} cmd = ["env", env_vars, cmd].flatten end cmd end ## # Wrap command in quotes and escape as needed. def quote_cmd cmd cmd = [*cmd].join(" ") "'#{cmd.gsub(/'/){|s| "'\\''"}}'" end ## # Build an sh -c command def sh_cmd cmd ["sh", "-c", quote_cmd(cmd)] end ## # Build a command with sudo. # If sudo_val is nil, it is considered to mean "pass-through" # and the default shell sudo will be used. # If sudo_val is false, the cmd will be returned unchanged. # If sudo_val is true, the returned command will be prefaced # with sudo -H # If sudo_val is a String, the command will be prefaced # with sudo -H -u string_value def sudo_cmd cmd, sudo_val=nil sudo_val = sudo_val[:sudo] if Hash === sudo_val sudo_val = @sudo if sudo_val.nil? case sudo_val when true ["sudo", "-H", cmd].flatten when String ["sudo", "-H", "-u", sudo_val, cmd].flatten else cmd end end ## # Force symlinking a directory. def symlink target, symlink_name call "ln -sfT #{target} #{symlink_name}" rescue false end ## # Synchronize a block with the current mutex if it exists. def sync if @mutex @mutex.synchronize{ yield } else yield end end ## # Returns true if command was run successfully, otherwise returns false. def system cmd, options=nil call(cmd, options) && true rescue false end - ## - # Checks if timeout occurred. - - def timed_out? start_time, max_time=@timeout - return unless max_time - Time.now.to_i - start_time.to_i > max_time - end - - ## # Execute a block while setting the shell's mutex. # Sets the mutex to its original value on exit. # Executing commands with a mutex is used for user prompts. def with_mutex mutex old_mutex, @mutex = @mutex, mutex yield @mutex = old_mutex end ## # Runs the passed block within a connection session. # If the shell is already connected, connecting and disconnecting # is ignored; otherwise, the session method will ensure that # the shell's connection gets closed after the block has been # executed. def with_session prev_connection = connected? connect unless prev_connection yield disconnect unless prev_connection end ## # Write string to stdout (by default). def write str @output.write str end alias << write ## # Execute a command with open4 and loop until the process exits. # The cmd argument may be a string or an array. If a block is passed, # it will be called when data is received and passed the stream type # and stream string value: # shell.execute "test -s 'blah' && echo 'true'" do |stream, str| # stream #=> :stdout # string #=> 'true' # end # # The method returns the output from the stdout stream by default, and # raises a CmdError if the exit status of the command is not zero. def execute cmd cmd = [cmd] unless Array === cmd @pid, inn, out, err = popen4(*cmd) inn.sync = true log_methods = {out => :debug, err => :error} result, status = process_streams(@pid, out, err) do |stream, data| stream_name = :out if stream == out stream_name = :err if stream == err stream_name = :inn if stream == inn Sunshine.logger.send log_methods[stream], "#{@host}:#{stream_name}", data # User blocks should run with sync threads to avoid badness. sync do yield(stream_name, data, inn) if block_given? end if password_required?(stream_name, data) then kill_process(@pid) unless Sunshine.interactive? send_password_to_stream(inn, data) end end raise_command_failed(status, cmd) unless status.success? result[out].join.chomp ensure inn.close rescue nil out.close rescue nil err.close rescue nil @pid = nil end private def raise_command_failed(status, cmd) err = CmdError.new status.exitstatus, [*cmd].join(" ") raise err end def password_required? stream_name, data stream_name == :err && data =~ Shell.sudo_prompt_matcher end def send_password_to_stream inn, data prompt_for_password if data =~ Shell.sudo_failed_matcher inn.puts @password || prompt_for_password end def kill_process pid, kill_type="KILL" begin Process.kill kill_type, pid Process.wait rescue end end def process_streams pid, *streams result = Hash.new{|h,k| h[k] = []} update_activity # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 puts "#{@host} IDLE..." if idle? raise TimeoutError if timed_out? next if selected.nil? or selected.empty? selected.each do |stream| update_activity if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) yield(stream, data) result[stream] << data end end return result, status end end end
jcasts/sunshine
d7e4d2a414328b95285b444aab8df210eac5836a
shell back to using update_activity
diff --git a/lib/sunshine/shell.rb b/lib/sunshine/shell.rb index 1dd5765..5175986 100644 --- a/lib/sunshine/shell.rb +++ b/lib/sunshine/shell.rb @@ -1,470 +1,471 @@ module Sunshine ## # The Shell class handles local input, output and execution to the shell. class Shell include Open4 LOCAL_USER = `whoami`.chomp LOCAL_HOST = `hostname`.chomp class << self # The message to match in stderr to determine logging in has failed. # Defaults to: # /^Sorry, try again./ attr_accessor :sudo_failed_matcher # The message to match in stderr to determine a password is required. # Defaults to: # /^Password:/ attr_accessor :sudo_prompt_matcher end self.sudo_failed_matcher = /^Sorry, try again./ self.sudo_prompt_matcher = /^Password:/ attr_reader :user, :host, :password, :input, :output, :mutex, :pid attr_accessor :env, :sudo, :timeout def initialize output = $stdout, options={} @output = output $stdin.sync @input = HighLine.new $stdin @user = LOCAL_USER @host = LOCAL_HOST @sudo = options[:sudo] @env = options[:env] || {} @password = options[:password] @timeout = options[:timeout] || Sunshine.timeout @idle_time = options[:idle_after] || 1 @mutex = @pid = nil end ## # Checks for equality def == shell @host == shell.host && @user == shell.user rescue false end ## # Prompt the user for input. def ask(*args, &block) sync{ @input.ask(*args, &block) } end ## # Prompt the user to agree. def agree(*args, &block) sync{ @input.agree(*args, &block) } end ## # Execute a command on the local system and return the output. def call cmd, options={}, &block Sunshine.logger.info @host, "Running: #{cmd}" do execute sudo_cmd(cmd, options), &block end end ## # Prompt the user to make a choice. def choose &block sync{ @input.choose(&block) } end ## # Close the output IO. (Required by the Logger class) def close @output.close end ## # Returns true. Compatibility method with RemoteShell. def connect true end ## # Returns true. Compatibility method with RemoteShell. def connected? true end ## # Returns true. Compatibility method with RemoteShell. def disconnect true end ## # Copies a file. Compatibility method with RemoteShell. def download from_path, to_path, options={}, &block Sunshine.logger.info @host, "Copying #{from_path} -> #{to_path}" do FileUtils.cp_r from_path, to_path end end alias upload download ## # Expands the path. Compatibility method with RemoteShell. def expand_path path File.expand_path path end ## # Checks if file exists. Compatibility method with RemoteShell. def file? filepath File.file? filepath end ## # Checks if timeout occurred. def timed_out? start_time=@cmd_activity, max_time=@timeout return unless max_time Time.now.to_f - start_time.to_f > max_time end ## # Update the time of the last command activity - def update_timeout + def update_activity @cmd_activity = Time.now end ## # Checks if shell is still receiving data. def idle? start_time=@cmd_activity, max_time=@idle_time timed_out? start_time, max_time end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " pid = fork do exec sudo_cmd(env_cmd(cmd)).to_a.join(" ") end Process.waitpid pid end end ## # Write a file. Compatibility method with RemoteShell. def make_file filepath, content, options={} File.open(filepath, "w+"){|f| f.write(content)} end ## # Get the name of the OS def os_name @os_name ||= call("uname -s").strip.downcase end ## # Prompt the user for a password def prompt_for_password host_info = [@user, @host].compact.join("@") @password = ask("#{host_info} Password:") do |q| q.echo = false end end ## # Build an env command if an env_hash is passed def env_cmd cmd, env_hash=@env if env_hash && !env_hash.empty? env_vars = env_hash.map{|e| e.join("=")} cmd = ["env", env_vars, cmd].flatten end cmd end ## # Wrap command in quotes and escape as needed. def quote_cmd cmd cmd = [*cmd].join(" ") "'#{cmd.gsub(/'/){|s| "'\\''"}}'" end ## # Build an sh -c command def sh_cmd cmd ["sh", "-c", quote_cmd(cmd)] end ## # Build a command with sudo. # If sudo_val is nil, it is considered to mean "pass-through" # and the default shell sudo will be used. # If sudo_val is false, the cmd will be returned unchanged. # If sudo_val is true, the returned command will be prefaced # with sudo -H # If sudo_val is a String, the command will be prefaced # with sudo -H -u string_value def sudo_cmd cmd, sudo_val=nil sudo_val = sudo_val[:sudo] if Hash === sudo_val sudo_val = @sudo if sudo_val.nil? case sudo_val when true ["sudo", "-H", cmd].flatten when String ["sudo", "-H", "-u", sudo_val, cmd].flatten else cmd end end ## # Force symlinking a directory. def symlink target, symlink_name call "ln -sfT #{target} #{symlink_name}" rescue false end ## # Synchronize a block with the current mutex if it exists. def sync if @mutex @mutex.synchronize{ yield } else yield end end ## # Returns true if command was run successfully, otherwise returns false. def system cmd, options=nil call(cmd, options) && true rescue false end ## # Checks if timeout occurred. def timed_out? start_time, max_time=@timeout return unless max_time Time.now.to_i - start_time.to_i > max_time end ## # Execute a block while setting the shell's mutex. # Sets the mutex to its original value on exit. # Executing commands with a mutex is used for user prompts. def with_mutex mutex old_mutex, @mutex = @mutex, mutex yield @mutex = old_mutex end ## # Runs the passed block within a connection session. # If the shell is already connected, connecting and disconnecting # is ignored; otherwise, the session method will ensure that # the shell's connection gets closed after the block has been # executed. def with_session prev_connection = connected? connect unless prev_connection yield disconnect unless prev_connection end ## # Write string to stdout (by default). def write str @output.write str end alias << write ## # Execute a command with open4 and loop until the process exits. # The cmd argument may be a string or an array. If a block is passed, # it will be called when data is received and passed the stream type # and stream string value: # shell.execute "test -s 'blah' && echo 'true'" do |stream, str| # stream #=> :stdout # string #=> 'true' # end # # The method returns the output from the stdout stream by default, and # raises a CmdError if the exit status of the command is not zero. def execute cmd cmd = [cmd] unless Array === cmd @pid, inn, out, err = popen4(*cmd) inn.sync = true log_methods = {out => :debug, err => :error} result, status = process_streams(@pid, out, err) do |stream, data| stream_name = :out if stream == out stream_name = :err if stream == err stream_name = :inn if stream == inn Sunshine.logger.send log_methods[stream], "#{@host}:#{stream_name}", data # User blocks should run with sync threads to avoid badness. sync do yield(stream_name, data, inn) if block_given? end if password_required?(stream_name, data) then kill_process(@pid) unless Sunshine.interactive? send_password_to_stream(inn, data) end end raise_command_failed(status, cmd) unless status.success? result[out].join.chomp ensure inn.close rescue nil out.close rescue nil err.close rescue nil @pid = nil end private def raise_command_failed(status, cmd) err = CmdError.new status.exitstatus, [*cmd].join(" ") raise err end def password_required? stream_name, data stream_name == :err && data =~ Shell.sudo_prompt_matcher end def send_password_to_stream inn, data prompt_for_password if data =~ Shell.sudo_failed_matcher inn.puts @password || prompt_for_password end def kill_process pid, kill_type="KILL" begin Process.kill kill_type, pid Process.wait rescue end end def process_streams pid, *streams result = Hash.new{|h,k| h[k] = []} - start_time = Time.now + update_activity # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 - raise TimeoutError if timed_out? start_time + puts "#{@host} IDLE..." if idle? + raise TimeoutError if timed_out? next if selected.nil? or selected.empty? selected.each do |stream| - start_time = Time.now + update_activity if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) yield(stream, data) result[stream] << data end end return result, status end end end
jcasts/sunshine
9f3e75d716a30099c5dd8c965626156574ae927f
made shell's current pid available as an instance variable, added check for idleness
diff --git a/lib/sunshine/remote_shell.rb b/lib/sunshine/remote_shell.rb index b5415a8..808165a 100644 --- a/lib/sunshine/remote_shell.rb +++ b/lib/sunshine/remote_shell.rb @@ -1,272 +1,270 @@ module Sunshine ## # Keeps an SSH connection open to a server the app will be deployed to. # Deploy servers use the ssh command and support any ssh feature. # By default, deploy servers use the ControlMaster feature to share # socket connections, with the ControlPath = ~/.ssh/sunshine-%r%h:%p # # Setting session-persistant environment variables is supported by # accessing the @env attribute. class RemoteShell < Shell ## # The loop to keep the ssh connection open. LOGIN_LOOP = "echo ok; echo ready; "+ "for (( ; ; )); do kill -0 $PPID && sleep 10 || exit; done;" LOGIN_TIMEOUT = 30 ## # Closes all remote shell connections. def self.disconnect_all return unless defined?(@remote_shells) @remote_shells.each{|rs| rs.disconnect} end ## # Registers a remote shell for global access from the class. # Handled automatically on initialization. def self.register remote_shell (@remote_shells ||= []) << remote_shell end - attr_reader :host, :user, :pid + attr_reader :host, :user, :parent_pid attr_accessor :ssh_flags, :rsync_flags ## # Remote shells essentially need a host and optional user. # Typical instantiation is done through either of these methods: # RemoteShell.new "user@host" # RemoteShell.new "host", :user => "user" # # The constructor also supports the following options: # :env:: hash - hash of environment variables to set for the ssh session # :password:: string - password for ssh login; if missing the deploy server # will attempt to prompt the user for a password. def initialize host, options={} super $stdout, options @host, @user = host.split("@").reverse @user ||= options[:user] @rsync_flags = ["-azrP"] @rsync_flags.concat [*options[:rsync_flags]] if options[:rsync_flags] @ssh_flags = [ "-o ControlMaster=auto", "-o ControlPath=~/.ssh/sunshine-%r@%h:%p" ] @ssh_flags.concat ["-l", @user] if @user @ssh_flags.concat [*options[:ssh_flags]] if options[:ssh_flags] - @pid, @inn, @out, @err = nil + @parent_pid = nil self.class.register self end ## # Runs a command via SSH. Optional block is passed the # stream(stderr, stdout) and string data. def call command_str, options={}, &block Sunshine.logger.info @host, "Running: #{command_str}" do execute build_remote_cmd(command_str, options), &block end end ## # Connect to host via SSH and return process pid def connect return true if connected? cmd = ssh_cmd quote_cmd(LOGIN_LOOP), :sudo => false - @pid, @inn, @out, @err = popen4 cmd.join(" ") - @inn.sync = true + @parent_pid, inn, out, err = popen4 cmd.join(" ") + inn.sync = true data = "" ready = nil start_time = Time.now.to_i - until ready || @out.eof? - data << @out.readpartial(1024) + until ready || out.eof? + data << out.readpartial(1024) ready = data =~ /ready/ raise TimeoutError if timed_out?(start_time, LOGIN_TIMEOUT) end unless connected? disconnect host_info = [@user, @host].compact.join("@") raise ConnectionError, "Can't connect to #{host_info}" end - @inn.close - @pid + inn.close rescue nil + out.close rescue nil + err.close rescue nil + + @parent_pid end ## # Check if SSH session is open and returns process pid def connected? - Process.kill(0, @pid) && @pid rescue false + Process.kill(0, @parent_pid) && @parent_pid rescue false end ## # Disconnect from host def disconnect - @inn.close rescue nil - @out.close rescue nil - @err.close rescue nil - - kill_process @pid, "HUP" rescue nil - - @pid = nil + kill_process @parent_pid, "HUP" rescue nil + @parent_pid = nil end ## # Download a file via rsync def download from_path, to_path, options={}, &block from_path = "#{@host}:#{from_path}" Sunshine.logger.info @host, "Downloading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Expand a path: # shell.expand_path "~user/thing" # #=> "/home/user/thing" def expand_path path dir = File.dirname path full_dir = call "cd #{dir} && pwd" File.join full_dir, File.basename(path) end ## # Checks if the given file exists def file? filepath self.system "test -f #{filepath}" end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " cmd = quote_cmd cmd pid = fork do exec \ ssh_cmd(sudo_cmd(env_cmd(cmd)), :flags => "-t").to_a.join(" ") end Process.waitpid pid end end ## # Create a file remotely def make_file filepath, content, options={} temp_filepath = "#{TMP_DIR}/#{File.basename(filepath)}_#{Time.now.to_i}#{rand(10000)}" File.open(temp_filepath, "w+"){|f| f.write(content)} self.upload temp_filepath, filepath, options File.delete(temp_filepath) end ## # Builds an ssh command with permissions, env, etc. def build_remote_cmd cmd, options={} cmd = sh_cmd cmd cmd = env_cmd cmd cmd = sudo_cmd cmd, options cmd = ssh_cmd cmd, options end ## # Uploads a file via rsync. def upload from_path, to_path, options={}, &block to_path = "#{@host}:#{to_path}" Sunshine.logger.info @host, "Uploading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Figure out which rsync flags to use. def build_rsync_flags options flags = @rsync_flags.dup remote_rsync = 'rsync' rsync_sudo = sudo_cmd remote_rsync, options unless rsync_sudo == remote_rsync flags << "--rsync-path='#{ rsync_sudo.join(" ") }'" end flags << "-e \"ssh #{@ssh_flags.join(' ')}\"" if @ssh_flags flags.concat [*options[:flags]] if options[:flags] flags end ## # Creates an rsync command. def rsync_cmd from_path, to_path, options={} cmd = ["rsync", build_rsync_flags(options), from_path, to_path] cmd.flatten.compact.join(" ") end ## # Wraps the command in an ssh call. def ssh_cmd cmd, options=nil options ||= {} flags = [*options[:flags]].concat @ssh_flags ["ssh", flags, @host, cmd].flatten.compact end end end diff --git a/lib/sunshine/shell.rb b/lib/sunshine/shell.rb index e9cdd58..1dd5765 100644 --- a/lib/sunshine/shell.rb +++ b/lib/sunshine/shell.rb @@ -1,444 +1,470 @@ module Sunshine ## # The Shell class handles local input, output and execution to the shell. class Shell include Open4 LOCAL_USER = `whoami`.chomp LOCAL_HOST = `hostname`.chomp class << self # The message to match in stderr to determine logging in has failed. # Defaults to: # /^Sorry, try again./ attr_accessor :sudo_failed_matcher # The message to match in stderr to determine a password is required. # Defaults to: # /^Password:/ attr_accessor :sudo_prompt_matcher end self.sudo_failed_matcher = /^Sorry, try again./ self.sudo_prompt_matcher = /^Password:/ - attr_reader :user, :host, :password, :input, :output, :mutex + attr_reader :user, :host, :password, :input, :output, :mutex, :pid attr_accessor :env, :sudo, :timeout def initialize output = $stdout, options={} @output = output $stdin.sync @input = HighLine.new $stdin @user = LOCAL_USER @host = LOCAL_HOST @sudo = options[:sudo] @env = options[:env] || {} @password = options[:password] @timeout = options[:timeout] || Sunshine.timeout + @idle_time = options[:idle_after] || 1 - @mutex = nil + @mutex = @pid = nil end ## # Checks for equality def == shell @host == shell.host && @user == shell.user rescue false end ## # Prompt the user for input. def ask(*args, &block) sync{ @input.ask(*args, &block) } end ## # Prompt the user to agree. def agree(*args, &block) sync{ @input.agree(*args, &block) } end ## # Execute a command on the local system and return the output. def call cmd, options={}, &block Sunshine.logger.info @host, "Running: #{cmd}" do execute sudo_cmd(cmd, options), &block end end ## # Prompt the user to make a choice. def choose &block sync{ @input.choose(&block) } end ## # Close the output IO. (Required by the Logger class) def close @output.close end ## # Returns true. Compatibility method with RemoteShell. def connect true end ## # Returns true. Compatibility method with RemoteShell. def connected? true end ## # Returns true. Compatibility method with RemoteShell. def disconnect true end ## # Copies a file. Compatibility method with RemoteShell. def download from_path, to_path, options={}, &block Sunshine.logger.info @host, "Copying #{from_path} -> #{to_path}" do FileUtils.cp_r from_path, to_path end end alias upload download ## # Expands the path. Compatibility method with RemoteShell. def expand_path path File.expand_path path end ## # Checks if file exists. Compatibility method with RemoteShell. def file? filepath File.file? filepath end + ## + # Checks if timeout occurred. + + def timed_out? start_time=@cmd_activity, max_time=@timeout + return unless max_time + Time.now.to_f - start_time.to_f > max_time + end + + + ## + # Update the time of the last command activity + + def update_timeout + @cmd_activity = Time.now + end + + + ## + # Checks if shell is still receiving data. + + def idle? start_time=@cmd_activity, max_time=@idle_time + timed_out? start_time, max_time + end + + ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " pid = fork do exec sudo_cmd(env_cmd(cmd)).to_a.join(" ") end Process.waitpid pid end end ## # Write a file. Compatibility method with RemoteShell. def make_file filepath, content, options={} File.open(filepath, "w+"){|f| f.write(content)} end ## # Get the name of the OS def os_name @os_name ||= call("uname -s").strip.downcase end ## # Prompt the user for a password def prompt_for_password host_info = [@user, @host].compact.join("@") @password = ask("#{host_info} Password:") do |q| q.echo = false end end ## # Build an env command if an env_hash is passed def env_cmd cmd, env_hash=@env if env_hash && !env_hash.empty? env_vars = env_hash.map{|e| e.join("=")} cmd = ["env", env_vars, cmd].flatten end cmd end ## # Wrap command in quotes and escape as needed. def quote_cmd cmd cmd = [*cmd].join(" ") "'#{cmd.gsub(/'/){|s| "'\\''"}}'" end ## # Build an sh -c command def sh_cmd cmd ["sh", "-c", quote_cmd(cmd)] end ## # Build a command with sudo. # If sudo_val is nil, it is considered to mean "pass-through" # and the default shell sudo will be used. # If sudo_val is false, the cmd will be returned unchanged. # If sudo_val is true, the returned command will be prefaced # with sudo -H # If sudo_val is a String, the command will be prefaced # with sudo -H -u string_value def sudo_cmd cmd, sudo_val=nil sudo_val = sudo_val[:sudo] if Hash === sudo_val sudo_val = @sudo if sudo_val.nil? case sudo_val when true ["sudo", "-H", cmd].flatten when String ["sudo", "-H", "-u", sudo_val, cmd].flatten else cmd end end ## # Force symlinking a directory. def symlink target, symlink_name call "ln -sfT #{target} #{symlink_name}" rescue false end ## # Synchronize a block with the current mutex if it exists. def sync if @mutex @mutex.synchronize{ yield } else yield end end ## # Returns true if command was run successfully, otherwise returns false. def system cmd, options=nil call(cmd, options) && true rescue false end ## # Checks if timeout occurred. def timed_out? start_time, max_time=@timeout return unless max_time Time.now.to_i - start_time.to_i > max_time end ## # Execute a block while setting the shell's mutex. # Sets the mutex to its original value on exit. # Executing commands with a mutex is used for user prompts. def with_mutex mutex old_mutex, @mutex = @mutex, mutex yield @mutex = old_mutex end ## # Runs the passed block within a connection session. # If the shell is already connected, connecting and disconnecting # is ignored; otherwise, the session method will ensure that # the shell's connection gets closed after the block has been # executed. def with_session prev_connection = connected? connect unless prev_connection yield disconnect unless prev_connection end ## # Write string to stdout (by default). def write str @output.write str end alias << write ## # Execute a command with open4 and loop until the process exits. # The cmd argument may be a string or an array. If a block is passed, # it will be called when data is received and passed the stream type # and stream string value: # shell.execute "test -s 'blah' && echo 'true'" do |stream, str| # stream #=> :stdout # string #=> 'true' # end # # The method returns the output from the stdout stream by default, and # raises a CmdError if the exit status of the command is not zero. def execute cmd cmd = [cmd] unless Array === cmd - pid, inn, out, err = popen4(*cmd) + @pid, inn, out, err = popen4(*cmd) inn.sync = true log_methods = {out => :debug, err => :error} - result, status = process_streams(pid, out, err) do |stream, data| + result, status = process_streams(@pid, out, err) do |stream, data| stream_name = :out if stream == out stream_name = :err if stream == err stream_name = :inn if stream == inn + Sunshine.logger.send log_methods[stream], + "#{@host}:#{stream_name}", data # User blocks should run with sync threads to avoid badness. sync do - Sunshine.logger.send log_methods[stream], - "#{@host}:#{stream_name}", data - yield(stream_name, data, inn) if block_given? end if password_required?(stream_name, data) then - kill_process(pid) unless Sunshine.interactive? + kill_process(@pid) unless Sunshine.interactive? send_password_to_stream(inn, data) end end raise_command_failed(status, cmd) unless status.success? result[out].join.chomp ensure inn.close rescue nil out.close rescue nil err.close rescue nil + @pid = nil end private def raise_command_failed(status, cmd) err = CmdError.new status.exitstatus, [*cmd].join(" ") raise err end def password_required? stream_name, data stream_name == :err && data =~ Shell.sudo_prompt_matcher end def send_password_to_stream inn, data prompt_for_password if data =~ Shell.sudo_failed_matcher inn.puts @password || prompt_for_password end def kill_process pid, kill_type="KILL" begin Process.kill kill_type, pid Process.wait rescue end end def process_streams pid, *streams result = Hash.new{|h,k| h[k] = []} start_time = Time.now # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 raise TimeoutError if timed_out? start_time next if selected.nil? or selected.empty? selected.each do |stream| start_time = Time.now if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) yield(stream, data) result[stream] << data end end return result, status end end end
jcasts/sunshine
2cdf8843f4dc5145ff9b3a223a12d3c5d5d80965
removed unnecessary items in apache2 config template
diff --git a/templates/apache/apache.conf.erb b/templates/apache/apache.conf.erb index 8fafee5..7d335ea 100644 --- a/templates/apache/apache.conf.erb +++ b/templates/apache/apache.conf.erb @@ -1,65 +1,63 @@ -LoadModule log_config_module modules/mod_log_config.so LoadModule authz_host_module modules/mod_authz_host.so ErrorLog <%= expand_path log_file(:stderr) %> TransferLog <%= expand_path log_file(:stdout) %> <% if use_passenger? -%> LoadModule passenger_module <%= passenger_root %>/ext/apache2/mod_passenger.so PassengerRuby <%= shell.call "which ruby" %> PassengerRoot <%= passenger_root %> PassengerMaxPoolSize <%= processes %> <% end -%> <% unless App === target -%> LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_connect_module modules/mod_proxy_connect.so LoadModule proxy_http_module modules/mod_proxy_http.so LoadModule proxy_balancer_module modules/mod_proxy_balancer.so <% end -%> PidFile <%= expand_path pid %> MaxClients <%= connections %> <% if sudo == true || sudo == 'root' -%> User nobody -Group nobody <% end -%> Listen <%= port %> NameVirtualHost *:<%= port %> <VirtualHost *:<%= port %>> ServerName <%= server_name %> ServerAlias www.<%= server_name %> DocumentRoot <%= expand_path app.current_path %>/public <Directory <%= expand_path app.current_path %>/public> Options FollowSymLinks -MultiViews AllowOverride None Order allow,deny Allow from all </Directory> <%= "RailsBaseURI #{rails_base_uri}" if rails_base_uri %> <% unless App === target -%> <Proxy balancer://<%= proxy_name %>> <% [*target].each do |server| %> BalancerMember http://0.0.0.0:<%= server.port %> <% end -%> </Proxy> # Using / after the proxy target is essential to the public dir. ProxyPass / balancer://<%= proxy_name %>/ timeout=<%= timeout %> ProxyPassReverse / balancer://<%= proxy_name %>/ ProxyPreserveHost On <% end -%> </VirtualHost>
jcasts/sunshine
0cb880421cbf59a217613ef372b5fa8aae77edeb
fixed missing server app env file symlink
diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index eace06a..ca7b03d 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -1,681 +1,681 @@ module Sunshine ## # Handles App deployment functionality for a single deploy server. # # Server apps can be assigned any number of roles for classification. # :roles:: sym|array - roles assigned (web, db, app, etc...) # By default server apps get the special :all role which will # always return true when calling: # server_app.has_roles? :some_role # # ServerApp objects can be instantiated several ways: # ServerApp.new app_instance, shell_instance, options_hash # # When passing an App instance, the new ServerApp will keep an active link # to the app's properties. Name, deploy, and path attributes will be # actively linked. # # Rely on ServerApp to create a RemoteShell instance to use: # ServerApp.new app_instance, "host.com", options_hash # # Instantiate with app name and rely on Sunshine defaults for app paths: # ServerApp.new "app_name", shell_instance, options_hash # # Explicitely assign the app's root path: # ServerApp.new "app_name", ..., :root_path => "/path/to/app_root" # # Assigning a specific deploy name to use can be done with the # :deploy_name option: # ServerApp.new "app_name", ..., :deploy_name => "deploy" class ServerApp ## # Define an attribute that will get a value from app, or locally if # @app isn't set. def self.app_attr *attribs attribs.each do |attrib| class_eval <<-STR, __FILE__, __LINE__ + 1 def #{attrib} @app ? @app.send(:#{attrib}) : @#{attrib} end STR end end ## # Creates dependency instance methods such as gem_install, yum_install, etc # on both App and ServerApp classes. def self.register_dependency_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = Hash === names.last ? names.delete_at(-1) : Hash.new names.each do |name| dep = #{dep_class}.new(name, options) dep.install! :call => @shell end end STR App.class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = names.last if Hash === names.last with_server_apps options, :msg => "Installing #{dep_class.short_name} packages", :send => [:#{dep_class.short_name}_install, *names] end STR end ## # Creates a ServerApp instance from a deploy info file. def self.from_info_file path, shell=nil shell ||= Sunshine.shell opts = YAML.load shell.call("cat #{path}") opts[:root_path] = opts.delete :path sa_shell = shell.dup sa_shell.env = opts[:env] || Hash.new sa_shell.connect if shell.connected? new opts[:name], sa_shell, opts end app_attr :name, :deploy_name app_attr :root_path, :checkout_path, :current_path app_attr :deploys_path, :log_path, :shared_path, :scripts_path attr_accessor :app, :roles, :scripts, :info, :shell, :crontab attr_writer :pkg_manager ## # Create a server app instance. Supports the following # argument configurations: # # ServerApp.new app_inst, "myserver.com", :roles => :web # ServerApp.new "app_name", shell_inst, options_hash def initialize app, host, options={} @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No status for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end - symlink_scripts_to_root + symlink_scripts_to_root @scripts.keys, "env" end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => @shell.call("date"), :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path, :sunshine_version => Sunshine::VERSION }.merge @info end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec "#{self.name}:#{self.root_path}", 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's restart script. Raises an exception on failure. # Post-deploy only. def restart! # Permissions are handled by the script, use: :sudo => false run_script! :restart, :sudo => false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the root_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} run_script! name, options, &block rescue false end ## # Runs a script from the root_path. Raises an exception if the status # code is not 0. # Post-deploy only. def run_script! name, options=nil, &block options ||= {} script_path = File.join self.scripts_path, name.to_s @shell.call script_path, options, &block end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script! :status, :sudo => false true rescue CmdError => e return false if e.exit_code == Daemon::STATUS_DOWN_CODE raise e end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Run the app's start script. Raises an exception on failure. # Post-deploy only. def start! options=nil options ||= {} if running? return unless options[:force] stop! end # Permissions are handled by the script, use: :sudo => false run_script! :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's stop script. Raises an exception on failure. # Post-deploy only. def stop! # Permissions are handled by the script, use: :sudo => false run_script! :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## - # Creates a symlink of every script in the scripts_path dir in the + # Creates a symlink of every script_name from the scripts_path dir to the # app's root directory for easy access. - def symlink_scripts_to_root - self.scripts.each do |name, val| + def symlink_scripts_to_root *script_names + script_names.flatten.each do |name, val| script_file = File.join self.scripts_path, name.to_s pointer_file = File.join self.root_path, name.to_s @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} excludes = scm_info.delete :exclude if scm_info[:exclude] excludes = [excludes].flatten.compact excludes.map!{|e| "--exclude #{e}"} repo = RsyncRepo.new code_dir, :flags => excludes repo.checkout_to self.checkout_path, @shell @info[:scm] = scm_info end ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@current_path}/script" end end end
jcasts/sunshine
498b0d6a5c1e228e63fecd849d4a092c77fa8ce0
made rsync repo remote checkout only
diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index e234c48..1178767 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -69,1025 +69,1025 @@ module Sunshine # # qa_special: # :inherits: qa # :root_path: /path/to/application # :deploy_env: qa # # By default, App will get the deploy_env value from Sunshine.deploy_env, but # it may also be passed in explicitely as an option. class App ## # Initialize and deploy an application in a single step. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml # # Options supported are: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_checkout:: Boolean - when true, will checkout the codebase # directly from the deploy servers; defaults to false. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] @on_sigint = @on_exception = nil end ## # Call a command on specified server apps. Returns an array of responses. # Supports any App#find and Shell#call options: # app.call "ls -1", :sudo => true, :host => "web.app.com" # #=> [".\n..\ndir1", ".\n..\ndir1", ".\n..\ndir2"] def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Start a persistant connection to app servers. # Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected and returns a boolean. # Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected and returns a boolean. # Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect from app servers. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # If the deploy fails or an exception is raised, it will attempt to # run the Sunshine.exception_behavior, which is set to :revert by # default. However, this is not true of ssh connection failures. # # If the deploy is interrupted by a SIGINT, it will attempt to run # the Sunshine.sigint_behavior, which is set to :revert by default. # # The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Once deployment is complete, the deploy method will attempt to # run App#start! which will run any start script checked into # App#scripts_path, or the start script that will have been generated # by using Sunshine server setups. def deploy options=nil state = { :success => false, :stopped => false, :symlinked => false } Sunshine.logger.info :app, "Beginning #{@name} deploy" with_session options do |app| interruptable state do raise DeployError, "No servers defined for #{@name}" if @server_apps.empty? make_app_directories checkout_codebase state[:stopped] = true if stop state[:symlinked] = true if symlink_current_dir yield self if block_given? run_post_user_lambdas build_control_scripts build_deploy_info_file build_crontab register_as_deployed state[:success] = true if start! :force => true end remove_old_deploys if state[:success] rescue Sunshine.logger.error :app, "Could not remove old deploys" state[:success] &&= deployed? end Sunshine.logger.info :app, "Finished #{@name} deploy" if state[:success] state[:success] end ## # Runs the given block while handling SIGINTs and exceptions # according to rules set by Sunshine.sigint_behavior and # Sunshine.exception_behavior or with the override hooks # App#on_sigint and App#on_exception. def interruptable options={} interrupt_trap = TrapStack.add_trap "Interrupted #{@name}" do handle_sigint options end yield if block_given? rescue => e Sunshine.logger.error :app, "#{e.class}: #{e.message}" do Sunshine.logger.error '>>', e.backtrace.join("\n") end handle_exception e, options ensure TrapStack.delete_trap interrupt_trap end ## # Calls the Apps on_sigint hook or the default Sunshine.sigint_behavior. def handle_sigint state={} return @on_sigint.call(state) if @on_sigint handle_interruption Sunshine.sigint_behavior, state end ## # Calls the Apps on_exception hook or the default # Sunshine.exception_behavior. def handle_exception exception, state={} return @on_exception.call(exception, state) if @on_exception handle_interruption Sunshine.exception_behavior, state end ## # Set this to define the behavior of SIGINT during a deploy. # Defines what to do when an INT signal is received when running # a proc through App#interruptable. Used primarily to catch SIGINTs # during deploys. Passes the block a hash with the state of the deploy: # # app.on_sigint do |deploy_state_hash| # deploy_state_hash # #=> {:stopped => true, :symlinked => true, :success => false} # end def on_sigint &block @on_sigint = block end ## # Set this to define the behavior of exceptions during a deploy. # Defines what to do when an exception is received when running # a proc through App#interruptable. Used primarily to catch exceptions # during deploys. Passes the block the exception and a hash with the # state of the deploy: # # app.on_exception do |exception, deploy_state_hash| # # do something... # end def on_exception &block @on_exception = block end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. def handle_interruption behavior, state={} case behavior when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :revert revert! if state[:symlinked] start if state[:stopped] when Sunshine.interactive? && :console self.console! when Sunshine.interactive? && :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" menu.choice(:revert) { handle_interruption :revert, state } menu.choice(:console){ handle_interruption :console, state } menu.choice(:exit) { handle_interruption :exit, state } end else raise DeployError, "Deploy of #{@name} was interrupted." end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. # app.revert! :role => :web def revert! options=nil with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env on all app shells. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. # :exclude:: String|Array - Exclude the specified paths during # a deploy via copy. def checkout_codebase options=nil copy_option = options[:copy] if options exclude = options.delete :exclude if options - if @remote_checkout && !copy_option + if RsyncRepo === @repo || (@remote_checkout && !copy_option) with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path scm_info[:exclude] = [Sunshine.exclude_paths, exclude].flatten.compact with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully by checking the name of the # deploy on every app server with the instance's deploy name. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. Supports all App#find options. # See Sunshine::ServerApp for more information. def each options=nil, &block server_apps = find options server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. # Supports all App#find options. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Sunshine::Yum # # Package managers are typically detected automatically by each # individual server_apps. # Supports all App#find options. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. # Supports all App#find options. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. # Supports all App#find options. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app # Supports all App#find options. def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. # Supports all App#find options. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Run the restart script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def restart! options=nil with_server_apps options, :msg => "Running restart script", :send => :restart! end ## # Runs bundler on deploy servers. Supports all App#find options. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] end ## # Runs GemInstaller on deploy servers. Supports all App#find options. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run the given script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def run_script! name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script!, name, options] end ## # Run a sass task on any or all deploy servers. # Supports all App#find options. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. # Supports all App#find options. def shell_env env_hash=nil, options=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps options, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Run the start script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def start! options=nil with_server_apps options, :msg => "Running start script", :send => [:start!, options] end ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. Supports all App#find options. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end ## # Run the stop script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def stop! options=nil with_server_apps options, :msg => "Running stop script", :send => :stop! end ## # Use sudo on all the app's deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. # Supports all App#find options. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! # Calls App#each if Sunshine.use_threads? is false. # Supports all App#find options. def threaded_each options=nil, &block return each options, &block unless Sunshine.use_threads? mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end # Supports all App#find options. def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here # end # # Note: App#with_server_apps calls App#with_session. If you do not need # or want a server connection you can pass :no_session. def with_server_apps search_options, options={} options = search_options.merge options if Hash === search_options message = options[:msg] method = options[:no_threads] ? :each : :threaded_each auto_session = !options[:no_session] block = lambda do |*| send(method, search_options) do |server_app| if block_given? yield(server_app) elsif options[:send] server_app.send(*options[:send]) end end end msg_block = lambda do |*| if message Sunshine.logger.info(:app, message, &block) else block.call end end auto_session ? with_session(&msg_block) : msg_block.call end ## # Runs block ensuring a connection to remote_shells. # Connecting and disconnecting will be ignored if a session # already exists. Supports all App#find options. # # Ensures that servers are disconnected after the block is run # if servers were not previously connected. def with_session options=nil with_filter options do prev_connection = connected?
jcasts/sunshine
e2efd191ea4385031fb9cd248120105dc7854fdb
removed ruby -w option until open4 stops raising warnings
diff --git a/bin/sunshine b/bin/sunshine index e2050e4..f7a7db1 100755 --- a/bin/sunshine +++ b/bin/sunshine @@ -1,12 +1,12 @@ -#!/usr/bin/env ruby -w +#!/usr/bin/env ruby begin require 'sunshine' rescue LoadError => e raise e unless e.message =~ %r{no such file to load -- sunshine} $: << File.join(File.dirname(__FILE__), "../lib") require 'sunshine' end Sunshine.run
jcasts/sunshine
4cba8d4c081159f8a48b18b3080bedd8a74822e3
added Sunshine config to turn off threads
diff --git a/lib/sunshine.rb b/lib/sunshine.rb index 0f4b7a8..176fea6 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,441 +1,451 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'yaml' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' require 'irb' # Turn off EOF tracking to be able to prompt on deploy exceptions. HighLine.track_eof = false ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. VERSION = '1.3.0' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { 'auto_dependencies' => true, 'deploy_env' => :development, 'exception_behavior' => :revert, 'exclude_paths' => [], 'interactive' => true, 'level' => 'info', 'max_deploy_versions' => 5, 'remote_checkouts' => false, + 'threads_enabled' => true, 'timeout' => 300, 'sigint_behavior' => :revert, 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end ## # Defines what to do when deploy raises an exception. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.exception_behavior @config['exception_behavior'] end ## # Array of paths or globs that should be excluded from the checkout. # Does not work with remote_checkouts enabled. def self.exclude_paths @config['exclude_paths'] end ## # Should sunshine ever ask for user input? True by default. # Overridden in the config or with the -a option. def self.interactive? @config['interactive'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end ## # Defines what to do when sigint is sent during deploys. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.sigint_behavior @config['sigint_behavior'] end ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end + ## + # Check if App objects should use threads when iterating over ServerApps. + # Defaults to true, overridden with the 'threads_enabled' config. + + def self.use_threads? + @config['threads_enabled'] + end + + ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config create_default_config! load_config_file USER_CONFIG_FILE @config['deploy_env'] = ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] || @config['deploy_env'] @config end def self.create_default_config! unless File.file? USER_CONFIG_FILE File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" msg << DEFAULT_CONFIG.to_yaml self.exit 1, msg end end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset TrapStack.trap_signal :INT do |msg| $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" logger.info :INT, msg end TrapStack.add_trap "Disconnecting all remote shells." do RemoteShell.disconnect_all end require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' require 'sunshine/trap_stack' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies' diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index acad245..e234c48 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -465,738 +465,741 @@ module Sunshine each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. # :exclude:: String|Array - Exclude the specified paths during # a deploy via copy. def checkout_codebase options=nil copy_option = options[:copy] if options exclude = options.delete :exclude if options if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path scm_info[:exclude] = [Sunshine.exclude_paths, exclude].flatten.compact with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully by checking the name of the # deploy on every app server with the instance's deploy name. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. Supports all App#find options. # See Sunshine::ServerApp for more information. def each options=nil, &block server_apps = find options server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. # Supports all App#find options. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Sunshine::Yum # # Package managers are typically detected automatically by each # individual server_apps. # Supports all App#find options. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. # Supports all App#find options. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. # Supports all App#find options. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app # Supports all App#find options. def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. # Supports all App#find options. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Run the restart script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def restart! options=nil with_server_apps options, :msg => "Running restart script", :send => :restart! end ## # Runs bundler on deploy servers. Supports all App#find options. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] end ## # Runs GemInstaller on deploy servers. Supports all App#find options. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run the given script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def run_script! name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script!, name, options] end ## # Run a sass task on any or all deploy servers. # Supports all App#find options. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. # Supports all App#find options. def shell_env env_hash=nil, options=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps options, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Run the start script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def start! options=nil with_server_apps options, :msg => "Running start script", :send => [:start!, options] end ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. Supports all App#find options. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end ## # Run the stop script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def stop! options=nil with_server_apps options, :msg => "Running stop script", :send => :stop! end ## # Use sudo on all the app's deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. # Supports all App#find options. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! + # Calls App#each if Sunshine.use_threads? is false. # Supports all App#find options. def threaded_each options=nil, &block + return each options, &block unless Sunshine.use_threads? + mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end # Supports all App#find options. def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here # end # # Note: App#with_server_apps calls App#with_session. If you do not need # or want a server connection you can pass :no_session. def with_server_apps search_options, options={} options = search_options.merge options if Hash === search_options message = options[:msg] method = options[:no_threads] ? :each : :threaded_each auto_session = !options[:no_session] block = lambda do |*| send(method, search_options) do |server_app| if block_given? yield(server_app) elsif options[:send] server_app.send(*options[:send]) end end end msg_block = lambda do |*| if message Sunshine.logger.info(:app, message, &block) else block.call end end auto_session ? with_session(&msg_block) : msg_block.call end ## # Runs block ensuring a connection to remote_shells. # Connecting and disconnecting will be ignored if a session # already exists. Supports all App#find options. # # Ensures that servers are disconnected after the block is run # if servers were not previously connected. def with_session options=nil with_filter options do prev_connection = connected? begin connect unless prev_connection yield self ensure disconnect unless prev_connection end end end private ## # Set all the app paths based on the root deploy path. def set_deploy_paths path @root_path = path || File.join(Sunshine.web_directory, @name) @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@current_path}/script" end ## # Set the app's deploy servers: # server_apps_from_config "some_server" # #=> [<ServerApp @host="some_server"...>] # # server_apps_from_config ["svr1", "svr2", "svr3"] # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] # # remote_shells = [["svr1", {:roles => "web db app"}], "svr2", "svr3"] # server_apps_from_config remote_shells # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] def server_apps_from_config shells shells = [*shells].compact shells.map{|shell| ServerApp.new(*[self,*shell]) } end ## # Set the app's repo: # repo_from_config SvnRepo.new("myurl") # repo_from_config :type => :svn, :url => "myurl" def repo_from_config repo_def case repo_def when Sunshine::Repo repo_def when Hash Sunshine::Repo.new_of_type repo_def[:type], repo_def[:url], repo_def else Sunshine::Repo.detect Sunshine::PATH end end ## # Load a yml config file, parses it with erb and resolves deploy env # inheritance. def config_from_file config_file, erb_binding=binding, env=@deploy_env return {} unless config_file config_data = YAML.load build_erb(config_file, erb_binding) load_config_for config_data, env end ## # Loads an app yml config file, gets the default config # and the current deploy env and returns a merged config hash. def load_config_for config_hash, env return {} unless config_hash deploy_env_config = (config_hash[env] || {}).dup deploy_env_config[:inherits] ||= [] deploy_env_config[:inherits].unshift(:default) if :default != env && config_hash[:default] merge_config_inheritance deploy_env_config, config_hash end ## # Recursively merges config hashes based on the value at :inherits def merge_config_inheritance main_config, all_configs new_config = {} parents = [*main_config[:inherits]].compact parents.each do |config_name| parent = all_configs[config_name] parent = merge_config_inheritance parent, all_configs new_config = new_config.merge parent end new_config.merge main_config # Two merges important for inheritance order end end end diff --git a/lib/sunshine/binder.rb b/lib/sunshine/binder.rb index 119e129..cd50912 100644 --- a/lib/sunshine/binder.rb +++ b/lib/sunshine/binder.rb @@ -1,70 +1,69 @@ module Sunshine ## - # Instantiated per deploy server and used to pass bindings to the config's - # ERB build method: + # Create a selective binding. Useful for controlling ERB builds: # binder.set :server_name, "blah.com" # binder.forward :server_method, ... # binder.get_binding class Binder def initialize target @target = target end ## # Set the binding instance variable and accessor method. def set key, value=nil, &block value ||= block if block_given? instance_variable_set("@#{key}", value) eval_str = <<-STR undef #{key} if defined?(#{key}) def #{key}(*args) if Proc === @#{key} @#{key}.call(*args) else @#{key} end end STR instance_eval eval_str, __FILE__, __LINE__ + 1 end ## # Takes a hash and assign each hash key/value as an attribute. def import_hash hash hash.each{|k, v| self.set(k, v)} end ## # Forward a method to the server instance. def forward *method_names method_names.each do |method_name| instance_eval <<-STR, __FILE__, __LINE__ + 1 undef #{method_name} if defined?(#{method_name}) def #{method_name}(*args, &block) @target.#{method_name}(*args, &block) end STR end end ## # Retrieve the object's binding. def get_binding binding end end end
jcasts/sunshine
4e3d8ce634a59cb9c89a465abfc1e0a2f618c7dc
removed gpg_decrypt
diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index 30572f9..acad245 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -156,1041 +156,1024 @@ module Sunshine self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] @on_sigint = @on_exception = nil end ## # Call a command on specified server apps. Returns an array of responses. # Supports any App#find and Shell#call options: # app.call "ls -1", :sudo => true, :host => "web.app.com" # #=> [".\n..\ndir1", ".\n..\ndir1", ".\n..\ndir2"] def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Start a persistant connection to app servers. # Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected and returns a boolean. # Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected and returns a boolean. # Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect from app servers. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # If the deploy fails or an exception is raised, it will attempt to # run the Sunshine.exception_behavior, which is set to :revert by # default. However, this is not true of ssh connection failures. # # If the deploy is interrupted by a SIGINT, it will attempt to run # the Sunshine.sigint_behavior, which is set to :revert by default. # # The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Once deployment is complete, the deploy method will attempt to # run App#start! which will run any start script checked into # App#scripts_path, or the start script that will have been generated # by using Sunshine server setups. def deploy options=nil state = { :success => false, :stopped => false, :symlinked => false } Sunshine.logger.info :app, "Beginning #{@name} deploy" with_session options do |app| interruptable state do raise DeployError, "No servers defined for #{@name}" if @server_apps.empty? make_app_directories checkout_codebase state[:stopped] = true if stop state[:symlinked] = true if symlink_current_dir yield self if block_given? run_post_user_lambdas build_control_scripts build_deploy_info_file build_crontab register_as_deployed state[:success] = true if start! :force => true end remove_old_deploys if state[:success] rescue Sunshine.logger.error :app, "Could not remove old deploys" state[:success] &&= deployed? end Sunshine.logger.info :app, "Finished #{@name} deploy" if state[:success] state[:success] end ## # Runs the given block while handling SIGINTs and exceptions # according to rules set by Sunshine.sigint_behavior and # Sunshine.exception_behavior or with the override hooks # App#on_sigint and App#on_exception. def interruptable options={} interrupt_trap = TrapStack.add_trap "Interrupted #{@name}" do handle_sigint options end yield if block_given? rescue => e Sunshine.logger.error :app, "#{e.class}: #{e.message}" do Sunshine.logger.error '>>', e.backtrace.join("\n") end handle_exception e, options ensure TrapStack.delete_trap interrupt_trap end ## # Calls the Apps on_sigint hook or the default Sunshine.sigint_behavior. def handle_sigint state={} return @on_sigint.call(state) if @on_sigint handle_interruption Sunshine.sigint_behavior, state end ## # Calls the Apps on_exception hook or the default # Sunshine.exception_behavior. def handle_exception exception, state={} return @on_exception.call(exception, state) if @on_exception handle_interruption Sunshine.exception_behavior, state end ## # Set this to define the behavior of SIGINT during a deploy. # Defines what to do when an INT signal is received when running # a proc through App#interruptable. Used primarily to catch SIGINTs # during deploys. Passes the block a hash with the state of the deploy: # # app.on_sigint do |deploy_state_hash| # deploy_state_hash # #=> {:stopped => true, :symlinked => true, :success => false} # end def on_sigint &block @on_sigint = block end ## # Set this to define the behavior of exceptions during a deploy. # Defines what to do when an exception is received when running # a proc through App#interruptable. Used primarily to catch exceptions # during deploys. Passes the block the exception and a hash with the # state of the deploy: # # app.on_exception do |exception, deploy_state_hash| # # do something... # end def on_exception &block @on_exception = block end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. def handle_interruption behavior, state={} case behavior when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :revert revert! if state[:symlinked] start if state[:stopped] when Sunshine.interactive? && :console self.console! when Sunshine.interactive? && :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" menu.choice(:revert) { handle_interruption :revert, state } menu.choice(:console){ handle_interruption :console, state } menu.choice(:exit) { handle_interruption :exit, state } end else raise DeployError, "Deploy of #{@name} was interrupted." end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. # app.revert! :role => :web def revert! options=nil with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env on all app shells. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. # :exclude:: String|Array - Exclude the specified paths during # a deploy via copy. def checkout_codebase options=nil copy_option = options[:copy] if options exclude = options.delete :exclude if options if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path scm_info[:exclude] = [Sunshine.exclude_paths, exclude].flatten.compact with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully by checking the name of the # deploy on every app server with the instance's deploy name. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. Supports all App#find options. # See Sunshine::ServerApp for more information. def each options=nil, &block server_apps = find options server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end - ## - # Decrypt a file using gpg. Supports all App#find options, plus: - # :output:: str - the path the output file should go to - # :passphrase:: str - the passphrase gpg should use - - def gpg_decrypt gpg_file, options={} - options[:passphrase] ||= - Sunshine.shell.ask("Enter gpg passphrase:") do |q| - q.echo = false - end - - with_server_apps options, - :msg => "Gpg decrypt: #{gpg_file}", - :send => [:gpg_decrypt, gpg_file, options] - end - - ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. # Supports all App#find options. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Sunshine::Yum # # Package managers are typically detected automatically by each # individual server_apps. # Supports all App#find options. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. # Supports all App#find options. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. # Supports all App#find options. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app # Supports all App#find options. def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. # Supports all App#find options. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Run the restart script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def restart! options=nil with_server_apps options, :msg => "Running restart script", :send => :restart! end ## # Runs bundler on deploy servers. Supports all App#find options. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] end ## # Runs GemInstaller on deploy servers. Supports all App#find options. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run the given script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def run_script! name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script!, name, options] end ## # Run a sass task on any or all deploy servers. # Supports all App#find options. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. # Supports all App#find options. def shell_env env_hash=nil, options=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps options, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Run the start script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def start! options=nil with_server_apps options, :msg => "Running start script", :send => [:start!, options] end ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. Supports all App#find options. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end ## # Run the stop script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def stop! options=nil with_server_apps options, :msg => "Running stop script", :send => :stop! end ## # Use sudo on all the app's deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. # Supports all App#find options. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! # Supports all App#find options. def threaded_each options=nil, &block mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end # Supports all App#find options. def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here # end # # Note: App#with_server_apps calls App#with_session. If you do not need # or want a server connection you can pass :no_session. def with_server_apps search_options, options={} options = search_options.merge options if Hash === search_options message = options[:msg] method = options[:no_threads] ? :each : :threaded_each auto_session = !options[:no_session] block = lambda do |*| send(method, search_options) do |server_app| if block_given? yield(server_app) elsif options[:send] server_app.send(*options[:send]) end end end msg_block = lambda do |*| if message Sunshine.logger.info(:app, message, &block) else block.call end end auto_session ? with_session(&msg_block) : msg_block.call end ## # Runs block ensuring a connection to remote_shells. # Connecting and disconnecting will be ignored if a session # already exists. Supports all App#find options. # # Ensures that servers are disconnected after the block is run # if servers were not previously connected. def with_session options=nil with_filter options do prev_connection = connected? begin connect unless prev_connection yield self ensure disconnect unless prev_connection end end end private ## # Set all the app paths based on the root deploy path. def set_deploy_paths path @root_path = path || File.join(Sunshine.web_directory, @name) @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@current_path}/script" end ## # Set the app's deploy servers: # server_apps_from_config "some_server" # #=> [<ServerApp @host="some_server"...>] # # server_apps_from_config ["svr1", "svr2", "svr3"] # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] # # remote_shells = [["svr1", {:roles => "web db app"}], "svr2", "svr3"] # server_apps_from_config remote_shells # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] def server_apps_from_config shells shells = [*shells].compact shells.map{|shell| ServerApp.new(*[self,*shell]) } end ## # Set the app's repo: # repo_from_config SvnRepo.new("myurl") # repo_from_config :type => :svn, :url => "myurl" def repo_from_config repo_def case repo_def when Sunshine::Repo repo_def when Hash Sunshine::Repo.new_of_type repo_def[:type], repo_def[:url], repo_def else Sunshine::Repo.detect Sunshine::PATH end end ## # Load a yml config file, parses it with erb and resolves deploy env # inheritance. def config_from_file config_file, erb_binding=binding, env=@deploy_env return {} unless config_file config_data = YAML.load build_erb(config_file, erb_binding) load_config_for config_data, env end ## # Loads an app yml config file, gets the default config # and the current deploy env and returns a merged config hash. def load_config_for config_hash, env return {} unless config_hash deploy_env_config = (config_hash[env] || {}).dup deploy_env_config[:inherits] ||= [] deploy_env_config[:inherits].unshift(:default) if :default != env && config_hash[:default] diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index ecb109c..5583abb 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -1,705 +1,683 @@ module Sunshine ## # Handles App deployment functionality for a single deploy server. # # Server apps can be assigned any number of roles for classification. # :roles:: sym|array - roles assigned (web, db, app, etc...) # By default server apps get the special :all role which will # always return true when calling: # server_app.has_roles? :some_role # # ServerApp objects can be instantiated several ways: # ServerApp.new app_instance, shell_instance, options_hash # # When passing an App instance, the new ServerApp will keep an active link # to the app's properties. Name, deploy, and path attributes will be # actively linked. # # Rely on ServerApp to create a RemoteShell instance to use: # ServerApp.new app_instance, "host.com", options_hash # # Instantiate with app name and rely on Sunshine defaults for app paths: # ServerApp.new "app_name", shell_instance, options_hash # # Explicitely assign the app's root path: # ServerApp.new "app_name", ..., :root_path => "/path/to/app_root" # # Assigning a specific deploy name to use can be done with the # :deploy_name option: # ServerApp.new "app_name", ..., :deploy_name => "deploy" class ServerApp ## # Define an attribute that will get a value from app, or locally if # @app isn't set. def self.app_attr *attribs attribs.each do |attrib| class_eval <<-STR, __FILE__, __LINE__ + 1 def #{attrib} @app ? @app.send(:#{attrib}) : @#{attrib} end STR end end ## # Creates dependency instance methods such as gem_install, yum_install, etc # on both App and ServerApp classes. def self.register_dependency_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = Hash === names.last ? names.delete_at(-1) : Hash.new names.each do |name| dep = #{dep_class}.new(name, options) dep.install! :call => @shell end end STR App.class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = names.last if Hash === names.last with_server_apps options, :msg => "Installing #{dep_class.short_name} packages", :send => [:#{dep_class.short_name}_install, *names] end STR end ## # Creates a ServerApp instance from a deploy info file. def self.from_info_file path, shell=nil shell ||= Sunshine.shell opts = YAML.load shell.call("cat #{path}") opts[:root_path] = opts.delete :path sa_shell = shell.dup sa_shell.env = opts[:env] || Hash.new sa_shell.connect if shell.connected? new opts[:name], sa_shell, opts end app_attr :name, :deploy_name app_attr :root_path, :checkout_path, :current_path app_attr :deploys_path, :log_path, :shared_path, :scripts_path attr_accessor :app, :roles, :scripts, :info, :shell, :crontab attr_writer :pkg_manager ## # Create a server app instance. Supports the following # argument configurations: # # ServerApp.new app_inst, "myserver.com", :roles => :web # ServerApp.new "app_name", shell_inst, options_hash def initialize app, host, options={} @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No status for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload + @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => @shell.call("date"), :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path, :sunshine_version => Sunshine::VERSION }.merge @info end - ## - # Decrypt a file using gpg. Allows options: - # :output:: str - the path the output file should go to - # :passphrase:: str - the passphrase gpg should use - - def gpg_decrypt gpg_file, options={} - output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') - - passphrase = options[:passphrase] - passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" - - gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ - "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" - - @shell.call "mkdir -p #{File.dirname(passphrase_file)}" - - @shell.make_file passphrase_file, passphrase - - @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" - @shell.call "rm -f #{passphrase_file}" - end - - ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec "#{self.name}:#{self.root_path}", 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's restart script. Raises an exception on failure. # Post-deploy only. def restart! # Permissions are handled by the script, use: :sudo => false run_script! :restart, :sudo => false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the root_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} run_script! name, options, &block rescue false end ## # Runs a script from the root_path. Raises an exception if the status # code is not 0. # Post-deploy only. def run_script! name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script! :status, :sudo => false true rescue CmdError => e return false if e.exit_code == Daemon::STATUS_DOWN_CODE raise e end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Run the app's start script. Raises an exception on failure. # Post-deploy only. def start! options=nil options ||= {} if running? return unless options[:force] stop! end # Permissions are handled by the script, use: :sudo => false run_script! :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's stop script. Raises an exception on failure. # Post-deploy only. def stop! # Permissions are handled by the script, use: :sudo => false run_script! :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} excludes = scm_info.delete :exclude if scm_info[:exclude] excludes = [excludes].flatten.compact excludes.map!{|e| "--exclude #{e}"} repo = RsyncRepo.new code_dir, :flags => excludes repo.checkout_to self.checkout_path, @shell @info[:scm] = scm_info end ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@current_path}/script" end end end
jcasts/sunshine
cd445f82f6a347f925684c2bc7728fd70da0769c
changed deployed_at deploy info to use server time instead of the deployer's time
diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index 68c6667..ecb109c 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -1,705 +1,705 @@ module Sunshine ## # Handles App deployment functionality for a single deploy server. # # Server apps can be assigned any number of roles for classification. # :roles:: sym|array - roles assigned (web, db, app, etc...) # By default server apps get the special :all role which will # always return true when calling: # server_app.has_roles? :some_role # # ServerApp objects can be instantiated several ways: # ServerApp.new app_instance, shell_instance, options_hash # # When passing an App instance, the new ServerApp will keep an active link # to the app's properties. Name, deploy, and path attributes will be # actively linked. # # Rely on ServerApp to create a RemoteShell instance to use: # ServerApp.new app_instance, "host.com", options_hash # # Instantiate with app name and rely on Sunshine defaults for app paths: # ServerApp.new "app_name", shell_instance, options_hash # # Explicitely assign the app's root path: # ServerApp.new "app_name", ..., :root_path => "/path/to/app_root" # # Assigning a specific deploy name to use can be done with the # :deploy_name option: # ServerApp.new "app_name", ..., :deploy_name => "deploy" class ServerApp ## # Define an attribute that will get a value from app, or locally if # @app isn't set. def self.app_attr *attribs attribs.each do |attrib| class_eval <<-STR, __FILE__, __LINE__ + 1 def #{attrib} @app ? @app.send(:#{attrib}) : @#{attrib} end STR end end ## # Creates dependency instance methods such as gem_install, yum_install, etc # on both App and ServerApp classes. def self.register_dependency_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = Hash === names.last ? names.delete_at(-1) : Hash.new names.each do |name| dep = #{dep_class}.new(name, options) dep.install! :call => @shell end end STR App.class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = names.last if Hash === names.last with_server_apps options, :msg => "Installing #{dep_class.short_name} packages", :send => [:#{dep_class.short_name}_install, *names] end STR end ## # Creates a ServerApp instance from a deploy info file. def self.from_info_file path, shell=nil shell ||= Sunshine.shell opts = YAML.load shell.call("cat #{path}") opts[:root_path] = opts.delete :path sa_shell = shell.dup sa_shell.env = opts[:env] || Hash.new sa_shell.connect if shell.connected? new opts[:name], sa_shell, opts end app_attr :name, :deploy_name app_attr :root_path, :checkout_path, :current_path app_attr :deploys_path, :log_path, :shared_path, :scripts_path attr_accessor :app, :roles, :scripts, :info, :shell, :crontab attr_writer :pkg_manager ## # Create a server app instance. Supports the following # argument configurations: # # ServerApp.new app_inst, "myserver.com", :roles => :web # ServerApp.new "app_name", shell_inst, options_hash def initialize app, host, options={} @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No status for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info - { :deployed_at => Time.now.to_s, + { :deployed_at => @shell.call("date"), :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path, :sunshine_version => Sunshine::VERSION }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec "#{self.name}:#{self.root_path}", 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's restart script. Raises an exception on failure. # Post-deploy only. def restart! # Permissions are handled by the script, use: :sudo => false run_script! :restart, :sudo => false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the root_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} run_script! name, options, &block rescue false end ## # Runs a script from the root_path. Raises an exception if the status # code is not 0. # Post-deploy only. def run_script! name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script! :status, :sudo => false true rescue CmdError => e return false if e.exit_code == Daemon::STATUS_DOWN_CODE raise e end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Run the app's start script. Raises an exception on failure. # Post-deploy only. def start! options=nil options ||= {} if running? return unless options[:force] stop! end # Permissions are handled by the script, use: :sudo => false run_script! :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's stop script. Raises an exception on failure. # Post-deploy only. def stop! # Permissions are handled by the script, use: :sudo => false run_script! :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} excludes = scm_info.delete :exclude if scm_info[:exclude] excludes = [excludes].flatten.compact excludes.map!{|e| "--exclude #{e}"} repo = RsyncRepo.new code_dir, :flags => excludes repo.checkout_to self.checkout_path, @shell @info[:scm] = scm_info end ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@current_path}/script" end end end diff --git a/test/unit/test_server_app.rb b/test/unit/test_server_app.rb index 0658dcc..3cd8ca3 100644 --- a/test/unit/test_server_app.rb +++ b/test/unit/test_server_app.rb @@ -1,492 +1,491 @@ require 'test_helper' class TestServerApp < Test::Unit::TestCase def setup mock_svn_response @app = mock_app @app.repo.extend MockObject @sa = Sunshine::ServerApp.new @app, mock_remote_shell @sa.extend MockObject use_remote_shell @sa.shell end def test_from_info_file info_data = @sa.get_deploy_info.to_yaml @sa.shell.mock :call, :args => "cat info/path", :return => info_data server_app = Sunshine::ServerApp.from_info_file "info/path", @sa.shell assert_equal @sa.root_path, server_app.root_path assert_equal @sa.checkout_path, server_app.checkout_path assert_equal @sa.current_path, server_app.current_path assert_equal @sa.deploys_path, server_app.deploys_path assert_equal @sa.log_path, server_app.log_path assert_equal @sa.shared_path, server_app.shared_path assert_equal @sa.scripts_path, server_app.scripts_path assert_equal @sa.roles, server_app.roles assert_equal @sa.shell.env, server_app.shell_env assert_equal @sa.name, server_app.name assert_equal @sa.deploy_name, server_app.deploy_name end def test_init default_info = {:ports => {}} assert_equal default_info, @sa.info assert_equal @app, @sa.app assert_equal Hash.new, @sa.scripts assert_equal [:all], @sa.roles end def test_init_roles sa = Sunshine::ServerApp.new @app, "host", :roles => "role1 role2" assert_equal [:role1, :role2], sa.roles sa = Sunshine::ServerApp.new @app, "host", :roles => %w{role3 role4} assert_equal [:role3, :role4], sa.roles end def test_add_shell_paths @sa.add_shell_paths "test/path1", "test/path2" assert_equal "test/path1:test/path2:$PATH", @sa.shell_env['PATH'] @sa.add_shell_paths "test/path3", "test/path4" assert_equal "test/path3:test/path4:test/path1:test/path2:$PATH", @sa.shell_env['PATH'] end def test_app_attr sa_root_path = "local/server_app/path" sa_deploy_name = "local_deploy_name" @sa = Sunshine::ServerApp.new "test", "host", :root_path => sa_root_path, :deploy_name => sa_deploy_name assert_equal sa_root_path, @sa.root_path assert_equal sa_deploy_name, @sa.deploy_name assert_equal "test", @sa.name @sa.app = @app assert_not_equal sa_root_path, @sa.root_path assert_not_equal sa_deploy_name, @sa.deploy_name assert_not_equal "test", @sa.name assert_equal @app.root_path, @sa.root_path assert_equal @app.deploy_name, @sa.deploy_name assert_equal @app.name, @sa.name end def test_build_control_scripts @sa.scripts[:start] << "start" @sa.scripts[:stop] << "stop" @sa.scripts[:custom] << "custom" @sa.build_control_scripts [:start, :stop, :custom].each do |script| content = @sa.make_bash_script script, @sa.scripts[script] assert @sa.method_called?(:write_script, :args => [script, content]) end content = @sa.make_env_bash_script assert @sa.method_called?(:write_script, :args => ["env", content]) content = @sa.make_bash_script :restart, ["#{@sa.app.root_path}/stop", "#{@sa.app.root_path}/start"] assert @sa.method_called?(:write_script, :args => [:restart, content]) end def test_build_deploy_info_file @sa.shell.mock :file?, :return => false args = ["#{@app.scripts_path}/info", @sa.get_deploy_info.to_yaml] @sa.build_deploy_info_file assert @sa.shell.method_called?(:make_file, :args => args) args = ["#{@app.scripts_path}/info", "#{@app.root_path}/info"] assert @sa.shell.method_called?(:symlink, :args => args) end def test_checkout_repo @sa.checkout_repo @app.repo repo = @sa.app.repo args = [@app.checkout_path, @sa.shell] assert repo.method_called?(:checkout_to, :args => args) info = @app.repo.checkout_to @app.checkout_path, @sa.shell assert_equal info, @sa.info[:scm] end def test_deploy_details deploy_details = {:item => "thing"} other_details = {:key => "value"} @sa.shell.mock :call, :args => ["cat #{@sa.root_path}/info"], :return => other_details.to_yaml @sa.instance_variable_set "@deploy_details", deploy_details assert_equal deploy_details, @sa.deploy_details assert_equal other_details, @sa.deploy_details(true) end def test_not_deployed? @sa.mock :deploy_details, :args => [true], :return => nil assert_equal false, @sa.deployed? end def test_server_checked_deployed? @sa.mock :deploy_details, :args => [true], :return => {:deploy_name => @sa.deploy_name} assert_equal true, @sa.deployed? end def test_cached_details_deployed? @sa.instance_variable_set "@deploy_details", :deploy_name => @sa.deploy_name assert_equal true, @sa.deployed? end def test_get_deploy_info + @sa.shell.mock :call, :args => "whoami", :return => "user" + @sa.shell.mock :call, :args => "date", :return => "now" + test_info = { - :deployed_at => Time.now.to_s, - :deployed_as => @sa.shell.call("whoami"), + :deployed_at => "now", + :deployed_as => "user", :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(@app.checkout_path), :name => @sa.name, :env => @sa.shell_env, :roles => @sa.roles, :path => @app.root_path, + :ports => Hash.new, :sunshine_version => Sunshine::VERSION - }.merge @sa.info - - deploy_info = @sa.get_deploy_info + } - deploy_info.each do |key, val| - next if key == :deployed_at - assert_equal test_info[key], val - end + assert_equal test_info, @sa.get_deploy_info end def test_has_all_roles assert @sa.has_roles?([:web, :app, :blarg]) assert @sa.has_roles?([:web, :app, :blarg], true) end def test_has_roles @sa.roles = [:web, :app] assert @sa.has_roles?(:web) assert @sa.has_roles?([:web, :app]) assert [email protected]_roles?([:blarg, :web, :app]) assert @sa.has_roles?([:blarg, :web, :app], true) end def test_install_deps nginx_dep = Sunshine.dependencies.get 'nginx', :prefer => @sa.pkg_manager @sa.install_deps "ruby", nginx_dep assert_dep_install 'ruby', Sunshine::Yum assert_dep_install 'nginx', Sunshine::Yum end def test_install_deps_bad_type nginx_dep = Sunshine.dependencies.get 'nginx' @sa.install_deps nginx_dep, :type => Sunshine::Gem raise "Didn't raise missing dependency when it should have." rescue Sunshine::MissingDependency => e assert_equal "No dependency 'nginx' [Sunshine::Gem]", e.message end def test_make_app_directories @sa.make_app_directories assert_server_call "mkdir -p #{@sa.directories.join(" ")}" end def test_make_bash_script app_script = @sa.make_bash_script "blah", [1,2,3,4] assert_bash_script "blah", [1,2,3,4], app_script end def test_make_env_bash_script @sa.shell.env = {"BLAH" => "blarg", "HOME" => "/home/blah"} test_script = "#!/bin/bash\nenv BLAH=blarg HOME=/home/blah \"$@\"" assert_equal test_script, @sa.make_env_bash_script end def test_rake @sa.rake "db:migrate" assert_dep_install 'rake', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && rake db:migrate" end def test_register_as_deployed Sunshine::AddCommand.extend MockObject unless MockObject === Sunshine::AddCommand @sa.register_as_deployed args = ["#{@app.name}:#{@app.root_path}", {'servers' => [@sa.shell]}] assert Sunshine::AddCommand.method_called?(:exec, :args => args) end def test_remove_old_deploys Sunshine.setup 'max_deploy_versions' => 3 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_server_call "rm -rf #{removed.join(" ")}" end def test_remove_old_deploys_unnecessary Sunshine.setup 'max_deploy_versions' => 5 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.mock :call, :args => ["ls -1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_not_called "rm -rf #{removed.join(" ")}" end def test_revert! deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" last_deploy = "#{@app.deploys_path}/ploy5" assert_server_call "ln -sfT #{last_deploy} #{@app.current_path}" end def test_no_previous_revert! @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" end def test_run_bundler @sa.run_bundler assert_dep_install 'bundler', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && gem bundle" end def test_run_geminstaller @sa.run_geminstaller assert_dep_install 'geminstaller', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && geminstaller -e" end def test_running? set_mock_response_for @sa, 0, "#{@sa.root_path}/status" => [:out, "THE SYSTEM OK!"] assert_equal true, @sa.running? end def test_not_running? set_mock_response_for @sa, 13, "#{@sa.root_path}/status" => [:err, "THE SYSTEM IS DOWN!"] assert_equal false, @sa.running? end def test_errored_running? set_mock_response_for @sa, 1, "#{@sa.root_path}/status" => [:err, "KABLAM!"] assert_raises Sunshine::CmdError do @sa.running? end end def test_sass sass_files = %w{file1 file2 file3} @sa.sass(*sass_files) assert_dep_install 'haml', @sa.pkg_manager sass_files.each do |file| sass_file = "public/stylesheets/sass/#{file}.sass" css_file = "public/stylesheets/#{file}.css" assert_server_call \ "cd #{@app.checkout_path} && sass #{sass_file} #{css_file}" end end def test_shell_env assert_equal @sa.shell.env, @sa.shell_env end def test_symlink_current_dir @sa.symlink_current_dir assert_server_call "ln -sfT #{@app.checkout_path} #{@app.current_path}" end def test_upload_codebase @sa.shell.mock(:upload) @sa.upload_codebase "tmp/thing/", :test_scm => "info" assert_equal({:test_scm => "info"} , @sa.info[:scm]) assert @sa.shell.method_called?( :upload, :args => ["tmp/thing/", @sa.checkout_path, {:flags => ["--exclude .svn/","--exclude .git/"]}]) end def test_upload_codebase_with_exclude @sa.shell.mock(:upload) @sa.upload_codebase "tmp/thing/", :test_scm => "info", :exclude => "bad/path/" assert_equal({:test_scm => "info"} , @sa.info[:scm]) assert @sa.shell.method_called?( :upload, :args => ["tmp/thing/", @sa.checkout_path, {:flags => ["--exclude bad/path/", "--exclude .svn/", "--exclude .git/"]}]) end def test_upload_codebase_with_excludes @sa.shell.mock(:upload) @sa.upload_codebase "tmp/thing/", :test_scm => "info", :exclude => ["bad/path/", "other/exclude/"] assert_equal({:test_scm => "info"} , @sa.info[:scm]) assert @sa.shell.method_called?( :upload, :args => ["tmp/thing/", @sa.checkout_path, {:flags => ["--exclude bad/path/", "--exclude other/exclude/", "--exclude .svn/", "--exclude .git/"]}]) end def test_write_script @sa.shell.mock :file?, :return => false @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert @sa.shell.method_called?(:make_file, :args => args) end def test_symlink_scripts_to_root @sa.shell.mock :call, :args => ["ls -1 #{@sa.scripts_path}"], :return => "script_name\n" args = ["#{@app.scripts_path}/script_name", "#{@app.root_path}/script_name"] @sa.symlink_scripts_to_root assert @sa.shell.method_called?(:symlink, :args => args) end def test_write_script_existing @sa.shell.mock :file?, :return => true @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert [email protected]_called?(:make_file, :args => args) end end
jcasts/sunshine
0980c5f67d9e8d2ae3e2265c7dcf4f24b4efea8d
removed the (hopefully) last reference to healthcheck
diff --git a/README.txt b/README.txt index ead9837..da1d0eb 100644 --- a/README.txt +++ b/README.txt @@ -1,633 +1,632 @@ = Sunshine http://github.com/yaksnrainbows/sunshine http://betalabs.yellowpages.com/ == Description Sunshine is a framework for rack and rails application deployment. This gem was made possible by the sponsoring of AT&T Interactive (http://attinteractive.com). == Setup and Usage Installing sunshine: $ gem install sunshine Call sunshine to create the config file: $ sunshine Missing config file was created for you: /Users/jsmith/.sunshine --- auto_dependencies: true deploy_env: :development exception_behavior: :revert exclude_paths: [] interactive: true level: info max_deploy_versions: 5 remote_checkouts: false timeout: 300 sigint_behavior: :revert web_directory: /srv/http You can either use sunshine by requiring the gem in your script, such as in a rakefile (which is more common): $ rake sunshine:deploy env=qa Or you can also call built-in sunshine commands: $ sunshine run my_deploy.rb -e qa == Rake Deploy Tasks in 5 Minutes Although Sunshine comes with it's own bundle of commands, they should be used to control deployed apps on remote servers in instances where deploy information (e.g. your deploy yaml file) is unavailable. Their purpose is to query a server where Sunshine apps have been deployed and have a nominal amount of information and control over them. Sunshine control commands are run on a per-server basis. Most of the time, you'll want to control the deploy on a per-app basis. You have the deploy information and you need to do things involving that specific deploy. Rake tasks are great for that, and Sunshine comes with a template rake file that you can modify to fit your needs. You can copy the template rake file to rake/ by running: $ sunshine --rakefile rake/. If you open the file, you'll see a variety of tasks that handle deployment, to -application start/stop/restart-ing, to health checks. Most likely, the two tasks +application start/stop/restart-ing, to status checks. Most likely, the two tasks you'll need to update are the :app (for instantiation) and the :deploy tasks. First off, if you're using rails, you'll probably want to update "task :app" to "task :app => :environment" in order to get all the rails environment goodness. You'll also want to make sure that the @app object gets instantiated with the proper hash value or yaml file. Second, you need to update your :deploy task. Add whatever instructions you need to the @app.deploy block. Here's a sample of completed :app and :deploy tasks: namespace :sunshine do desc "Instantiate Sunshine" task :app => :environment do Sunshine.setup 'sudo' => 'app_user', 'web_directory' => '/var/www', 'deploy_env' => Rails.environment @app = Sunshine::App.new \ :repo => Sunshine::SvnRepo.new("svn://subversion/repo/tags/release001"), :remote_shells => 'user@my_server.com' end desc "Deploy the app" task :deploy => :app do Sunshine.setup 'trace' => true @app.deploy do |app| rainbows = Sunshine::Rainbows.new app, :port => 5001 nginx = Sunshine::Nginx.new app, :point_to => rainbows app.run_geminstaller rainbows.setup nginx.setup end end ... end And that's it! Try running your Sunshine rake tasks! rake sunshine:app # Instantiate Sunshine rake sunshine:deploy # Deploy the app rake sunshine:info # Get deployed app info rake sunshine:restart # Run the remote restart script rake sunshine:start # Run the remote start script rake sunshine:status # Check if the deployed app is running rake sunshine:stop # Run the remote stop script == Understanding Deployment === The App Class Writing a Sunshine script is easy. App objects are the core of Sunshine deployment. The Sunshine paradygm is to construct an app object, and run custom deploy code by passing a block to its deploy method: options = { :name => 'myapp', :repo => {:type => :svn, :url => 'svn://blah...'}, :root_path => '/usr/local/myapp' } options[:remote_shells] = case Sunshine.deploy_env when 'qa' ['qa1.svr.com', 'qa2.svr.com'] else 'localhost' end Sunshine::App.deploy(options) do |app| app_server = Sunshine::Rainbows.new(app) app_server.setup Sunshine::Nginx.new(app, :point_to => app_server).setup end An App holds information about where to deploy an application to and how to deploy it, as well as many convenience methods to setup and manipulate the deployment process. Most of these methods support passing remote shell find options: app.rake 'db:migrate', :role => :db app.deploy :host => 'server1.com' See Sunshine::App#find for more information. === Working With Environments Environment specific setups can be accomplished in a few ways. The most obvious way is to create a different script for each environment. You can also define the App's constructor hash on a per-environment basis (as seen above), which gives you lots of control. That said, the App class also provides a mechanism for environment handling using configuration files. The App::new methods support passing a path to a yaml config file: app = Sunshine::App.new("path/to/config.yml") app.deploy{|app| Sunshine::Rainbows.new(app).setup } The yaml file can also be any IO stream who's output will parse to yaml. This can be ueful for passing the file's DATA and keep all the deploy information in one place: # The following two lines are equivalent: app = Sunshine::App.new app = Sunshine::App.new Sunshine::DATA app.deploy{|app| Sunshine::Rainbows.new(app).setup } __END__ # yaml for app goes here... Yaml files are read on a deploy-environment basis so its format reflects this: --- # Default is always inherited by all environments :default : :name : app_name :repo : :type : svn :url : svn://subversion/app_name/branches/continuous_integration :root_path : /usr/local/app_name :remote_shells : - - localhost - :roles : web db app # Setup for qa environment :qa : :repo : :type : svn :url : svn://subversion/app_name/tags/release_0001 :remote_shells : - qa1.servers.com - qa2.servers.com # Prod inherits top level values from :qa :prod : :inherits : :qa :remote_shells : - prod1.servers.com - prod2.servers.com In this example, :prod inherits top level values from :qa (only :repo in this instance). The :inherits key also supports an array as its value. All environments also inherit from the :default environment. The :default is also used if the app's deploy_env is not found in the config. Finally, yaml configs get parsed by erb, exposing any options passed to the App's constuctor, along with the deploy environment, letting your write configs such as: # deploy.rb app = App.new "deploy.yml", :name => "my_app", :deploy_name => "release_001" # deploy.yml --- :default : :repo : :type : svn :url : svn://subversion/<%= name %>/tags/<%= deploy_name %> :remote_shells : - <%= deploy_env %>1.<%= name %>.domain.com - <%= deploy_env %>2.<%= name %>.domain.com See Sunshine::App for more information. == Servers === Basics Sunshine lets you install and setup server applications to run your app on. The typical approach to serving ruby applications is to run Nginx or Apache as a load balancer in front of a backend such as Thin, or Mongrels. Using Sunshine, this is most commonly defined as a part of the deploy process: app.deploy do |app| backend = Sunshine::Thin.new app, :port => 5000 nginx = Sunshine::Nginx.new app, :point_to => backend backend.setup nginx.setup end When a new Server is instantiated and its setup method is run, it is added to the app's control scripts. This means that when the deploy is complete, those servers can be controlled by the app's start/stop/restart/status methods. === Load Balancing Since frontend servers support load balancing, you can also point them to server clusters: backend = Sunshine::Thin.new_cluster 10, app, :port => 5000 nginx = Sunshine::Nginx.new app, :point_to => backend backend.setup nginx.setup In this instance, Nginx will know to forward requests to the cluster of Thin servers created. You could do this more explicitely with the following: backend = Array.new 5000.upto(5009) do |port| thin = Sunshine::Thin.new app, :port => port, :name => "thin.#{port}" thin.setup backend << thin end Sunshine::Nginx.new app, :point_to => backend === Phusion Passenger If you are running a lower traffic application, Phusion Passenger is available for both Nginx and Apache. Passenger will be used by default if no backend is specified. You could have an Nginx Passenger setup on port 80 with a single line: Sunshine::Nginx.new(app).setup Easy! Servers let you do much more configuration with log files, config files, etc. For more information, see Sunshine::Server. == Dependencies Sunshine has simple, basic dependency support, and relies mostly on preexisting package manager tools such as apt, yum, or rubygems. Dependencies or packages can be defined independently, or as a part of a dependency tree (see Sunshine::DependencyLib). Sunshine has its own internal dependency tree which can be modified but users can also create their own. === User Dependencies The most common way of using dependencies is through ServerApp: server_app.apt_install 'postgresql', 'libxslt' server_app.gem_install 'json', :version => '>=1.0.0' This should be plenty for most users. You can however create simple standalone package definitions: postgresql = Sunshine::Apt.new('postgresql') postgresql.install! :call => server_app.shell You can imagine how this would be useful to do server configuration with Sunshine: server = RemoteShell.new "[email protected]" server.connect %w{postgresql libxslt ruby-full rubygems}.each do |dep_name| Sunshine::Apt.new(dep_name).install! :call => server end Warning: If the :call options isn't specified, the dependency will attempt to install on the local system. See Sunshine::Dependency for more information. === Internal Sunshine Dependencies (advanced) Sunshine's default dependencies are defined in Sunshine.dependencies and can be overridden as needed: Sunshine.dependencies.get 'rubygems', :type => Sunshine::Yum #=> <Sunshine::Yum ... version='1.3.5' > # Not what you want? Replace it: Sunshine.dependencies.yum 'rubygems', :version => '1.3.2' Any dependencies added or modified in Sunshine.dependencies are used as a part of the internal Sunshine workings. Also to note: ServerApp#pkg_manager is crucial in defining which dependency to use. By default, a server_app's package manager will be either Yum or Apt depending on availability. That can be overridden with something like: server_app.pkg_manager = Sunshine::Yum An array can also be given and the server_app will attempt to install available dependencies according to that type order: server_app.pkg_manager = [Sunshine::Tpkg, Sunshine::Yum] In this instance, if no Tpkg dependency was defined in Sunshine.dependencies, the server_app will look for a Yum dependency. If you want to ensure all your server_apps use the same dependency definition, you may consider: Sunshine.dependencies.yum 'rubygems', :version => '1.3.2' Sunshine.dependencies.apt 'rubygems', :version => '1.3.2' # ... and so on Note: You can disable automatic dependency installation by setting Sunshine's auto_dependencies config to false. == Using Permissions In order to deploy applications successfully, it's important to know how, where, and when to use permissions in Sunshine deploy scripts. === The Shell Class The primary handler of permissions is the Sunshine::Shell class. Since all commands are run through a Shell object, it naturally handles permission changes. The following will create a new remote shell which is logged into as user "bob" but will use root to perform all calls: # The following two lines are equivalent: svr = Sunshine::RemoteShell.new "[email protected]", :sudo => true svr = Sunshine::RemoteShell.new "myserver.com", :user => "bob" :sudo => true Sudo can also be set after instantiation. Let's change the permissions back to its default: svr.sudo = nil You can of course also run single commands with a one-off sudo setting: svr.call "whoami", :sudo => true #=> "root" Shell sudo values are important! Depending on what the value of shell.sudo is, behavior will change dramatically: - sudo = true -> sudo -H command - sudo = 'root' -> sudo -H -u root command - sudo = 'usr' -> sudo -H -u usr command - sudo = false -> enforce never using sudo - sudo = nil -> passthrough (don't care) Here are a few examples of these values being used: svr = Sunshine::RemoteShell.new "[email protected]", :sudo => true svr.call "whoami" #=> root svr.call "whoami", :sudo => "usr" #=> usr svr.call "whoami", :sudo => nil #=> root svr.call "whoami", :sudo => false #=> bob These values are crucial as other Sunshine classes have and pass around other sudo requirements/values to shell objects. === Who Affects Sudo There are 3 main places to beware of how sudo gets used. ==== Apps The first, most obvious place is the App class: app.sudo = "bob" app.server_apps.first.shell.sudo #=> "bob" app.sudo = true app.server_apps.first.shell.sudo #=> true Since the App class effectively owns the shells it uses, setting sudo on the App will permanently change the sudo value of its shells. Note: You may notice that you can set a sudo config value on the Sunshine module. This is used for the default value of Sunshine::App#sudo and is passed along to an app's shells on instantiation. ==== Servers Because of how unix works with servers and ports, it's not uncommon to have to run start/stop/restart server commands with upgraded permissions. This is true for Apache and Nginx on ports below 1024. Due to this, servers automatically try to adjust their permissions to run their commands correctly. Since servers should run their commands consistantly, the only way to affect their sudo value is on a server instance basis: server = Nginx.new app, :sudo => nil # let the shell handle sudo However, the above will most likely cause Nginx's start command to fail if shell permissions don't allow running root processes. Note: Servers will ONLY touch permissions if their port is smaller than 1024. ==== Dependencies Since Sunshine also deals with installing dependencies, the Dependency class and its children all have a class level sudo setting which is set to true by default. This means that any dependency will by default run its commands using sudo: dep = Sunshine::Apt.new "libdvdread" dep.install! :call => shell #=> sudo -H apt-get install libdvdread This can be changed on the class level: shell.sudo = "usr" Sunshine::Apt.sudo = nil # let the shell handle sudo dep.install! :call => shell #=> sudo -H -u usr apt-get install libdvdread It can also be set on an individual basis: dep.install! :call => shell, :sudo => nil == Sunshine Configuration Aside from passing the sunshine command options, Sunshine can be configured both in the deploy script by calling Sunshine.setup and globally in the ~/.sunshine file. The following is a list of supported config keys: 'auto_dependencies' -> Check and install missing deploy dependencies; defaults to true. 'deploy_env' -> The default deploy environment to use; defaults to :development. 'exception_behavior' -> The behavior called when an exception is raised during a deploy; defaults to :revert. 'exclude_paths' -> Paths to exclude in the checkout when deploying code with via rsync; defaults to empty Array. 'interactive' -> Automate calls; fail instead of prompting the user; defaults to false. 'level' -> Logger's debug level; defaults to 'info'. 'max_deploy_versions' -> The maximum number of deploys to keep on a server; defaults to 5. 'remote_checkouts' -> Use remote servers to checkout the codebase; defaults to false. 'require' -> Require external ruby libs or gems; defaults to nil. 'timeout' -> The amount of time in seconds for shells to wait with no incoming data before timing out; defaults to 300. 'sigint_behavior' -> The behavior called when a SIGINT is received during a deploy; defaults to :revert. 'trace' -> Show detailed output messages; defaults to false. 'web_directory' -> Path to where apps should be deployed to; defaults to '/srv/http'. == Deployed Application Control Sunshine has a variety of commands that allow simple control of remote or locally deployed applications. These include start, stop, restart actions to be taken application-wide, as well as querying for the -health and state of the app: +state of the app: Examples: sunshine run deploy_script.rb sunshine restart myapp -r [email protected],[email protected] - sunshine list myapp myotherapp --health -r [email protected] - sunshine list myapp --status + sunshine list myapp myotherapp --status -r [email protected] The Sunshine commands are as follows: add Register an app with sunshine list Display deployed apps restart Restart a deployed app rm Unregister an app with sunshine run Run a Sunshine ruby file script Run an app script start Start a deployed app stop Stop a deployed app For more help on sunshine commands, use 'sunshine COMMAND --help'. For more information about control scripts, see the Sunshine::App#build_control_scripts method. === Remote Scripts and Permissions: Important: Applications are deployed on a per-user basis. When calling commands that require superuser permissions (e.g. calling restart on an app that runs on Apache, port 80), make sure that the user used to log in has sudo permissions. Example: I've deployed an application logged in as 'superuser' but for a 'peon' user with a lower permission level using something like: Sunshine.setup 'sudo' => 'peon' @app = Sunshine::App.new :remote_shells => '[email protected]' Using any of the following will fail to return since 'peon' has no sudo priviledges: $ sunshine restart app -r [email protected] $ sunshine restart app -r [email protected] -S Yet, if you only log in as 'superuser' the app will not be found as it will be looking for apps deployed and run for 'superuser', hence this is wrong too: $ sunshine restart app -r [email protected] To run the script correctly, use the same setup used for your deploy, in this case: $ sunshine restart app -r [email protected] -S peon This is true for the following commands: $ sunshine list --status $ sunshine restart $ sunshine script $ sunshine start $ sunshine stop == Licence (The MIT License) Copyright (c) 2010 At&t Interactive Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
jcasts/sunshine
fa6691d86be028ae2211315d2b1d07c52dd1d14f
Move the default config creation out, so that it can be stubbed.
diff --git a/lib/sunshine.rb b/lib/sunshine.rb index f8db0e0..0f4b7a8 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,439 +1,441 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'yaml' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' require 'irb' # Turn off EOF tracking to be able to prompt on deploy exceptions. HighLine.track_eof = false ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. VERSION = '1.3.0' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { 'auto_dependencies' => true, 'deploy_env' => :development, 'exception_behavior' => :revert, 'exclude_paths' => [], 'interactive' => true, 'level' => 'info', 'max_deploy_versions' => 5, 'remote_checkouts' => false, 'timeout' => 300, 'sigint_behavior' => :revert, 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end ## # Defines what to do when deploy raises an exception. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.exception_behavior @config['exception_behavior'] end ## # Array of paths or globs that should be excluded from the checkout. # Does not work with remote_checkouts enabled. def self.exclude_paths @config['exclude_paths'] end ## # Should sunshine ever ask for user input? True by default. # Overridden in the config or with the -a option. def self.interactive? @config['interactive'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end ## # Defines what to do when sigint is sent during deploys. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.sigint_behavior @config['sigint_behavior'] end ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config - unless File.file? USER_CONFIG_FILE - File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} - - msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" - msg << DEFAULT_CONFIG.to_yaml - - self.exit 1, msg - end - + create_default_config! load_config_file USER_CONFIG_FILE @config['deploy_env'] = ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] || @config['deploy_env'] @config end + def self.create_default_config! + unless File.file? USER_CONFIG_FILE + File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} + + msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" + msg << DEFAULT_CONFIG.to_yaml + + self.exit 1, msg + end + end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset TrapStack.trap_signal :INT do |msg| $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" logger.info :INT, msg end TrapStack.add_trap "Disconnecting all remote shells." do RemoteShell.disconnect_all end require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' require 'sunshine/trap_stack' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies'
jcasts/sunshine
b3337b37506ff92be1edfa637b7c416a95795ede
Healthcheck wasn't dead enough.
diff --git a/lib/commands/list.rb b/lib/commands/list.rb index 4efb3ca..53b14d1 100644 --- a/lib/commands/list.rb +++ b/lib/commands/list.rb @@ -1,327 +1,303 @@ module Sunshine ## # List and perform simple state actions on lists of sunshine apps. # # Usage: sunshine list [options] app_name [more names...] # # Arguments: # app_name Name of an application to list. # # Options: # -s, --status Check if an app is running. # -d, --details Get details about the deployed apps. - # -h, --health [STATUS] Set or get the healthcheck status. - # (enable, disable, remove) # -f, --format FORMAT Set the output format (txt, yml, json) # -u, --user USER User to use for remote login. Use with -r # -r, --remote svr1,svr2 Run on one or more remote servers. # -S, --sudo Run remote commands using sudo or sudo -u USER # -v, --verbose Run in verbose mode. class ListCommand < DefaultCommand ## # Takes an array and a hash, runs the command and returns: # true: success # false: failed # exitcode: # code == 0: success # code != 0: failed # and optionally an accompanying message. def self.exec names, config action = config['return'] || :exist? args = config[action.to_s] || [] args = [args, names].flatten output = exec_each_server config do |shell| new(shell).send(action, *args) end return output end ## # Executes common list functionality for each deploy server. def self.exec_each_server config shells = config['servers'] format = config['format'] responses = {} success = true shells.each do |shell| shell.with_session do begin state, response = yield(shell) rescue => e state = false response = "#{e.class}: #{e.message}\n#{e.backtrace.join("\n")}" end host = shell.host success = state if success responses[host] = build_response state, response end end output = format ? self.send(format, responses) : responses return success, output end ## # Formats response as text output: # ------------------ # subdomain.host.com # ------------------ # app_name: running def self.txt_format res_hash str_out = "" res_hash.each do |host, response| separator = "-" * host.length host_status = if Hash === response[:data] apps_status = response[:data].map do |app_name, status| "#{app_name}: #{status[:data]}\n" end apps_status.join("\n") else response[:data] end str_out << "\n" str_out << [separator, host, separator].join("\n") str_out << "\n" str_out << host_status str_out << "\n" end str_out end ## # Formats response as yaml: def self.yml_format res_hash res_hash.to_yaml end ## # Formats response as json: def self.json_format res_hash res_hash.to_json end attr_accessor :app_list, :shell def initialize shell @shell = shell @app_list = self.class.load_list @shell end ## # Reads and returns the specified apps' info file. # Returns a response hash (see ListCommand#each_app). def details(*app_names) each_app(*app_names) do |server_app| "\n#{server_app.deploy_details.to_yaml}" end end ## # Returns the path of specified apps. # Returns a response hash (see ListCommand#each_app). def exist?(*app_names) each_app(*app_names) do |server_app| server_app.root_path end end - ## - # Get or set the healthcheck state. - # Returns a response hash (see ListCommand#each_app). - - def health(*app_names) - action = app_names.delete_at(0) if Symbol === app_names.first - - each_app(*app_names) do |server_app| - server_app.health.send action if action - server_app.health.status - end - end - - ## # Checks if the apps' pids are present. # Returns a response hash (see ListCommand#each_app). def status(*app_names) each_app(*app_names) do |server_app| begin server_app.status rescue => e e.message end end end ## # Runs a command and returns the status for each app_name: # status_after_command 'restart', ['app1', 'app2'] def status_after_command cmd, app_names, options=nil each_app(*app_names) do |server_app| yield(server_app) if block_given? begin server_app.run_script! cmd, options server_app.status.to_s rescue CmdError => e raise "Failed running #{cmd}: #{server_app.status rescue :not_found}" end end end # Do something with each server app and build a response hash: # each_app do |server_app| # ... # end # # Restrict it to a set of apps if they are present on the server: # each_app('app1', 'app2') do |server_app| # ... # end # # Returns a response hash: # {"app_name" => {:success => true, :data => "somedata"} ...} def each_app(*app_names) app_names = @app_list.keys if app_names.empty? response_for_each(*app_names) do |name| path = @app_list[name] raise "Application not found." unless path server_app = ServerApp.new name, @shell, :root_path => path yield(server_app) if block_given? end end ## # Builds a response object for each item passed and returns # the result of the passed block as its data value. def response_for_each(*items) response = {} success = true items.each do |item| begin data = yield(item) if block_given? response[item] = self.class.build_response true, data rescue => e success = false response[item] = self.class.build_response false, e.message end end [success, response] end ## # Builds a standard response entry: # {:success => true, :data => "somedata"} def self.build_response success, data=nil {:success => success, :data => data} end ## # Load the app list yaml file from the server. def self.load_list server yml_list = server.call "cat #{Sunshine::APP_LIST_PATH} || echo" list = YAML.load yml_list list = {} unless Hash === list list end ## # Write the app list hash to the remote server. def self.save_list list, server path = server.expand_path Sunshine::APP_LIST_PATH server.make_file path, list.to_yaml end ## # Parses the argv passed to the command def self.parse_args argv parse_remote_args(argv) do |opt, options| opt.banner = <<-EOF Usage: #{opt.program_name} list [options] app_name [more names...] Arguments: app_name Name of an application to list. EOF opt.on('-s', '--status', 'Check if an app is running.') do options['return'] = :status end opt.on('-d', '--details', 'Get details about the deployed apps.') do options['return'] = :details end - - vals = [:enable, :disable, :remove] - desc = "Set or get the healthcheck status. (#{vals.join(", ")})" - - opt.on('-h', '--health [STATUS]', vals, desc) do |status| - options['health'] = status.to_sym if status - options['return'] = :health - end end end end end diff --git a/lib/sunshine.rb b/lib/sunshine.rb index e59ca2a..f8db0e0 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,441 +1,439 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'yaml' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' require 'irb' # Turn off EOF tracking to be able to prompt on deploy exceptions. HighLine.track_eof = false ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. VERSION = '1.3.0' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { 'auto_dependencies' => true, 'deploy_env' => :development, 'exception_behavior' => :revert, 'exclude_paths' => [], 'interactive' => true, 'level' => 'info', 'max_deploy_versions' => 5, 'remote_checkouts' => false, 'timeout' => 300, 'sigint_behavior' => :revert, 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end ## # Defines what to do when deploy raises an exception. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.exception_behavior @config['exception_behavior'] end ## # Array of paths or globs that should be excluded from the checkout. # Does not work with remote_checkouts enabled. def self.exclude_paths @config['exclude_paths'] end ## # Should sunshine ever ask for user input? True by default. # Overridden in the config or with the -a option. def self.interactive? @config['interactive'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end ## # Defines what to do when sigint is sent during deploys. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.sigint_behavior @config['sigint_behavior'] end ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config unless File.file? USER_CONFIG_FILE File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" msg << DEFAULT_CONFIG.to_yaml self.exit 1, msg end load_config_file USER_CONFIG_FILE @config['deploy_env'] = ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] || @config['deploy_env'] @config end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset TrapStack.trap_signal :INT do |msg| $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" logger.info :INT, msg end TrapStack.add_trap "Disconnecting all remote shells." do RemoteShell.disconnect_all end require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' require 'sunshine/trap_stack' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' - require 'sunshine/healthcheck' - require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies'
jcasts/sunshine
1e54d76d7bf038c1a4f303a6edb1e156758f6d86
Allow criminals to deploy from, say, "#{Dir.pwd}/.git".
diff --git a/lib/sunshine/repos/git_repo.rb b/lib/sunshine/repos/git_repo.rb index bf64229..6b85131 100644 --- a/lib/sunshine/repos/git_repo.rb +++ b/lib/sunshine/repos/git_repo.rb @@ -1,122 +1,122 @@ module Sunshine ## # Simple wrapper for git repos. Constructor supports :tree option to # specify either a branch or tree-ish to checkout: # git = GitRepo.new "git://mygitrepo.git", :tree => "tags/release001" class GitRepo < Repo LOG_FORMAT = [ ":revision: %H", ":committer: %cn", ":date: %cd", ":message: %s", ":refs: '%d'", ":tree: %t" ].join("%n") ## # Check if this is an svn repo def self.valid? path="." File.exist? File.join(path, ".git") end ## # Get the repo info from the path to a checked out git repo def self.get_info path=".", shell=nil shell ||= Sunshine.shell info = YAML.load git_log(path, shell) info[:date] = Time.parse info[:date] info[:branch] = parse_branch info info[:url] = git_origin path, shell info rescue => e raise RepoError, e end ## # Returns the git logs for a path, formatted as yaml. def self.git_log path, shell git_options = "-1 --no-color --format=\"#{LOG_FORMAT}\"" shell.call "cd #{path} && git log #{git_options}" end ## # Returns the fetch origin of the current git repo. Returns the path to a # public git repo by default: # GitRepo.git_origin "/some/path", Sunshine.shell # #=> "git://myrepo/path/to/repo.git" # GitRepo.git_origin "/some/path", Sunshine.shell, false # #=> "user@myrepo:path/to/repo.git" def self.git_origin path, shell, public_url=true get_origin_cmd = "cd #{path} && git remote -v | grep \\(fetch\\)" origin = shell.call get_origin_cmd origin = origin.split(/\t|\s/)[1] origin = make_public_url origin if public_url origin end ## # Returns the git url for a public checkout def self.make_public_url git_url url, protocol = git_url.split("://").reverse url, user = url.split("@").reverse url.gsub!(":", "/") if !protocol "git://#{url}" end attr_accessor :tree def initialize url, options={} super @tree = options[:branch] || options[:tree] || "master" end def do_checkout path, shell cmd = "cd #{path} && git clone #{@url} #{scm_flags} . && "+ "git checkout #{@tree}" shell.call cmd end - NAME_MATCH = /\/([^\/]+)\.git/ + NAME_MATCH = /\/([^\/]+)(\/?)\.git/ def name @url.match(NAME_MATCH)[1] rescue raise RepoError, "Git url must match #{NAME_MATCH.inspect}" end private def self.parse_branch response refs = response[:refs] return response[:tree] unless refs && !refs.strip.empty? ref_names = refs.delete('()').gsub('/', '_') ref_names.split(',').last.strip end end end
jcasts/sunshine
113d4ba40be704282b7c690ad8b0def7223dc539
moved scripts_path to current_path/script to integrate with rails
diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index 9676d09..30572f9 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -621,599 +621,599 @@ module Sunshine def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. Supports all App#find options. # See Sunshine::ServerApp for more information. def each options=nil, &block server_apps = find options server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Supports all App#find options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. # Supports all App#find options. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Sunshine::Yum # # Package managers are typically detected automatically by each # individual server_apps. # Supports all App#find options. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. # Supports all App#find options. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. # Supports all App#find options. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app # Supports all App#find options. def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. # Supports all App#find options. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Run the restart script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def restart! options=nil with_server_apps options, :msg => "Running restart script", :send => :restart! end ## # Runs bundler on deploy servers. Supports all App#find options. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] end ## # Runs GemInstaller on deploy servers. Supports all App#find options. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run the given script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def run_script! name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script!, name, options] end ## # Run a sass task on any or all deploy servers. # Supports all App#find options. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. # Supports all App#find options. def shell_env env_hash=nil, options=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps options, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Run the start script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def start! options=nil with_server_apps options, :msg => "Running start script", :send => [:start!, options] end ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. Supports all App#find options. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end ## # Run the stop script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def stop! options=nil with_server_apps options, :msg => "Running stop script", :send => :stop! end ## # Use sudo on all the app's deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. # Supports all App#find options. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! # Supports all App#find options. def threaded_each options=nil, &block mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end # Supports all App#find options. def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here # end # # Note: App#with_server_apps calls App#with_session. If you do not need # or want a server connection you can pass :no_session. def with_server_apps search_options, options={} options = search_options.merge options if Hash === search_options message = options[:msg] method = options[:no_threads] ? :each : :threaded_each auto_session = !options[:no_session] block = lambda do |*| send(method, search_options) do |server_app| if block_given? yield(server_app) elsif options[:send] server_app.send(*options[:send]) end end end msg_block = lambda do |*| if message Sunshine.logger.info(:app, message, &block) else block.call end end auto_session ? with_session(&msg_block) : msg_block.call end ## # Runs block ensuring a connection to remote_shells. # Connecting and disconnecting will be ignored if a session # already exists. Supports all App#find options. # # Ensures that servers are disconnected after the block is run # if servers were not previously connected. def with_session options=nil with_filter options do prev_connection = connected? begin connect unless prev_connection yield self ensure disconnect unless prev_connection end end end private ## # Set all the app paths based on the root deploy path. def set_deploy_paths path @root_path = path || File.join(Sunshine.web_directory, @name) @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" - @scripts_path = "#{@checkout_path}/sunshine_scripts" + @scripts_path = "#{@current_path}/script" end ## # Set the app's deploy servers: # server_apps_from_config "some_server" # #=> [<ServerApp @host="some_server"...>] # # server_apps_from_config ["svr1", "svr2", "svr3"] # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] # # remote_shells = [["svr1", {:roles => "web db app"}], "svr2", "svr3"] # server_apps_from_config remote_shells # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] def server_apps_from_config shells shells = [*shells].compact shells.map{|shell| ServerApp.new(*[self,*shell]) } end ## # Set the app's repo: # repo_from_config SvnRepo.new("myurl") # repo_from_config :type => :svn, :url => "myurl" def repo_from_config repo_def case repo_def when Sunshine::Repo repo_def when Hash Sunshine::Repo.new_of_type repo_def[:type], repo_def[:url], repo_def else Sunshine::Repo.detect Sunshine::PATH end end ## # Load a yml config file, parses it with erb and resolves deploy env # inheritance. def config_from_file config_file, erb_binding=binding, env=@deploy_env return {} unless config_file config_data = YAML.load build_erb(config_file, erb_binding) load_config_for config_data, env end ## # Loads an app yml config file, gets the default config # and the current deploy env and returns a merged config hash. def load_config_for config_hash, env return {} unless config_hash deploy_env_config = (config_hash[env] || {}).dup deploy_env_config[:inherits] ||= [] deploy_env_config[:inherits].unshift(:default) if :default != env && config_hash[:default] merge_config_inheritance deploy_env_config, config_hash end ## # Recursively merges config hashes based on the value at :inherits def merge_config_inheritance main_config, all_configs new_config = {} parents = [*main_config[:inherits]].compact parents.each do |config_name| parent = all_configs[config_name] parent = merge_config_inheritance parent, all_configs new_config = new_config.merge parent end new_config.merge main_config # Two merges important for inheritance order end end end diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index a0a1c5a..68c6667 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -189,517 +189,517 @@ module Sunshine # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path, :sunshine_version => Sunshine::VERSION }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec "#{self.name}:#{self.root_path}", 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's restart script. Raises an exception on failure. # Post-deploy only. def restart! # Permissions are handled by the script, use: :sudo => false run_script! :restart, :sudo => false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the root_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} run_script! name, options, &block rescue false end ## # Runs a script from the root_path. Raises an exception if the status # code is not 0. # Post-deploy only. def run_script! name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script! :status, :sudo => false true rescue CmdError => e return false if e.exit_code == Daemon::STATUS_DOWN_CODE raise e end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Run the app's start script. Raises an exception on failure. # Post-deploy only. def start! options=nil options ||= {} if running? return unless options[:force] stop! end # Permissions are handled by the script, use: :sudo => false run_script! :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's stop script. Raises an exception on failure. # Post-deploy only. def stop! # Permissions are handled by the script, use: :sudo => false run_script! :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} excludes = scm_info.delete :exclude if scm_info[:exclude] excludes = [excludes].flatten.compact excludes.map!{|e| "--exclude #{e}"} repo = RsyncRepo.new code_dir, :flags => excludes repo.checkout_to self.checkout_path, @shell @info[:scm] = scm_info end ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" - @scripts_path = "#{@checkout_path}/sunshine_scripts" + @scripts_path = "#{@current_path}/script" end end end
jcasts/sunshine
52813263e5a206f6c4734eea9d3ac3939d063f05
fixed register_as_deployed test
diff --git a/test/unit/test_server_app.rb b/test/unit/test_server_app.rb index 70d1def..0658dcc 100644 --- a/test/unit/test_server_app.rb +++ b/test/unit/test_server_app.rb @@ -1,492 +1,492 @@ require 'test_helper' class TestServerApp < Test::Unit::TestCase def setup mock_svn_response @app = mock_app @app.repo.extend MockObject @sa = Sunshine::ServerApp.new @app, mock_remote_shell @sa.extend MockObject use_remote_shell @sa.shell end def test_from_info_file info_data = @sa.get_deploy_info.to_yaml @sa.shell.mock :call, :args => "cat info/path", :return => info_data server_app = Sunshine::ServerApp.from_info_file "info/path", @sa.shell assert_equal @sa.root_path, server_app.root_path assert_equal @sa.checkout_path, server_app.checkout_path assert_equal @sa.current_path, server_app.current_path assert_equal @sa.deploys_path, server_app.deploys_path assert_equal @sa.log_path, server_app.log_path assert_equal @sa.shared_path, server_app.shared_path assert_equal @sa.scripts_path, server_app.scripts_path assert_equal @sa.roles, server_app.roles assert_equal @sa.shell.env, server_app.shell_env assert_equal @sa.name, server_app.name assert_equal @sa.deploy_name, server_app.deploy_name end def test_init default_info = {:ports => {}} assert_equal default_info, @sa.info assert_equal @app, @sa.app assert_equal Hash.new, @sa.scripts assert_equal [:all], @sa.roles end def test_init_roles sa = Sunshine::ServerApp.new @app, "host", :roles => "role1 role2" assert_equal [:role1, :role2], sa.roles sa = Sunshine::ServerApp.new @app, "host", :roles => %w{role3 role4} assert_equal [:role3, :role4], sa.roles end def test_add_shell_paths @sa.add_shell_paths "test/path1", "test/path2" assert_equal "test/path1:test/path2:$PATH", @sa.shell_env['PATH'] @sa.add_shell_paths "test/path3", "test/path4" assert_equal "test/path3:test/path4:test/path1:test/path2:$PATH", @sa.shell_env['PATH'] end def test_app_attr sa_root_path = "local/server_app/path" sa_deploy_name = "local_deploy_name" @sa = Sunshine::ServerApp.new "test", "host", :root_path => sa_root_path, :deploy_name => sa_deploy_name assert_equal sa_root_path, @sa.root_path assert_equal sa_deploy_name, @sa.deploy_name assert_equal "test", @sa.name @sa.app = @app assert_not_equal sa_root_path, @sa.root_path assert_not_equal sa_deploy_name, @sa.deploy_name assert_not_equal "test", @sa.name assert_equal @app.root_path, @sa.root_path assert_equal @app.deploy_name, @sa.deploy_name assert_equal @app.name, @sa.name end def test_build_control_scripts @sa.scripts[:start] << "start" @sa.scripts[:stop] << "stop" @sa.scripts[:custom] << "custom" @sa.build_control_scripts [:start, :stop, :custom].each do |script| content = @sa.make_bash_script script, @sa.scripts[script] assert @sa.method_called?(:write_script, :args => [script, content]) end content = @sa.make_env_bash_script assert @sa.method_called?(:write_script, :args => ["env", content]) content = @sa.make_bash_script :restart, ["#{@sa.app.root_path}/stop", "#{@sa.app.root_path}/start"] assert @sa.method_called?(:write_script, :args => [:restart, content]) end def test_build_deploy_info_file @sa.shell.mock :file?, :return => false args = ["#{@app.scripts_path}/info", @sa.get_deploy_info.to_yaml] @sa.build_deploy_info_file assert @sa.shell.method_called?(:make_file, :args => args) args = ["#{@app.scripts_path}/info", "#{@app.root_path}/info"] assert @sa.shell.method_called?(:symlink, :args => args) end def test_checkout_repo @sa.checkout_repo @app.repo repo = @sa.app.repo args = [@app.checkout_path, @sa.shell] assert repo.method_called?(:checkout_to, :args => args) info = @app.repo.checkout_to @app.checkout_path, @sa.shell assert_equal info, @sa.info[:scm] end def test_deploy_details deploy_details = {:item => "thing"} other_details = {:key => "value"} @sa.shell.mock :call, :args => ["cat #{@sa.root_path}/info"], :return => other_details.to_yaml @sa.instance_variable_set "@deploy_details", deploy_details assert_equal deploy_details, @sa.deploy_details assert_equal other_details, @sa.deploy_details(true) end def test_not_deployed? @sa.mock :deploy_details, :args => [true], :return => nil assert_equal false, @sa.deployed? end def test_server_checked_deployed? @sa.mock :deploy_details, :args => [true], :return => {:deploy_name => @sa.deploy_name} assert_equal true, @sa.deployed? end def test_cached_details_deployed? @sa.instance_variable_set "@deploy_details", :deploy_name => @sa.deploy_name assert_equal true, @sa.deployed? end def test_get_deploy_info test_info = { :deployed_at => Time.now.to_s, :deployed_as => @sa.shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(@app.checkout_path), :name => @sa.name, :env => @sa.shell_env, :roles => @sa.roles, :path => @app.root_path, :sunshine_version => Sunshine::VERSION }.merge @sa.info deploy_info = @sa.get_deploy_info deploy_info.each do |key, val| next if key == :deployed_at assert_equal test_info[key], val end end def test_has_all_roles assert @sa.has_roles?([:web, :app, :blarg]) assert @sa.has_roles?([:web, :app, :blarg], true) end def test_has_roles @sa.roles = [:web, :app] assert @sa.has_roles?(:web) assert @sa.has_roles?([:web, :app]) assert [email protected]_roles?([:blarg, :web, :app]) assert @sa.has_roles?([:blarg, :web, :app], true) end def test_install_deps nginx_dep = Sunshine.dependencies.get 'nginx', :prefer => @sa.pkg_manager @sa.install_deps "ruby", nginx_dep assert_dep_install 'ruby', Sunshine::Yum assert_dep_install 'nginx', Sunshine::Yum end def test_install_deps_bad_type nginx_dep = Sunshine.dependencies.get 'nginx' @sa.install_deps nginx_dep, :type => Sunshine::Gem raise "Didn't raise missing dependency when it should have." rescue Sunshine::MissingDependency => e assert_equal "No dependency 'nginx' [Sunshine::Gem]", e.message end def test_make_app_directories @sa.make_app_directories assert_server_call "mkdir -p #{@sa.directories.join(" ")}" end def test_make_bash_script app_script = @sa.make_bash_script "blah", [1,2,3,4] assert_bash_script "blah", [1,2,3,4], app_script end def test_make_env_bash_script @sa.shell.env = {"BLAH" => "blarg", "HOME" => "/home/blah"} test_script = "#!/bin/bash\nenv BLAH=blarg HOME=/home/blah \"$@\"" assert_equal test_script, @sa.make_env_bash_script end def test_rake @sa.rake "db:migrate" assert_dep_install 'rake', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && rake db:migrate" end def test_register_as_deployed Sunshine::AddCommand.extend MockObject unless MockObject === Sunshine::AddCommand @sa.register_as_deployed - args = [@app.root_path, {'servers' => [@sa.shell]}] + args = ["#{@app.name}:#{@app.root_path}", {'servers' => [@sa.shell]}] assert Sunshine::AddCommand.method_called?(:exec, :args => args) end def test_remove_old_deploys Sunshine.setup 'max_deploy_versions' => 3 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_server_call "rm -rf #{removed.join(" ")}" end def test_remove_old_deploys_unnecessary Sunshine.setup 'max_deploy_versions' => 5 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.mock :call, :args => ["ls -1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_not_called "rm -rf #{removed.join(" ")}" end def test_revert! deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" last_deploy = "#{@app.deploys_path}/ploy5" assert_server_call "ln -sfT #{last_deploy} #{@app.current_path}" end def test_no_previous_revert! @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" end def test_run_bundler @sa.run_bundler assert_dep_install 'bundler', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && gem bundle" end def test_run_geminstaller @sa.run_geminstaller assert_dep_install 'geminstaller', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && geminstaller -e" end def test_running? set_mock_response_for @sa, 0, "#{@sa.root_path}/status" => [:out, "THE SYSTEM OK!"] assert_equal true, @sa.running? end def test_not_running? set_mock_response_for @sa, 13, "#{@sa.root_path}/status" => [:err, "THE SYSTEM IS DOWN!"] assert_equal false, @sa.running? end def test_errored_running? set_mock_response_for @sa, 1, "#{@sa.root_path}/status" => [:err, "KABLAM!"] assert_raises Sunshine::CmdError do @sa.running? end end def test_sass sass_files = %w{file1 file2 file3} @sa.sass(*sass_files) assert_dep_install 'haml', @sa.pkg_manager sass_files.each do |file| sass_file = "public/stylesheets/sass/#{file}.sass" css_file = "public/stylesheets/#{file}.css" assert_server_call \ "cd #{@app.checkout_path} && sass #{sass_file} #{css_file}" end end def test_shell_env assert_equal @sa.shell.env, @sa.shell_env end def test_symlink_current_dir @sa.symlink_current_dir assert_server_call "ln -sfT #{@app.checkout_path} #{@app.current_path}" end def test_upload_codebase @sa.shell.mock(:upload) @sa.upload_codebase "tmp/thing/", :test_scm => "info" assert_equal({:test_scm => "info"} , @sa.info[:scm]) assert @sa.shell.method_called?( :upload, :args => ["tmp/thing/", @sa.checkout_path, {:flags => ["--exclude .svn/","--exclude .git/"]}]) end def test_upload_codebase_with_exclude @sa.shell.mock(:upload) @sa.upload_codebase "tmp/thing/", :test_scm => "info", :exclude => "bad/path/" assert_equal({:test_scm => "info"} , @sa.info[:scm]) assert @sa.shell.method_called?( :upload, :args => ["tmp/thing/", @sa.checkout_path, {:flags => ["--exclude bad/path/", "--exclude .svn/", "--exclude .git/"]}]) end def test_upload_codebase_with_excludes @sa.shell.mock(:upload) @sa.upload_codebase "tmp/thing/", :test_scm => "info", :exclude => ["bad/path/", "other/exclude/"] assert_equal({:test_scm => "info"} , @sa.info[:scm]) assert @sa.shell.method_called?( :upload, :args => ["tmp/thing/", @sa.checkout_path, {:flags => ["--exclude bad/path/", "--exclude other/exclude/", "--exclude .svn/", "--exclude .git/"]}]) end def test_write_script @sa.shell.mock :file?, :return => false @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert @sa.shell.method_called?(:make_file, :args => args) end def test_symlink_scripts_to_root @sa.shell.mock :call, :args => ["ls -1 #{@sa.scripts_path}"], :return => "script_name\n" args = ["#{@app.scripts_path}/script_name", "#{@app.root_path}/script_name"] @sa.symlink_scripts_to_root assert @sa.shell.method_called?(:symlink, :args => args) end def test_write_script_existing @sa.shell.mock :file?, :return => true @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert [email protected]_called?(:make_file, :args => args) end end
jcasts/sunshine
41b7f7428fd2ad64a297741b894c708eef823ada
fixed ServerApp#register_as_deployed to pass the correct app name
diff --git a/README.txt b/README.txt index 9ed88f1..ead9837 100644 --- a/README.txt +++ b/README.txt @@ -1,633 +1,633 @@ = Sunshine http://github.com/yaksnrainbows/sunshine http://betalabs.yellowpages.com/ == Description Sunshine is a framework for rack and rails application deployment. This gem was made possible by the sponsoring of AT&T Interactive (http://attinteractive.com). == Setup and Usage Installing sunshine: $ gem install sunshine Call sunshine to create the config file: $ sunshine Missing config file was created for you: /Users/jsmith/.sunshine --- auto_dependencies: true deploy_env: :development exception_behavior: :revert exclude_paths: [] interactive: true level: info max_deploy_versions: 5 remote_checkouts: false timeout: 300 sigint_behavior: :revert web_directory: /srv/http You can either use sunshine by requiring the gem in your script, such as in a rakefile (which is more common): $ rake sunshine:deploy env=qa Or you can also call built-in sunshine commands: $ sunshine run my_deploy.rb -e qa == Rake Deploy Tasks in 5 Minutes Although Sunshine comes with it's own bundle of commands, they should be used to control deployed apps on remote servers in instances where deploy information (e.g. your deploy yaml file) is unavailable. Their purpose is to query a server where Sunshine apps have been deployed and have a nominal amount of information and control over them. Sunshine control commands are run on a per-server basis. Most of the time, you'll want to control the deploy on a per-app basis. You have the deploy information and you need to do things involving that specific deploy. Rake tasks are great for that, and Sunshine comes with a template rake file that you can modify to fit your needs. You can copy the template rake file to rake/ by running: $ sunshine --rakefile rake/. If you open the file, you'll see a variety of tasks that handle deployment, to application start/stop/restart-ing, to health checks. Most likely, the two tasks you'll need to update are the :app (for instantiation) and the :deploy tasks. First off, if you're using rails, you'll probably want to update "task :app" to "task :app => :environment" in order to get all the rails environment goodness. You'll also want to make sure that the @app object gets instantiated with the proper hash value or yaml file. Second, you need to update your :deploy task. Add whatever instructions you need to the @app.deploy block. Here's a sample of completed :app and :deploy tasks: namespace :sunshine do desc "Instantiate Sunshine" task :app => :environment do Sunshine.setup 'sudo' => 'app_user', 'web_directory' => '/var/www', 'deploy_env' => Rails.environment @app = Sunshine::App.new \ :repo => Sunshine::SvnRepo.new("svn://subversion/repo/tags/release001"), :remote_shells => 'user@my_server.com' end desc "Deploy the app" task :deploy => :app do Sunshine.setup 'trace' => true @app.deploy do |app| rainbows = Sunshine::Rainbows.new app, :port => 5001 nginx = Sunshine::Nginx.new app, :point_to => rainbows app.run_geminstaller rainbows.setup nginx.setup end end ... end And that's it! Try running your Sunshine rake tasks! rake sunshine:app # Instantiate Sunshine rake sunshine:deploy # Deploy the app rake sunshine:info # Get deployed app info rake sunshine:restart # Run the remote restart script rake sunshine:start # Run the remote start script rake sunshine:status # Check if the deployed app is running rake sunshine:stop # Run the remote stop script == Understanding Deployment === The App Class Writing a Sunshine script is easy. App objects are the core of Sunshine deployment. The Sunshine paradygm is to construct an app object, and run custom deploy code by passing a block to its deploy method: options = { :name => 'myapp', :repo => {:type => :svn, :url => 'svn://blah...'}, :root_path => '/usr/local/myapp' } options[:remote_shells] = case Sunshine.deploy_env when 'qa' ['qa1.svr.com', 'qa2.svr.com'] else 'localhost' end Sunshine::App.deploy(options) do |app| app_server = Sunshine::Rainbows.new(app) - app_server.restart + app_server.setup - Sunshine::Nginx.new(app, :point_to => app_server).restart + Sunshine::Nginx.new(app, :point_to => app_server).setup end An App holds information about where to deploy an application to and how to deploy it, as well as many convenience methods to setup and manipulate the deployment process. Most of these methods support passing remote shell find options: app.rake 'db:migrate', :role => :db app.deploy :host => 'server1.com' See Sunshine::App#find for more information. === Working With Environments Environment specific setups can be accomplished in a few ways. The most obvious way is to create a different script for each environment. You can also define the App's constructor hash on a per-environment basis (as seen above), which gives you lots of control. That said, the App class also provides a mechanism for environment handling using configuration files. The App::new methods support passing a path to a yaml config file: app = Sunshine::App.new("path/to/config.yml") - app.deploy{|app| Sunshine::Rainbows.new(app).restart } + app.deploy{|app| Sunshine::Rainbows.new(app).setup } The yaml file can also be any IO stream who's output will parse to yaml. This can be ueful for passing the file's DATA and keep all the deploy information in one place: # The following two lines are equivalent: app = Sunshine::App.new app = Sunshine::App.new Sunshine::DATA - app.deploy{|app| Sunshine::Rainbows.new(app).restart } + app.deploy{|app| Sunshine::Rainbows.new(app).setup } __END__ # yaml for app goes here... Yaml files are read on a deploy-environment basis so its format reflects this: --- # Default is always inherited by all environments :default : :name : app_name :repo : :type : svn :url : svn://subversion/app_name/branches/continuous_integration :root_path : /usr/local/app_name :remote_shells : - - localhost - :roles : web db app # Setup for qa environment :qa : :repo : :type : svn :url : svn://subversion/app_name/tags/release_0001 :remote_shells : - qa1.servers.com - qa2.servers.com # Prod inherits top level values from :qa :prod : :inherits : :qa :remote_shells : - prod1.servers.com - prod2.servers.com In this example, :prod inherits top level values from :qa (only :repo in this instance). The :inherits key also supports an array as its value. All environments also inherit from the :default environment. The :default is also used if the app's deploy_env is not found in the config. Finally, yaml configs get parsed by erb, exposing any options passed to the App's constuctor, along with the deploy environment, letting your write configs such as: # deploy.rb app = App.new "deploy.yml", :name => "my_app", :deploy_name => "release_001" # deploy.yml --- :default : :repo : :type : svn :url : svn://subversion/<%= name %>/tags/<%= deploy_name %> :remote_shells : - <%= deploy_env %>1.<%= name %>.domain.com - <%= deploy_env %>2.<%= name %>.domain.com See Sunshine::App for more information. == Servers === Basics Sunshine lets you install and setup server applications to run your app on. The typical approach to serving ruby applications is to run Nginx or Apache as a load balancer in front of a backend such as Thin, or Mongrels. Using Sunshine, this is most commonly defined as a part of the deploy process: app.deploy do |app| backend = Sunshine::Thin.new app, :port => 5000 nginx = Sunshine::Nginx.new app, :point_to => backend backend.setup nginx.setup end When a new Server is instantiated and its setup method is run, it is added to the app's control scripts. This means that when the deploy is complete, those servers can be controlled by the app's start/stop/restart/status methods. === Load Balancing Since frontend servers support load balancing, you can also point them to server clusters: backend = Sunshine::Thin.new_cluster 10, app, :port => 5000 nginx = Sunshine::Nginx.new app, :point_to => backend backend.setup nginx.setup In this instance, Nginx will know to forward requests to the cluster of Thin servers created. You could do this more explicitely with the following: backend = Array.new 5000.upto(5009) do |port| thin = Sunshine::Thin.new app, :port => port, :name => "thin.#{port}" thin.setup backend << thin end Sunshine::Nginx.new app, :point_to => backend === Phusion Passenger If you are running a lower traffic application, Phusion Passenger is available for both Nginx and Apache. Passenger will be used by default if no backend is specified. You could have an Nginx Passenger setup on port 80 with a single line: Sunshine::Nginx.new(app).setup Easy! Servers let you do much more configuration with log files, config files, etc. For more information, see Sunshine::Server. == Dependencies Sunshine has simple, basic dependency support, and relies mostly on preexisting package manager tools such as apt, yum, or rubygems. Dependencies or packages can be defined independently, or as a part of a dependency tree (see Sunshine::DependencyLib). Sunshine has its own internal dependency tree which can be modified but users can also create their own. === User Dependencies The most common way of using dependencies is through ServerApp: server_app.apt_install 'postgresql', 'libxslt' server_app.gem_install 'json', :version => '>=1.0.0' This should be plenty for most users. You can however create simple standalone package definitions: postgresql = Sunshine::Apt.new('postgresql') postgresql.install! :call => server_app.shell You can imagine how this would be useful to do server configuration with Sunshine: server = RemoteShell.new "[email protected]" server.connect %w{postgresql libxslt ruby-full rubygems}.each do |dep_name| Sunshine::Apt.new(dep_name).install! :call => server end Warning: If the :call options isn't specified, the dependency will attempt to install on the local system. See Sunshine::Dependency for more information. === Internal Sunshine Dependencies (advanced) Sunshine's default dependencies are defined in Sunshine.dependencies and can be overridden as needed: Sunshine.dependencies.get 'rubygems', :type => Sunshine::Yum #=> <Sunshine::Yum ... version='1.3.5' > # Not what you want? Replace it: Sunshine.dependencies.yum 'rubygems', :version => '1.3.2' Any dependencies added or modified in Sunshine.dependencies are used as a part of the internal Sunshine workings. Also to note: ServerApp#pkg_manager is crucial in defining which dependency to use. By default, a server_app's package manager will be either Yum or Apt depending on availability. That can be overridden with something like: server_app.pkg_manager = Sunshine::Yum An array can also be given and the server_app will attempt to install available dependencies according to that type order: server_app.pkg_manager = [Sunshine::Tpkg, Sunshine::Yum] In this instance, if no Tpkg dependency was defined in Sunshine.dependencies, the server_app will look for a Yum dependency. If you want to ensure all your server_apps use the same dependency definition, you may consider: Sunshine.dependencies.yum 'rubygems', :version => '1.3.2' Sunshine.dependencies.apt 'rubygems', :version => '1.3.2' # ... and so on Note: You can disable automatic dependency installation by setting Sunshine's auto_dependencies config to false. == Using Permissions In order to deploy applications successfully, it's important to know how, where, and when to use permissions in Sunshine deploy scripts. === The Shell Class The primary handler of permissions is the Sunshine::Shell class. Since all commands are run through a Shell object, it naturally handles permission changes. The following will create a new remote shell which is logged into as user "bob" but will use root to perform all calls: # The following two lines are equivalent: svr = Sunshine::RemoteShell.new "[email protected]", :sudo => true svr = Sunshine::RemoteShell.new "myserver.com", :user => "bob" :sudo => true Sudo can also be set after instantiation. Let's change the permissions back to its default: svr.sudo = nil You can of course also run single commands with a one-off sudo setting: svr.call "whoami", :sudo => true #=> "root" Shell sudo values are important! Depending on what the value of shell.sudo is, behavior will change dramatically: - sudo = true -> sudo -H command - sudo = 'root' -> sudo -H -u root command - sudo = 'usr' -> sudo -H -u usr command - sudo = false -> enforce never using sudo - sudo = nil -> passthrough (don't care) Here are a few examples of these values being used: svr = Sunshine::RemoteShell.new "[email protected]", :sudo => true svr.call "whoami" #=> root svr.call "whoami", :sudo => "usr" #=> usr svr.call "whoami", :sudo => nil #=> root svr.call "whoami", :sudo => false #=> bob These values are crucial as other Sunshine classes have and pass around other sudo requirements/values to shell objects. === Who Affects Sudo There are 3 main places to beware of how sudo gets used. ==== Apps The first, most obvious place is the App class: app.sudo = "bob" app.server_apps.first.shell.sudo #=> "bob" app.sudo = true app.server_apps.first.shell.sudo #=> true Since the App class effectively owns the shells it uses, setting sudo on the App will permanently change the sudo value of its shells. Note: You may notice that you can set a sudo config value on the Sunshine module. This is used for the default value of Sunshine::App#sudo and is passed along to an app's shells on instantiation. ==== Servers Because of how unix works with servers and ports, it's not uncommon to have to run start/stop/restart server commands with upgraded permissions. This is true for Apache and Nginx on ports below 1024. Due to this, servers automatically try to adjust their permissions to run their commands correctly. Since servers should run their commands consistantly, the only way to affect their sudo value is on a server instance basis: server = Nginx.new app, :sudo => nil # let the shell handle sudo However, the above will most likely cause Nginx's start command to fail if shell permissions don't allow running root processes. Note: Servers will ONLY touch permissions if their port is smaller than 1024. ==== Dependencies Since Sunshine also deals with installing dependencies, the Dependency class and its children all have a class level sudo setting which is set to true by default. This means that any dependency will by default run its commands using sudo: dep = Sunshine::Apt.new "libdvdread" dep.install! :call => shell #=> sudo -H apt-get install libdvdread This can be changed on the class level: shell.sudo = "usr" Sunshine::Apt.sudo = nil # let the shell handle sudo dep.install! :call => shell #=> sudo -H -u usr apt-get install libdvdread It can also be set on an individual basis: dep.install! :call => shell, :sudo => nil == Sunshine Configuration Aside from passing the sunshine command options, Sunshine can be configured both in the deploy script by calling Sunshine.setup and globally in the ~/.sunshine file. The following is a list of supported config keys: 'auto_dependencies' -> Check and install missing deploy dependencies; defaults to true. 'deploy_env' -> The default deploy environment to use; defaults to :development. 'exception_behavior' -> The behavior called when an exception is raised during a deploy; defaults to :revert. 'exclude_paths' -> Paths to exclude in the checkout when deploying code with via rsync; defaults to empty Array. 'interactive' -> Automate calls; fail instead of prompting the user; defaults to false. 'level' -> Logger's debug level; defaults to 'info'. 'max_deploy_versions' -> The maximum number of deploys to keep on a server; defaults to 5. 'remote_checkouts' -> Use remote servers to checkout the codebase; defaults to false. 'require' -> Require external ruby libs or gems; defaults to nil. 'timeout' -> The amount of time in seconds for shells to wait with no incoming data before timing out; defaults to 300. 'sigint_behavior' -> The behavior called when a SIGINT is received during a deploy; defaults to :revert. 'trace' -> Show detailed output messages; defaults to false. 'web_directory' -> Path to where apps should be deployed to; defaults to '/srv/http'. == Deployed Application Control Sunshine has a variety of commands that allow simple control of remote or locally deployed applications. These include start, stop, restart actions to be taken application-wide, as well as querying for the health and state of the app: Examples: sunshine run deploy_script.rb sunshine restart myapp -r [email protected],[email protected] sunshine list myapp myotherapp --health -r [email protected] sunshine list myapp --status The Sunshine commands are as follows: add Register an app with sunshine list Display deployed apps restart Restart a deployed app rm Unregister an app with sunshine run Run a Sunshine ruby file script Run an app script start Start a deployed app stop Stop a deployed app For more help on sunshine commands, use 'sunshine COMMAND --help'. For more information about control scripts, see the Sunshine::App#build_control_scripts method. === Remote Scripts and Permissions: Important: Applications are deployed on a per-user basis. When calling commands that require superuser permissions (e.g. calling restart on an app that runs on Apache, port 80), make sure that the user used to log in has sudo permissions. Example: I've deployed an application logged in as 'superuser' but for a 'peon' user with a lower permission level using something like: Sunshine.setup 'sudo' => 'peon' @app = Sunshine::App.new :remote_shells => '[email protected]' Using any of the following will fail to return since 'peon' has no sudo priviledges: $ sunshine restart app -r [email protected] $ sunshine restart app -r [email protected] -S Yet, if you only log in as 'superuser' the app will not be found as it will be looking for apps deployed and run for 'superuser', hence this is wrong too: $ sunshine restart app -r [email protected] To run the script correctly, use the same setup used for your deploy, in this case: $ sunshine restart app -r [email protected] -S peon This is true for the following commands: $ sunshine list --status $ sunshine restart $ sunshine script $ sunshine start $ sunshine stop == Licence (The MIT License) Copyright (c) 2010 At&t Interactive Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/lib/sunshine.rb b/lib/sunshine.rb index 3eaaabe..e59ca2a 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,441 +1,441 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'yaml' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' require 'irb' # Turn off EOF tracking to be able to prompt on deploy exceptions. HighLine.track_eof = false ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. - VERSION = '1.2.2' + VERSION = '1.3.0' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { 'auto_dependencies' => true, 'deploy_env' => :development, 'exception_behavior' => :revert, 'exclude_paths' => [], 'interactive' => true, 'level' => 'info', 'max_deploy_versions' => 5, 'remote_checkouts' => false, 'timeout' => 300, 'sigint_behavior' => :revert, 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end ## # Defines what to do when deploy raises an exception. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.exception_behavior @config['exception_behavior'] end ## # Array of paths or globs that should be excluded from the checkout. # Does not work with remote_checkouts enabled. def self.exclude_paths @config['exclude_paths'] end ## # Should sunshine ever ask for user input? True by default. # Overridden in the config or with the -a option. def self.interactive? @config['interactive'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end ## # Defines what to do when sigint is sent during deploys. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.sigint_behavior @config['sigint_behavior'] end ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config unless File.file? USER_CONFIG_FILE File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" msg << DEFAULT_CONFIG.to_yaml self.exit 1, msg end load_config_file USER_CONFIG_FILE @config['deploy_env'] = ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] || @config['deploy_env'] @config end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset TrapStack.trap_signal :INT do |msg| $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" logger.info :INT, msg end TrapStack.add_trap "Disconnecting all remote shells." do RemoteShell.disconnect_all end require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' require 'sunshine/trap_stack' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' require 'sunshine/healthcheck' require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies' diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index 2e8d639..a0a1c5a 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -1,705 +1,705 @@ module Sunshine ## # Handles App deployment functionality for a single deploy server. # # Server apps can be assigned any number of roles for classification. # :roles:: sym|array - roles assigned (web, db, app, etc...) # By default server apps get the special :all role which will # always return true when calling: # server_app.has_roles? :some_role # # ServerApp objects can be instantiated several ways: # ServerApp.new app_instance, shell_instance, options_hash # # When passing an App instance, the new ServerApp will keep an active link # to the app's properties. Name, deploy, and path attributes will be # actively linked. # # Rely on ServerApp to create a RemoteShell instance to use: # ServerApp.new app_instance, "host.com", options_hash # # Instantiate with app name and rely on Sunshine defaults for app paths: # ServerApp.new "app_name", shell_instance, options_hash # # Explicitely assign the app's root path: # ServerApp.new "app_name", ..., :root_path => "/path/to/app_root" # # Assigning a specific deploy name to use can be done with the # :deploy_name option: # ServerApp.new "app_name", ..., :deploy_name => "deploy" class ServerApp ## # Define an attribute that will get a value from app, or locally if # @app isn't set. def self.app_attr *attribs attribs.each do |attrib| class_eval <<-STR, __FILE__, __LINE__ + 1 def #{attrib} @app ? @app.send(:#{attrib}) : @#{attrib} end STR end end ## # Creates dependency instance methods such as gem_install, yum_install, etc # on both App and ServerApp classes. def self.register_dependency_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = Hash === names.last ? names.delete_at(-1) : Hash.new names.each do |name| dep = #{dep_class}.new(name, options) dep.install! :call => @shell end end STR App.class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = names.last if Hash === names.last with_server_apps options, :msg => "Installing #{dep_class.short_name} packages", :send => [:#{dep_class.short_name}_install, *names] end STR end ## # Creates a ServerApp instance from a deploy info file. def self.from_info_file path, shell=nil shell ||= Sunshine.shell opts = YAML.load shell.call("cat #{path}") opts[:root_path] = opts.delete :path sa_shell = shell.dup sa_shell.env = opts[:env] || Hash.new sa_shell.connect if shell.connected? new opts[:name], sa_shell, opts end app_attr :name, :deploy_name app_attr :root_path, :checkout_path, :current_path app_attr :deploys_path, :log_path, :shared_path, :scripts_path attr_accessor :app, :roles, :scripts, :info, :shell, :crontab attr_writer :pkg_manager ## # Create a server app instance. Supports the following # argument configurations: # # ServerApp.new app_inst, "myserver.com", :roles => :web # ServerApp.new "app_name", shell_inst, options_hash def initialize app, host, options={} @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No status for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path, :sunshine_version => Sunshine::VERSION }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed - AddCommand.exec self.root_path, 'servers' => [@shell] + AddCommand.exec "#{self.name}:#{self.root_path}", 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's restart script. Raises an exception on failure. # Post-deploy only. def restart! # Permissions are handled by the script, use: :sudo => false run_script! :restart, :sudo => false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the root_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} run_script! name, options, &block rescue false end ## # Runs a script from the root_path. Raises an exception if the status # code is not 0. # Post-deploy only. def run_script! name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script! :status, :sudo => false true rescue CmdError => e return false if e.exit_code == Daemon::STATUS_DOWN_CODE raise e end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Run the app's start script. Raises an exception on failure. # Post-deploy only. def start! options=nil options ||= {} if running? return unless options[:force] stop! end # Permissions are handled by the script, use: :sudo => false run_script! :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's stop script. Raises an exception on failure. # Post-deploy only. def stop! # Permissions are handled by the script, use: :sudo => false run_script! :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} excludes = scm_info.delete :exclude if scm_info[:exclude] excludes = [excludes].flatten.compact excludes.map!{|e| "--exclude #{e}"} repo = RsyncRepo.new code_dir, :flags => excludes repo.checkout_to self.checkout_path, @shell @info[:scm] = scm_info end ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end end end
jcasts/sunshine
999528c8517e20b1ef7961dc2b8f3f05b347e6cf
removed health check from default rake file
diff --git a/templates/sunshine/sunshine.rake b/templates/sunshine/sunshine.rake index aeb57ce..0063d24 100644 --- a/templates/sunshine/sunshine.rake +++ b/templates/sunshine/sunshine.rake @@ -1,159 +1,132 @@ namespace :sunshine do ## # If using Rails, have the environment available by updating :app task to: # task :app => :environment do # ... # end desc "Instantiate app" task :app do require 'sunshine' # By default, Sunshine will deploy with env set from (in order): # ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] # # If using Rails, you may want to setup Sunshine with the same environment: # Sunshine.setup 'deploy_env' => Rails.environment # View the Sunshine README, scripts in the sunshine/examples # directory, or the docs for Sunshine::App for more information on # App instantiation. @app = Sunshine::App.new "path/to/app_deploy_config.yml" # or # @app = Sunshine::App.new app_config_hash end ## # Put your deploy-specific logic in the deploy task... desc "Deploy the app" task :deploy => :app do Sunshine.setup 'trace' => true @app.deploy do |app| # Do deploy-specific stuff here, e.g. # # app.run_bundler # # unicorn = Sunshine::Unicorn.new app, :port => 3000, # :processes => 8 # unicorn.setup end end ## # Server setup logic that doesn't need to be run on every deploy # can be put in the :setup task. # # Note: By default, Sunshine will attempt to install missing server # dependencies that it uses if they are not present (e.g. Nginx, Apache...). # If you would like to disable this behavior and handle these dependencies # explicitely, add this setup configuration to your :app or :deploy task: # Sunshine.setup 'auto_dependencies' => false # # If you do so, ensure that the dependency bins are available in $PATH. desc "Sets up deploy servers" task :setup => :app do Sunshine.setup 'trace' => true # Setup servers here # # @app.with_filter :role => :app do |app| # app.yum_install 'libxml2', 'libxml2-devel' # app.gem_install 'mechanize' # end # # @app.with_filter :role => :db do |app| # app.yum_install 'sqlite' # app.gem_install 'sqlite3' # end # # If you're not able to add your public key to remote servers, # you can setup your tasks to use the App#with_session method # to avoid having to login multiple times: # # @app.with_session do # @app.with_filter :role => :app do |app| # app.yum_install 'libxml2', 'libxml2-devel' # app.gem_install 'mechanize' # end # ... # end end # Post-deploy control tasks: desc "Run db:migrate on remote :db servers" task :db_migrate => :app do @app.rake 'db:migrate', :role => :db end desc "Run the remote start script" task :start => :app do @app.start puts @app.status.to_yaml end desc "Run the remote stop script" task :stop => :app do @app.stop puts @app.status.to_yaml end desc "Run the remote restart script" task :restart => :app do @app.restart puts @app.status.to_yaml end desc "Check if the deployed app is running" task :status => :app do puts @app.status.to_yaml end desc "Get deployed app info" task :info => :app do puts @app.deploy_details.to_yaml end - - - desc "Get the health state" - task :health => :app do - puts @app.health.to_yaml - end - - - namespace :health do - - desc "Turn on health check" - task :enable => :app do - puts @app.health(:enable).to_yaml - end - - - desc "Turn off health check" - task :disable => :app do - puts @app.health(:disable).to_yaml - end - - - desc "Remove health check" - task :remove => :app do - puts @app.health(:remove).to_yaml - end - end end
jcasts/sunshine
6c6e434effc7f9f731a4fb943a4bfa3f038182b4
removed references to healthcheck
diff --git a/History.txt b/History.txt index 925226c..9ef45d8 100644 --- a/History.txt +++ b/History.txt @@ -1,383 +1,385 @@ === 1.3.0 / 2010 * Bugfixes: + * Completely removed the Healthcheck implementation. + * Removed superfluous App#upload_tasks method. * Lots of rdoc updates. === 1.2.2 / 2010-10-13 * Bugfixes: * Added support for ruby 1.9.2 === 1.2.1 / 2010-10-05 * Improvements: * Added customizable behaviors for sigint and failures during deploys. * Added Sunshine irb shell to work directly with deploying apps. * Added ability to launch a pseudo terminal from a RemoteShell. * Added exit code to CmdError. * Added exclude paths for checkout by copy. * Bugfixes: * Fixed custom scripts. * Fixed deploy env defaults. * Removed Shell#update_timeout as it was unnecessary. * RemoteShell rsync recurses by default. * Fixed start and stop script permissions when calling sunshine commands. === 1.2.0 / 2010-09-08 * Improvements: * Added better support for custom env/start/stop/restart scripts. * Added scripts sunshine command to call custom scripts remotely. * Deploy env defaults to ENV 'DEPLOY_ENV', 'env', 'RACK_ENV', or 'RAILS_ENV'. * Bugfixes: * ServerApp#run_geminstaller no longer defaults to using sudo. * Added better extensible package manager checking to ServerApp. * Fixed Cronjob functionality and added array support. === 1.1.2 / 2010-04-15 * Improvements: * Added array support to App#find. * Added auto registration of Dependency subclasses for scalability. * Added call to App#start in App#deploy. * Bugfixes: * Fixed bug where env wouldn't be applied correctly in control scripts. * Changed App#with_filter to actually change the App#server_apps attribute. * Shell#env_cmd now returns a flattened array. * Added actual check of running process to Daemon#status_cmd. === 1.1.1 / 2010-04-05 * Improvements: * Added Repo subclass registration for greater expandability. * Added support for checking out codebases locally then rsync-ing them. * Bugfixes: * Fixed RemoteShell login script lingering after disconnect. === 1.1.0 / 2010-04-02 * Improvements: * Support for server clustering with the ServerCluster class. * Added Daemon#status method. * Added the -R option for loading external libraries and gems. * Added support for Thin and MongrelRails. * Added Server support for max connections configuration. * Bugfixes: * Daemons no longer create control scripts if they aren't used. * Fixed Rsync repo to auto append "/" to urls for correct rsyncing. === 1.0.3 / 2010-03-26 * Improvements: * Added App#call method. * Added App#with_session and Shell#with_session to reduce login prompts. * Bugfixes: * Geminstaller now always installs with sudo. * Fixed permissions issues with running servers on ports < 1024. * Fixed healthcheck middleware. === 1.0.2 / 2010-03-25 * Bugfixes: * Fixed apache passenger dependency to run as sudo. * Fixed a bug in Repo::detect === 1.0.1 / 2010-03-25 * Bugfixes: * Added json dependency === 1.0.0 / 2010-03-25 * Improvements: * Added auto_dependencies config to turn on/off auto installing things. * Added healthcheck middleware support. * Added support for Apache2 and its passenger implementation. * Removed all Atti-specific code for public release. * Bugfixes: * Fixed Nginx passenger implementation. === 0.0.6 / 2010-03-19 * Major: * Removed DeployServerDispatcher. Dispatching now happens at the App level. * Moved Settler into Sunshine and renamed it to DependencyLib. * Improvements: * Added INT signal handling to exit deploys and close connections gracefully. * Added dependency installation methods apt_install, gem_install, tpkg_install and yum_install to App and ServerApp. * Extended functionality of ServerApp#upload_tasks. * ServerApp now support being instatiated with an App instance (for coordinated deploys) or just with an app name (for post-deploy usage). * Added a Sunshine rakefile template for task-based deploys. Available through: sunshine --rakefile [COPY_TO] * App#name gets auto-assigned by repo info if not provided. * Sunshine::web_directory used to determine App#deploy_path when missing. * Repo#detect now returns a Repo object instead of an array. * Added start/stop/restart/status methods to DeployServerApp. * ServerApp instances with unspecified roles get all roles by default. * App config files now use erb parsing. Any key/value passed the App constructor as a hash should be passed to the erb binding along with the deploy_env. * Added support to bundler for defining multiple dependencies with the same name, and different package managers. * Bugfixes: * Added setup checking to Daemon to only run setup when needed. * Moved healthcheck from App to ServerApp and improved the api. * Renamed DeployServerApp to ServerApp. * Renamed App#deploy_path and App#deploys_dir to App#root_path and App#deploys_path. * Renamed the 'deploy' command to 'run' to more accurately express it's use. * RsyncRepo#do_checkout fixed to match standard Repo#do_checkout methods. * Sunshine::DATA and Sunshine::PATH are now set when running standalone ruby deploy files. === 0.0.5 / 2010-02-26 * Sunshine::App: * Use of DeployServerDispatcher threading * Fixed control script creation to be deploy_server specific (takes roles into account) * Added AttiApp class for ATTi app deployment. * Constuctor supports :deploy_name option for nameable deploys. Defaults to the timestamp. * Auto-detects if the script's directory is a checked out repo and uses it if no repo information was given. * Support for running sass. * Sunshine::DeployServerDispatcher: * Added threading support * Sunshine::Repo: * Added support for detecting a repo type based on a path: Repo.detect [path [, console_or_deploy_server]] #=> [:git, "git://url/of/git/repo", {:tree => "master", ...}] * Moved info instance methods to the class * Support for git-svn: SvnRepo.git_svn? path * Changed the checkout_to method signature * Sunshine::Server: * Added support for ar_sendmail server. === 0.0.4 / 2010-02-12 * Added sudo functionality: * Support for :sudo option on Sunshine::App, Sunshine::Server, and Sunshine::DeployServer constructors, and attr_accessor :sudo * Settler Dependency classes support a default sudo value: Sunshine::Dependencies::Gem.sudo = true # use sudo Sunshine::Dependencies::Gem.sudo = "usr" # use sudo -u usr Sunshine::Dependencies::Gem.sudo = false # ensure sudo is off Sunshine::Dependencies::Gem.sudo = nil # use :call obj precedence * App supports passing a (yml) file object to the constructor. Useful for passing file DATA if desired: app = Sunshine::App.new Sunshine::DATA app.deploy!{|app| Sunshine::Rainbows.new(app).restart } __END__ #yaml for app goes here... * App class changes: * Changed the format of the App#checkout_path directory * Logrotate setup now has to be called explicitely * Commands functionality expanded: * Support for --sudo and --sudo=user on all Sunshine commands * Added --format option for control commands. Supports txt, yml, json. * Control scripts generated on the remote server now keep deploy-time shell_env variables: * Run commands with the --no-env option to run without deploy shell_env variables. * Run any script with the app's env variables using: /path/to/app/env some_command /path/to/app/env EXTRA_VAR=some_value some_command Supports all options the env command supports. * Dependency handling now supports apt. * DeployServers now support passing custom flags for ssh and rsync: deploy_server = DeployServer.new "svr.com", :rsync_flags => [...] deploy_server.call "some_command", :sudo => "user", :flags => '-C' deploy_server.upload "from", "to", :sudo => "user", :flags => ['--chmod=ugo=rwX', '-b'] deploy_server.download "from", "to", :flags => '--ignore-existing' * Repo implementation has significantly changed: * Added support for git repo. * Info about a repo is now retrieved with Repo#get_repo_info: repo.get_repo_info deploy_server, checkout_path * Repo constructor supports options hash with :flags option. === 0.0.3 / 2010-01-29 * Many small bugfixes * Tests, tests, and more tests * Changed DeployServer api * DeployServer#run is not longer supported, use DeployServer#call * Constructor supports a spaced delimited list for roles: DeployServer.new "myhost.com", :roles => "web db other" * Changed how deploy server yaml is parsed. Should parse to be valid on: DeployServer.new *parsed_yaml Example Given: :deploy_servers : - server1.com - - server2.com - - server3.com - :roles : web db other :ssh_flags : '-o ControlMaster=auto' === 0.0.2 / 2010-01-15 * Added Control Commands * add, deploy, list, restart, rm, start, stop * Application support * Changed VERSION file to info and its format to yaml * Deployed apps now have a start, stop and restart script * Added Crontab and log rotation support * Functional changes * Ditched net/ssh and net/scp for ssh and rsync through Open4 * Fixed and updated dependencies to use Yum * Support for sunshine user configuration in ~/.sunshine * Rake tasks * Support to run the app's rake tasks * Built in default ATTi rake tasks === 0.0.1 / 2009-11-18 * 1 major enhancement * First release! diff --git a/Manifest.txt b/Manifest.txt index d933f92..00adc0d 100644 --- a/Manifest.txt +++ b/Manifest.txt @@ -1,82 +1,79 @@ History.txt Manifest.txt README.txt Rakefile bin/sunshine examples/deploy_tasks.rake examples/standalone_deploy.rb examples/sunshine_deploy.rb lib/commands/add.rb lib/commands/default.rb lib/commands/list.rb lib/commands/restart.rb lib/commands/rm.rb lib/commands/run.rb lib/commands/script.rb lib/commands/start.rb lib/commands/stop.rb lib/sunshine.rb lib/sunshine/app.rb lib/sunshine/binder.rb lib/sunshine/crontab.rb lib/sunshine/daemon.rb lib/sunshine/daemons/apache.rb lib/sunshine/daemons/ar_sendmail.rb lib/sunshine/daemons/delayed_job.rb lib/sunshine/daemons/mongrel_rails.rb lib/sunshine/daemons/nginx.rb lib/sunshine/daemons/rainbows.rb lib/sunshine/daemons/server.rb lib/sunshine/daemons/server_cluster.rb lib/sunshine/daemons/thin.rb lib/sunshine/daemons/unicorn.rb lib/sunshine/dependencies.rb lib/sunshine/dependency_lib.rb lib/sunshine/exceptions.rb -lib/sunshine/healthcheck.rb lib/sunshine/output.rb lib/sunshine/package_managers/apt.rb lib/sunshine/package_managers/dependency.rb lib/sunshine/package_managers/gem.rb lib/sunshine/package_managers/yum.rb lib/sunshine/remote_shell.rb lib/sunshine/repo.rb lib/sunshine/repos/git_repo.rb lib/sunshine/repos/rsync_repo.rb lib/sunshine/repos/svn_repo.rb lib/sunshine/server_app.rb lib/sunshine/shell.rb lib/sunshine/trap_stack.rb templates/apache/apache.conf.erb templates/mongrel_rails/mongrel_rails.conf.erb templates/nginx/nginx.conf.erb templates/nginx/nginx_optimize.conf templates/nginx/nginx_proxy.conf templates/rainbows/rainbows.conf.erb -templates/sunshine/middleware/health.rb templates/sunshine/sunshine.rake templates/thin/thin.conf.erb templates/unicorn/unicorn.conf.erb test/fixtures/app_configs/test_app.yml test/fixtures/sunshine_test/test_upload test/helper_methods.rb test/mocks/mock_object.rb test/mocks/mock_open4.rb test/test_helper.rb test/unit/test_app.rb test/unit/test_binder.rb test/unit/test_crontab.rb test/unit/test_daemon.rb test/unit/test_git_repo.rb -test/unit/test_healthcheck.rb test/unit/test_nginx.rb test/unit/test_rainbows.rb test/unit/test_remote_shell.rb test/unit/test_repo.rb test/unit/test_server.rb test/unit/test_server_app.rb test/unit/test_server_cluster.rb test/unit/test_shell.rb test/unit/test_sunshine.rb test/unit/test_svn_repo.rb test/unit/test_unicorn.rb diff --git a/templates/sunshine/middleware/health.rb b/templates/sunshine/middleware/health.rb deleted file mode 100644 index d40710e..0000000 --- a/templates/sunshine/middleware/health.rb +++ /dev/null @@ -1,58 +0,0 @@ -module Sunshine - - class Health - - ## - # Default healthcheck request path. - - DEFAULT_REQUEST_PATH = '/_health' - - - ## - # The healthcheck-enabled file. - - HEALTHCHECK_FILE = '../../health.enabled' - - - ## - # Creates a new SunshineHealth middleware. Supported options are: - # :uri_path:: The path that healthcheck will be used on. - # :health_file:: The file to check for health. - - def initialize app, options={} - @app = app - @uri_path = options[:uri_path] || DEFAULT_REQUEST_PATH - @healthcheck_file = options[:health_file] || HEALTHCHECK_FILE - end - - - def call env - check_health?(env) ? health_response : @app.call(env) - end - - - ## - # Given the rack env, do we need to perform a health check? - - def check_health? env - env['PATH_INFO'] == @uri_path - end - - - ## - # Check if healthcheck is enabled. - - def health_enabled? - File.file? @healthcheck_file - end - - - ## - # Get a rack response for the current health status. - - def health_response - status, body = health_enabled? ? [200, "OK"] : [404, "404"] - [status, {'Content-Type' => 'text/html'}, body] - end - end -end
jcasts/sunshine
3577f1e12bfaac5817e681647c9e181a653f4602
removed healthcheck entirely
diff --git a/History.txt b/History.txt index 9cffd96..925226c 100644 --- a/History.txt +++ b/History.txt @@ -1,375 +1,383 @@ +=== 1.3.0 / 2010 + +* Bugfixes: + + * Removed superfluous App#upload_tasks method. + + * Lots of rdoc updates. + === 1.2.2 / 2010-10-13 * Bugfixes: * Added support for ruby 1.9.2 === 1.2.1 / 2010-10-05 * Improvements: * Added customizable behaviors for sigint and failures during deploys. * Added Sunshine irb shell to work directly with deploying apps. * Added ability to launch a pseudo terminal from a RemoteShell. * Added exit code to CmdError. * Added exclude paths for checkout by copy. * Bugfixes: * Fixed custom scripts. * Fixed deploy env defaults. * Removed Shell#update_timeout as it was unnecessary. * RemoteShell rsync recurses by default. * Fixed start and stop script permissions when calling sunshine commands. === 1.2.0 / 2010-09-08 * Improvements: * Added better support for custom env/start/stop/restart scripts. * Added scripts sunshine command to call custom scripts remotely. * Deploy env defaults to ENV 'DEPLOY_ENV', 'env', 'RACK_ENV', or 'RAILS_ENV'. * Bugfixes: * ServerApp#run_geminstaller no longer defaults to using sudo. * Added better extensible package manager checking to ServerApp. * Fixed Cronjob functionality and added array support. === 1.1.2 / 2010-04-15 * Improvements: * Added array support to App#find. * Added auto registration of Dependency subclasses for scalability. * Added call to App#start in App#deploy. * Bugfixes: * Fixed bug where env wouldn't be applied correctly in control scripts. * Changed App#with_filter to actually change the App#server_apps attribute. * Shell#env_cmd now returns a flattened array. * Added actual check of running process to Daemon#status_cmd. === 1.1.1 / 2010-04-05 * Improvements: * Added Repo subclass registration for greater expandability. * Added support for checking out codebases locally then rsync-ing them. * Bugfixes: * Fixed RemoteShell login script lingering after disconnect. === 1.1.0 / 2010-04-02 * Improvements: * Support for server clustering with the ServerCluster class. * Added Daemon#status method. * Added the -R option for loading external libraries and gems. * Added support for Thin and MongrelRails. * Added Server support for max connections configuration. * Bugfixes: * Daemons no longer create control scripts if they aren't used. * Fixed Rsync repo to auto append "/" to urls for correct rsyncing. === 1.0.3 / 2010-03-26 * Improvements: * Added App#call method. * Added App#with_session and Shell#with_session to reduce login prompts. * Bugfixes: * Geminstaller now always installs with sudo. * Fixed permissions issues with running servers on ports < 1024. * Fixed healthcheck middleware. === 1.0.2 / 2010-03-25 * Bugfixes: * Fixed apache passenger dependency to run as sudo. * Fixed a bug in Repo::detect === 1.0.1 / 2010-03-25 * Bugfixes: * Added json dependency === 1.0.0 / 2010-03-25 * Improvements: * Added auto_dependencies config to turn on/off auto installing things. * Added healthcheck middleware support. * Added support for Apache2 and its passenger implementation. * Removed all Atti-specific code for public release. * Bugfixes: * Fixed Nginx passenger implementation. === 0.0.6 / 2010-03-19 * Major: * Removed DeployServerDispatcher. Dispatching now happens at the App level. * Moved Settler into Sunshine and renamed it to DependencyLib. * Improvements: * Added INT signal handling to exit deploys and close connections gracefully. * Added dependency installation methods apt_install, gem_install, tpkg_install and yum_install to App and ServerApp. * Extended functionality of ServerApp#upload_tasks. * ServerApp now support being instatiated with an App instance (for coordinated deploys) or just with an app name (for post-deploy usage). * Added a Sunshine rakefile template for task-based deploys. Available through: sunshine --rakefile [COPY_TO] * App#name gets auto-assigned by repo info if not provided. * Sunshine::web_directory used to determine App#deploy_path when missing. * Repo#detect now returns a Repo object instead of an array. * Added start/stop/restart/status methods to DeployServerApp. * ServerApp instances with unspecified roles get all roles by default. * App config files now use erb parsing. Any key/value passed the App constructor as a hash should be passed to the erb binding along with the deploy_env. * Added support to bundler for defining multiple dependencies with the same name, and different package managers. * Bugfixes: * Added setup checking to Daemon to only run setup when needed. * Moved healthcheck from App to ServerApp and improved the api. * Renamed DeployServerApp to ServerApp. * Renamed App#deploy_path and App#deploys_dir to App#root_path and App#deploys_path. * Renamed the 'deploy' command to 'run' to more accurately express it's use. * RsyncRepo#do_checkout fixed to match standard Repo#do_checkout methods. * Sunshine::DATA and Sunshine::PATH are now set when running standalone ruby deploy files. === 0.0.5 / 2010-02-26 * Sunshine::App: * Use of DeployServerDispatcher threading * Fixed control script creation to be deploy_server specific (takes roles into account) * Added AttiApp class for ATTi app deployment. * Constuctor supports :deploy_name option for nameable deploys. Defaults to the timestamp. * Auto-detects if the script's directory is a checked out repo and uses it if no repo information was given. * Support for running sass. * Sunshine::DeployServerDispatcher: * Added threading support * Sunshine::Repo: * Added support for detecting a repo type based on a path: Repo.detect [path [, console_or_deploy_server]] #=> [:git, "git://url/of/git/repo", {:tree => "master", ...}] * Moved info instance methods to the class * Support for git-svn: SvnRepo.git_svn? path * Changed the checkout_to method signature * Sunshine::Server: * Added support for ar_sendmail server. === 0.0.4 / 2010-02-12 * Added sudo functionality: * Support for :sudo option on Sunshine::App, Sunshine::Server, and Sunshine::DeployServer constructors, and attr_accessor :sudo * Settler Dependency classes support a default sudo value: Sunshine::Dependencies::Gem.sudo = true # use sudo Sunshine::Dependencies::Gem.sudo = "usr" # use sudo -u usr Sunshine::Dependencies::Gem.sudo = false # ensure sudo is off Sunshine::Dependencies::Gem.sudo = nil # use :call obj precedence * App supports passing a (yml) file object to the constructor. Useful for passing file DATA if desired: app = Sunshine::App.new Sunshine::DATA app.deploy!{|app| Sunshine::Rainbows.new(app).restart } __END__ #yaml for app goes here... * App class changes: * Changed the format of the App#checkout_path directory * Logrotate setup now has to be called explicitely * Commands functionality expanded: * Support for --sudo and --sudo=user on all Sunshine commands * Added --format option for control commands. Supports txt, yml, json. * Control scripts generated on the remote server now keep deploy-time shell_env variables: * Run commands with the --no-env option to run without deploy shell_env variables. * Run any script with the app's env variables using: /path/to/app/env some_command /path/to/app/env EXTRA_VAR=some_value some_command Supports all options the env command supports. * Dependency handling now supports apt. * DeployServers now support passing custom flags for ssh and rsync: deploy_server = DeployServer.new "svr.com", :rsync_flags => [...] deploy_server.call "some_command", :sudo => "user", :flags => '-C' deploy_server.upload "from", "to", :sudo => "user", :flags => ['--chmod=ugo=rwX', '-b'] deploy_server.download "from", "to", :flags => '--ignore-existing' * Repo implementation has significantly changed: * Added support for git repo. * Info about a repo is now retrieved with Repo#get_repo_info: repo.get_repo_info deploy_server, checkout_path * Repo constructor supports options hash with :flags option. === 0.0.3 / 2010-01-29 * Many small bugfixes * Tests, tests, and more tests * Changed DeployServer api * DeployServer#run is not longer supported, use DeployServer#call * Constructor supports a spaced delimited list for roles: DeployServer.new "myhost.com", :roles => "web db other" * Changed how deploy server yaml is parsed. Should parse to be valid on: DeployServer.new *parsed_yaml Example Given: :deploy_servers : - server1.com - - server2.com - - server3.com - :roles : web db other :ssh_flags : '-o ControlMaster=auto' === 0.0.2 / 2010-01-15 * Added Control Commands * add, deploy, list, restart, rm, start, stop * Application support * Changed VERSION file to info and its format to yaml * Deployed apps now have a start, stop and restart script * Added Crontab and log rotation support * Functional changes * Ditched net/ssh and net/scp for ssh and rsync through Open4 * Fixed and updated dependencies to use Yum * Support for sunshine user configuration in ~/.sunshine * Rake tasks * Support to run the app's rake tasks * Built in default ATTi rake tasks === 0.0.1 / 2009-11-18 * 1 major enhancement * First release! diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index 7592d10..9676d09 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -1,1233 +1,1196 @@ module Sunshine ## # App objects are the core of Sunshine deployment. The Sunshine paradygm # is to construct an app object, and run custom deploy code by passing # a block to its deploy method. The following is the simplest way to # instantiate an app: # # app = Sunshine::App.new :remote_shells => "deploy_server.com" # # By default, Sunshine will look in the pwd for scm information and will # extract the app's name. The default root deploy path is specified by # Sunshine.web_directory, in this case: "/srv/http/app_name". # # More complex setups may look like the following: # # someserver = Sunshine::RemoteShell.new "[email protected]", # :roles => [:web, :app] # # myapprepo = Sunshine::SvnRepo.new "svn://my_repo/myapp/tags/release" # # app = Sunshine::App.new :name => 'myapp', # :repo => myapprepo, # :root_path => '/usr/local/myapp', # :remote_shells => someserver # # Note: The instantiation options :repo and :remote_shells support # the same data format that their respective initialize methods support. # The :remote_shells option also supports arrays of remote shell instance # arguments. # # Once an App is instantiated it can be manipulated in a variety of ways, # including deploying it: # # app.deploy do |app| # # app_server = Sunshine::Rainbows.new app, :port => 3000 # web_server = Sunshine::Nginx.new app, :point_to => app_server # # app_server.setup # web_server.setup # end # # The constructor also supports reading multi-env configs fom a yaml file, # which can also be the deploy script's DATA, to allow for concise, # encapsulated deploy files: # # # Load from an explicit yaml file: # Sunshine::App.new "path/to/config.yml" # # # Load from the yaml in the script file's DATA: # Sunshine::App.new # # Yaml files must define settings on a per-environment basis. The default # environment will be used as a base for all other environments: # # #config.yml: # --- # :default: # :repo: # :type: :svn # :url: http://subversion/repo/tags/release-001 # :remote_shells: dev.myserver.com # # qa: # :remote_shells: # - qa1.myserver.com # - qa2.myserver.com # # qa_special: # :inherits: qa # :root_path: /path/to/application # :deploy_env: qa # # By default, App will get the deploy_env value from Sunshine.deploy_env, but # it may also be passed in explicitely as an option. class App ## # Initialize and deploy an application in a single step. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml # # Options supported are: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_checkout:: Boolean - when true, will checkout the codebase # directly from the deploy servers; defaults to false. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] @on_sigint = @on_exception = nil end ## # Call a command on specified server apps. Returns an array of responses. # Supports any App#find and Shell#call options: # app.call "ls -1", :sudo => true, :host => "web.app.com" # #=> [".\n..\ndir1", ".\n..\ndir1", ".\n..\ndir2"] def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Start a persistant connection to app servers. # Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected and returns a boolean. # Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected and returns a boolean. # Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect from app servers. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # If the deploy fails or an exception is raised, it will attempt to # run the Sunshine.exception_behavior, which is set to :revert by # default. However, this is not true of ssh connection failures. # # If the deploy is interrupted by a SIGINT, it will attempt to run # the Sunshine.sigint_behavior, which is set to :revert by default. # - # Note: The deploy method will stop the former deploy just before + # The deploy method will stop the former deploy just before # symlink and the passed block is run. # - # Note: Once deployment is complete, the deploy method will attempt to - # run App#start. + # Once deployment is complete, the deploy method will attempt to + # run App#start! which will run any start script checked into + # App#scripts_path, or the start script that will have been generated + # by using Sunshine server setups. def deploy options=nil state = { :success => false, :stopped => false, :symlinked => false } Sunshine.logger.info :app, "Beginning #{@name} deploy" with_session options do |app| interruptable state do raise DeployError, "No servers defined for #{@name}" if @server_apps.empty? make_app_directories checkout_codebase state[:stopped] = true if stop state[:symlinked] = true if symlink_current_dir yield self if block_given? run_post_user_lambdas - health :enable - build_control_scripts build_deploy_info_file build_crontab register_as_deployed state[:success] = true if start! :force => true end remove_old_deploys if state[:success] rescue Sunshine.logger.error :app, "Could not remove old deploys" state[:success] &&= deployed? end Sunshine.logger.info :app, "Finished #{@name} deploy" if state[:success] state[:success] end ## # Runs the given block while handling SIGINTs and exceptions # according to rules set by Sunshine.sigint_behavior and # Sunshine.exception_behavior or with the override hooks # App#on_sigint and App#on_exception. def interruptable options={} interrupt_trap = TrapStack.add_trap "Interrupted #{@name}" do handle_sigint options end yield if block_given? rescue => e Sunshine.logger.error :app, "#{e.class}: #{e.message}" do Sunshine.logger.error '>>', e.backtrace.join("\n") end handle_exception e, options ensure TrapStack.delete_trap interrupt_trap end ## # Calls the Apps on_sigint hook or the default Sunshine.sigint_behavior. def handle_sigint state={} return @on_sigint.call(state) if @on_sigint handle_interruption Sunshine.sigint_behavior, state end ## # Calls the Apps on_exception hook or the default # Sunshine.exception_behavior. def handle_exception exception, state={} return @on_exception.call(exception, state) if @on_exception handle_interruption Sunshine.exception_behavior, state end ## # Set this to define the behavior of SIGINT during a deploy. # Defines what to do when an INT signal is received when running # a proc through App#interruptable. Used primarily to catch SIGINTs # during deploys. Passes the block a hash with the state of the deploy: # # app.on_sigint do |deploy_state_hash| # deploy_state_hash # #=> {:stopped => true, :symlinked => true, :success => false} # end def on_sigint &block @on_sigint = block end ## # Set this to define the behavior of exceptions during a deploy. # Defines what to do when an exception is received when running # a proc through App#interruptable. Used primarily to catch exceptions # during deploys. Passes the block the exception and a hash with the # state of the deploy: # # app.on_exception do |exception, deploy_state_hash| # # do something... # end def on_exception &block @on_exception = block end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. def handle_interruption behavior, state={} case behavior when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :revert revert! if state[:symlinked] start if state[:stopped] when Sunshine.interactive? && :console self.console! when Sunshine.interactive? && :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" menu.choice(:revert) { handle_interruption :revert, state } menu.choice(:console){ handle_interruption :console, state } menu.choice(:exit) { handle_interruption :exit, state } end else raise DeployError, "Deploy of #{@name} was interrupted." end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. # app.revert! :role => :web def revert! options=nil with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env on all app shells. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. # :exclude:: String|Array - Exclude the specified paths during # a deploy via copy. def checkout_codebase options=nil copy_option = options[:copy] if options exclude = options.delete :exclude if options if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path scm_info[:exclude] = [Sunshine.exclude_paths, exclude].flatten.compact with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully by checking the name of the # deploy on every app server with the instance's deploy name. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. Supports all App#find options. # See Sunshine::ServerApp for more information. def each options=nil, &block server_apps = find options server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Supports all App#find options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end - ## - # Gets or sets the healthcheck state. Returns a hash of host/state - # pairs. State values are :enabled, :disabled, and :down. The method - # argument can be omitted or take a value of :enable, :disable, or :remove: - # app.health - # #=> Returns the health status for all server_apps - # - # app.health :role => :web - # #=> Returns the status of all server_apps of role :web - # - # app.health :enable - # #=> Enables all health checking and returns the status - # - # app.health :disable, :role => :web - # #=> Disables health checking for :web server_apps and returns the status - - def health method=nil, options=nil - valid_methods = [:enable, :disable, :remove] - options = method if options.nil? && Hash === method - - valid_method = valid_methods.include? method - - message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method - message ||= "Getting status of" - message = "#{message} healthcheck" - - statuses = {} - with_server_apps options, :msg => message do |server_app| - server_app.health.send method if valid_method - - statuses[server_app.shell.host] = server_app.health.status - end - - statuses - end - - ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. # Supports all App#find options. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Sunshine::Yum # # Package managers are typically detected automatically by each # individual server_apps. # Supports all App#find options. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. # Supports all App#find options. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. # Supports all App#find options. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app # Supports all App#find options. def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. # Supports all App#find options. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Run the restart script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def restart! options=nil with_server_apps options, :msg => "Running restart script", :send => :restart! end ## # Runs bundler on deploy servers. Supports all App#find options. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] end ## # Runs GemInstaller on deploy servers. Supports all App#find options. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run the given script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def run_script! name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script!, name, options] end ## # Run a sass task on any or all deploy servers. # Supports all App#find options. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. # Supports all App#find options. def shell_env env_hash=nil, options=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps options, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Run the start script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def start! options=nil with_server_apps options, :msg => "Running start script", :send => [:start!, options] end ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. Supports all App#find options. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. # Post-deploy only. Supports all App#find options. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end ## # Run the stop script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. Supports all App#find options. def stop! options=nil with_server_apps options, :msg => "Running stop script", :send => :stop! end ## # Use sudo on all the app's deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. # Supports all App#find options. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! # Supports all App#find options. def threaded_each options=nil, &block mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end # Supports all App#find options. def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here # end # # Note: App#with_server_apps calls App#with_session. If you do not need # or want a server connection you can pass :no_session. def with_server_apps search_options, options={} options = search_options.merge options if Hash === search_options message = options[:msg] method = options[:no_threads] ? :each : :threaded_each auto_session = !options[:no_session] block = lambda do |*| send(method, search_options) do |server_app| if block_given? yield(server_app) elsif options[:send] server_app.send(*options[:send]) end end end msg_block = lambda do |*| if message Sunshine.logger.info(:app, message, &block) else block.call end end auto_session ? with_session(&msg_block) : msg_block.call end ## # Runs block ensuring a connection to remote_shells. # Connecting and disconnecting will be ignored if a session # already exists. Supports all App#find options. # # Ensures that servers are disconnected after the block is run # if servers were not previously connected. def with_session options=nil with_filter options do prev_connection = connected? begin connect unless prev_connection yield self ensure disconnect unless prev_connection end end end private ## # Set all the app paths based on the root deploy path. def set_deploy_paths path @root_path = path || File.join(Sunshine.web_directory, @name) @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end ## # Set the app's deploy servers: # server_apps_from_config "some_server" # #=> [<ServerApp @host="some_server"...>] # # server_apps_from_config ["svr1", "svr2", "svr3"] # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] # # remote_shells = [["svr1", {:roles => "web db app"}], "svr2", "svr3"] # server_apps_from_config remote_shells # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] def server_apps_from_config shells shells = [*shells].compact shells.map{|shell| ServerApp.new(*[self,*shell]) } end ## # Set the app's repo: # repo_from_config SvnRepo.new("myurl") # repo_from_config :type => :svn, :url => "myurl" def repo_from_config repo_def case repo_def when Sunshine::Repo repo_def when Hash Sunshine::Repo.new_of_type repo_def[:type], repo_def[:url], repo_def else Sunshine::Repo.detect Sunshine::PATH end end ## # Load a yml config file, parses it with erb and resolves deploy env # inheritance. def config_from_file config_file, erb_binding=binding, env=@deploy_env return {} unless config_file config_data = YAML.load build_erb(config_file, erb_binding) load_config_for config_data, env end ## # Loads an app yml config file, gets the default config # and the current deploy env and returns a merged config hash. def load_config_for config_hash, env return {} unless config_hash deploy_env_config = (config_hash[env] || {}).dup deploy_env_config[:inherits] ||= [] deploy_env_config[:inherits].unshift(:default) if :default != env && config_hash[:default] diff --git a/lib/sunshine/healthcheck.rb b/lib/sunshine/healthcheck.rb deleted file mode 100644 index 117d74d..0000000 --- a/lib/sunshine/healthcheck.rb +++ /dev/null @@ -1,98 +0,0 @@ -module Sunshine - - ## - # Healthcheck objects handle enabling and disabling health checking for - # load balancers by touching health.enabled and health.disabled files on - # an app's shell. - # - # If you would like to use Sunshine's healthcheck rack middleware, use - # the following command: - # sunshine --middleware your_middleware_dir - # - # Then simply specify the following in your config.ru: - # require 'your_middleware_dir/health' - # use Sunshine::Health - # - # Sunshine::Health supports the following options: - # :uri_path:: The path that healthcheck will be used on. - # :health_file:: The file to check for health. - # - # use Sunshine::Health, :uri_path => "/health.txt", - # :health_file => "health.txt" - - class Healthcheck - - ENABLED_FILE = "health.enabled" - DISABLED_FILE = "health.disabled" - - attr_accessor :shell, :enabled_file, :disabled_file - - def initialize path, shell - @shell = shell - @enabled_file = File.join path, ENABLED_FILE - @disabled_file = File.join path, DISABLED_FILE - end - - - ## - # Disables healthcheck - status: :disabled - - def disable - @shell.call "touch #{@disabled_file} && rm -f #{@enabled_file}" - end - - - ## - # Check if healthcheck is disabled. - - def disabled? - @shell.file? @disabled_file - end - - - ## - # Check if healthcheck is down. - - def down? - [email protected]?(@disabled_file) && [email protected]?(@enabled_file) - end - - - ## - # Enables healthcheck which should set status to :ok - - def enable - @shell.call "rm -f #{@disabled_file} && touch #{@enabled_file}" - end - - - ## - # Check if healthcheck is enabled. - - def enabled? - @shell.file? @enabled_file - end - - - ## - # Remove the healthcheck file - status: :down - - def remove - @shell.call "rm -f #{@disabled_file} #{@enabled_file}" - end - - - ## - # Get the health status from the shell. - # Returns one of three states: - # :enabled: everything is great - # :disabled: healthcheck was explicitely turned off - # :down: um, something is wrong - - def status - return :disabled if disabled? - return :enabled if enabled? - :down - end - end -end diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index 90f9636..2e8d639 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -1,646 +1,645 @@ module Sunshine ## # Handles App deployment functionality for a single deploy server. # # Server apps can be assigned any number of roles for classification. # :roles:: sym|array - roles assigned (web, db, app, etc...) # By default server apps get the special :all role which will # always return true when calling: # server_app.has_roles? :some_role # # ServerApp objects can be instantiated several ways: # ServerApp.new app_instance, shell_instance, options_hash # # When passing an App instance, the new ServerApp will keep an active link # to the app's properties. Name, deploy, and path attributes will be # actively linked. # # Rely on ServerApp to create a RemoteShell instance to use: # ServerApp.new app_instance, "host.com", options_hash # # Instantiate with app name and rely on Sunshine defaults for app paths: # ServerApp.new "app_name", shell_instance, options_hash # # Explicitely assign the app's root path: # ServerApp.new "app_name", ..., :root_path => "/path/to/app_root" # # Assigning a specific deploy name to use can be done with the # :deploy_name option: # ServerApp.new "app_name", ..., :deploy_name => "deploy" class ServerApp ## # Define an attribute that will get a value from app, or locally if # @app isn't set. def self.app_attr *attribs attribs.each do |attrib| class_eval <<-STR, __FILE__, __LINE__ + 1 def #{attrib} @app ? @app.send(:#{attrib}) : @#{attrib} end STR end end ## # Creates dependency instance methods such as gem_install, yum_install, etc # on both App and ServerApp classes. def self.register_dependency_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = Hash === names.last ? names.delete_at(-1) : Hash.new names.each do |name| dep = #{dep_class}.new(name, options) dep.install! :call => @shell end end STR App.class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = names.last if Hash === names.last with_server_apps options, :msg => "Installing #{dep_class.short_name} packages", :send => [:#{dep_class.short_name}_install, *names] end STR end ## # Creates a ServerApp instance from a deploy info file. def self.from_info_file path, shell=nil shell ||= Sunshine.shell opts = YAML.load shell.call("cat #{path}") opts[:root_path] = opts.delete :path sa_shell = shell.dup sa_shell.env = opts[:env] || Hash.new sa_shell.connect if shell.connected? new opts[:name], sa_shell, opts end app_attr :name, :deploy_name app_attr :root_path, :checkout_path, :current_path app_attr :deploys_path, :log_path, :shared_path, :scripts_path - attr_accessor :app, :roles, :scripts, :info, :shell, :crontab, :health + attr_accessor :app, :roles, :scripts, :info, :shell, :crontab attr_writer :pkg_manager ## # Create a server app instance. Supports the following # argument configurations: # # ServerApp.new app_inst, "myserver.com", :roles => :web # ServerApp.new "app_name", shell_inst, options_hash def initialize app, host, options={} @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell - @health = Healthcheck.new shared_path, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No status for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path, :sunshine_version => Sunshine::VERSION }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec self.root_path, 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's restart script. Raises an exception on failure. # Post-deploy only. def restart! # Permissions are handled by the script, use: :sudo => false run_script! :restart, :sudo => false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the root_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} run_script! name, options, &block rescue false end ## # Runs a script from the root_path. Raises an exception if the status # code is not 0. # Post-deploy only. def run_script! name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script! :status, :sudo => false true rescue CmdError => e return false if e.exit_code == Daemon::STATUS_DOWN_CODE raise e end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Run the app's start script. Raises an exception on failure. # Post-deploy only. def start! options=nil options ||= {} if running? return unless options[:force] stop! end # Permissions are handled by the script, use: :sudo => false run_script! :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's stop script. Raises an exception on failure. # Post-deploy only. def stop! # Permissions are handled by the script, use: :sudo => false run_script! :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") diff --git a/test/unit/test_healthcheck.rb b/test/unit/test_healthcheck.rb deleted file mode 100644 index 89f59d5..0000000 --- a/test/unit/test_healthcheck.rb +++ /dev/null @@ -1,70 +0,0 @@ -require 'test/test_helper' - -class TestHealthcheck < Test::Unit::TestCase - - def setup - @remote_shell = mock_remote_shell - @health = Sunshine::Healthcheck.new "somepath", @remote_shell - - @test_disabled = "test -f #{@health.disabled_file}" - @test_enabled = "test -f #{@health.enabled_file}" - end - - - def test_initialize - assert_equal @remote_shell, @health.shell - assert_equal "somepath/health.enabled", @health.enabled_file - assert_equal "somepath/health.disabled", @health.disabled_file - end - - - def test_disable - @health.disable - - cmd = "touch #{@health.disabled_file} && rm -f #{@health.enabled_file}" - assert_ssh_call cmd - end - - - def test_enable - @health.enable - - cmd = "rm -f #{@health.disabled_file} && touch #{@health.enabled_file}" - assert_ssh_call cmd - end - - - def test_remove - @health.remove - - cmd = "rm -f #{@health.disabled_file} #{@health.enabled_file}" - assert_ssh_call cmd - end - - - def test_status_down - @remote_shell.set_mock_response 1, - @test_disabled => [:err, ""], - @test_enabled => [:err, ""] - - assert_equal(:down, @health.status) - - assert_ssh_call @test_disabled - assert_ssh_call @test_enabled - end - - - def test_status_ok - @remote_shell.set_mock_response 1, @test_disabled => [:err, ""] - @remote_shell.set_mock_response 0, @test_enabled => [:out, ""] - - assert_equal(:enabled, @health.status) - end - - - def test_status_disabled - @remote_shell.set_mock_response 0, @test_disabled => [:out, ""] - - assert_equal(:disabled, @health.status) - end -end
jcasts/sunshine
8981ae21c95a12aed8c83915eb1a1c1634781b8e
revamped App rdoc and removed upload_tasks
diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index ce7e8d1..7592d10 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -1,1289 +1,1256 @@ module Sunshine ## # App objects are the core of Sunshine deployment. The Sunshine paradygm # is to construct an app object, and run custom deploy code by passing - # a block to its deploy method: + # a block to its deploy method. The following is the simplest way to + # instantiate an app: + # + # app = Sunshine::App.new :remote_shells => "deploy_server.com" + # + # By default, Sunshine will look in the pwd for scm information and will + # extract the app's name. The default root deploy path is specified by + # Sunshine.web_directory, in this case: "/srv/http/app_name". + # + # More complex setups may look like the following: # # someserver = Sunshine::RemoteShell.new "[email protected]", # :roles => [:web, :app] # - # options = { - # :name => 'myapp', - # :repo => {:type => :svn, :url => 'svn://blah...'}, - # :root_path => '/usr/local/myapp', - # :remote_shells => '[email protected]' - # } + # myapprepo = Sunshine::SvnRepo.new "svn://my_repo/myapp/tags/release" + # + # app = Sunshine::App.new :name => 'myapp', + # :repo => myapprepo, + # :root_path => '/usr/local/myapp', + # :remote_shells => someserver # - # app = Sunshine::App.new(options) + # Note: The instantiation options :repo and :remote_shells support + # the same data format that their respective initialize methods support. + # The :remote_shells option also supports arrays of remote shell instance + # arguments. + # + # Once an App is instantiated it can be manipulated in a variety of ways, + # including deploying it: # # app.deploy do |app| # # app_server = Sunshine::Rainbows.new app, :port => 3000 # web_server = Sunshine::Nginx.new app, :point_to => app_server # # app_server.setup # web_server.setup # end # - # Multiple apps can be defined, and deployed from a single deploy script. - # The constructor also supports passing a yaml file path: - # - # Sunshine::App.new("path/to/config.yml") + # The constructor also supports reading multi-env configs fom a yaml file, + # which can also be the deploy script's DATA, to allow for concise, + # encapsulated deploy files: # - # Deployment can be expressed more concisely by calling App::deploy: - # - # App.deploy("path/to/config.yml") do |app| - # Sunshine::Rainbows.new(app).setup - # end + # # Load from an explicit yaml file: + # Sunshine::App.new "path/to/config.yml" # - # - # An App holds information about where to deploy an application to and - # how to deploy it, as well as many convenience methods to setup and - # manipulate the deployment process. Most of these methods support passing - # remote shell find options: - # - # app.rake 'db:migrate', :role => :db - # app.deploy :host => 'server1.com' - # - # See App#find for more information. - # - # App instantiation can be done in several ways: - # App.new instantiation_hash - # App.new "path/to/config.yml", optional_extra_hash - # App.new #=> will attempt to load ruby's file DATA as yaml + # # Load from the yaml in the script file's DATA: + # Sunshine::App.new # # Yaml files must define settings on a per-environment basis. The default - # environment will be used if the deploy_env is not found in the config. - # Let's consider the following config: + # environment will be used as a base for all other environments: # # #config.yml: # --- # :default: # :repo: # :type: :svn # :url: http://subversion/repo/tags/release-001 # :remote_shells: dev.myserver.com # - # :qa: + # qa: # :remote_shells: # - qa1.myserver.com # - qa2.myserver.com # - # :qa_special: - # :inherits: :qa + # qa_special: + # :inherits: qa # :root_path: /path/to/application + # :deploy_env: qa # - # By default, environment definitions inherit the :default environment. In - # this instance, :qa_special also inherits from :qa. - # With the given config, I could setup the App instance as so: - # - # App.new "config.yml", :deploy_env => :development - # # Note: by default, App will get the deploy_env value - # # from Sunshine.deploy_env - # - # The above will simply load the default config. The following, however, - # will load the :qa_special config which inherits from - # both :qa and :default: - # - # App.new "config.yml", :deploy_env => :qa_special - # - # - # Another way of instantiating an App is to pass it a hash. Unlike the yaml - # config file, the hash is not on a per-environment basis and isexpected - # to already have the correct values for the given environment. - # The following is equivalent to loading the above :default environment: - # - # App.new :remote_shells => "dev.myserver.com", - # :repo => { - # :type => :svn, - # :url => "http://subversion/repo/tags/release-001" - # } - # - # In theory, the minimum amount of information required to instantiate - # an app is the repo and remote_shells. If the repo option is omitted, - # the App will attempt to detect if the pwd is a checkout out repo and - # use that information. If you would like to deploy an application that - # is not under source countrol, you may do so by using Sunshine::RsyncRepo, - # or passing :rsync in your hash as your repo type. - # - # - # Options supported by App.new are the following: - # - # :deploy_env:: String - specify the env to deploy with; defaults to - # Sunshine#deploy_env. - # - # :deploy_name:: String - if you want to specify a name for your deploy and - # checkout directory (affects the checkout_path); defaults to Time.now.to_i. - # - # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for - # deployment. Accepts any single instance or array of a Sunshine::Shell - # type instance or Sunshine::Shell instantiator-friendly arguments. - # - # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. - # Accepts any hash that can be passed to Sunshine::Repo::new_of_type - # or any Sunshine::Repo object. - # - # :root_path:: String - the absolute path the deployed application - # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". - # - # :shell_env:: Hash - environment variables to add to deploy shells. - # - # :sudo:: true|false|nil|String - which sudo value should be assigned to - # deploy shells; defaults to Sunshine#sudo. For more information on using - # sudo, see the Using Permissions section in README.txt. + # By default, App will get the deploy_env value from Sunshine.deploy_env, but + # it may also be passed in explicitely as an option. class App ## - # Initialize and deploy an application. + # Initialize and deploy an application in a single step. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml + # + # Options supported are: + # + # :deploy_env:: String - specify the env to deploy with; defaults to + # Sunshine#deploy_env. + # + # :deploy_name:: String - if you want to specify a name for your deploy and + # checkout directory (affects the checkout_path); defaults to Time.now.to_i. + # + # :remote_checkout:: Boolean - when true, will checkout the codebase + # directly from the deploy servers; defaults to false. + # + # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for + # deployment. Accepts any single instance or array of a Sunshine::Shell + # type instance or Sunshine::Shell instantiator-friendly arguments. + # + # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. + # Accepts any hash that can be passed to Sunshine::Repo::new_of_type + # or any Sunshine::Repo object. + # + # :root_path:: String - the absolute path the deployed application + # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". + # + # :shell_env:: Hash - environment variables to add to deploy shells. + # + # :sudo:: true|false|nil|String - which sudo value should be assigned to + # deploy shells; defaults to Sunshine#sudo. For more information on using + # sudo, see the Using Permissions section in README.txt. def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] @on_sigint = @on_exception = nil end ## - # Call a command on specified server apps. - # Supports any App#find and Shell#call options. + # Call a command on specified server apps. Returns an array of responses. + # Supports any App#find and Shell#call options: + # app.call "ls -1", :sudo => true, :host => "web.app.com" + # #=> [".\n..\ndir1", ".\n..\ndir1", ".\n..\ndir2"] def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## - # Connect server apps. Supports any App#find options. + # Start a persistant connection to app servers. + # Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected and returns a boolean. # Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected and returns a boolean. # Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## - # Disconnect server apps. Supports any App#find options. + # Disconnect from app servers. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # If the deploy fails or an exception is raised, it will attempt to - # run the Sunshine.failed_deploy_behavior, which is set to :revert by + # run the Sunshine.exception_behavior, which is set to :revert by # default. However, this is not true of ssh connection failures. # # If the deploy is interrupted by a SIGINT, it will attempt to run # the Sunshine.sigint_behavior, which is set to :revert by default. # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil state = { :success => false, :stopped => false, :symlinked => false } Sunshine.logger.info :app, "Beginning #{@name} deploy" with_session options do |app| interruptable state do raise DeployError, "No servers defined for #{@name}" if @server_apps.empty? make_app_directories checkout_codebase state[:stopped] = true if stop state[:symlinked] = true if symlink_current_dir yield self if block_given? run_post_user_lambdas health :enable build_control_scripts build_deploy_info_file build_crontab register_as_deployed state[:success] = true if start! :force => true end remove_old_deploys if state[:success] rescue Sunshine.logger.error :app, "Could not remove old deploys" state[:success] &&= deployed? end Sunshine.logger.info :app, "Finished #{@name} deploy" if state[:success] state[:success] end ## - # Handles SIGINTs and exceptions according to rules set by - # Sunshine.sigint_behavior and Sunshine.exception_behavior - # or with the override hooks App#on_sigint and App#on_exception. + # Runs the given block while handling SIGINTs and exceptions + # according to rules set by Sunshine.sigint_behavior and + # Sunshine.exception_behavior or with the override hooks + # App#on_sigint and App#on_exception. def interruptable options={} interrupt_trap = TrapStack.add_trap "Interrupted #{@name}" do handle_sigint options end yield if block_given? rescue => e Sunshine.logger.error :app, "#{e.class}: #{e.message}" do Sunshine.logger.error '>>', e.backtrace.join("\n") end handle_exception e, options ensure TrapStack.delete_trap interrupt_trap end ## # Calls the Apps on_sigint hook or the default Sunshine.sigint_behavior. def handle_sigint state={} return @on_sigint.call(state) if @on_sigint handle_interruption Sunshine.sigint_behavior, state end ## # Calls the Apps on_exception hook or the default # Sunshine.exception_behavior. def handle_exception exception, state={} return @on_exception.call(exception, state) if @on_exception handle_interruption Sunshine.exception_behavior, state end ## # Set this to define the behavior of SIGINT during a deploy. # Defines what to do when an INT signal is received when running # a proc through App#interruptable. Used primarily to catch SIGINTs # during deploys. Passes the block a hash with the state of the deploy: # # app.on_sigint do |deploy_state_hash| # deploy_state_hash # #=> {:stopped => true, :symlinked => true, :success => false} # end def on_sigint &block @on_sigint = block end ## # Set this to define the behavior of exceptions during a deploy. # Defines what to do when an exception is received when running # a proc through App#interruptable. Used primarily to catch exceptions # during deploys. Passes the block the exception and a hash with the # state of the deploy: # # app.on_exception do |exception, deploy_state_hash| # # do something... # end def on_exception &block @on_exception = block end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. def handle_interruption behavior, state={} case behavior when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :revert revert! if state[:symlinked] start if state[:stopped] when Sunshine.interactive? && :console self.console! when Sunshine.interactive? && :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" menu.choice(:revert) { handle_interruption :revert, state } menu.choice(:console){ handle_interruption :console, state } menu.choice(:exit) { handle_interruption :exit, state } end else raise DeployError, "Deploy of #{@name} was interrupted." end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. + # app.revert! :role => :web - def revert!(options=nil) + def revert! options=nil with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## - # Add paths the the shell $PATH env. + # Add paths the the shell $PATH env on all app shells. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. + # :exclude:: String|Array - Exclude the specified paths during + # a deploy via copy. def checkout_codebase options=nil copy_option = options[:copy] if options - exclude = options.delete(:exclude) if options + exclude = options.delete :exclude if options if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path scm_info[:exclude] = [Sunshine.exclude_paths, exclude].flatten.compact with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## - # Check if app has been deployed successfully. + # Check if app has been deployed successfully by checking the name of the + # deploy on every app server with the instance's deploy name. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## - # Iterate over each server app. + # Iterate over each server app. Supports all App#find options. + # See Sunshine::ServerApp for more information. - def each(options=nil, &block) - server_apps = find(options) + def each options=nil, &block + server_apps = find options server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## - # Decrypt a file using gpg. Allows all DeployServerDispatcher#find - # options, plus: + # Decrypt a file using gpg. Supports all App#find options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. + # Supports all App#find options. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories end ## # Assign the prefered package manager to all server_apps: - # app.prefer_pkg_manager Settler::Yum + # app.prefer_pkg_manager Sunshine::Yum # # Package managers are typically detected automatically by each # individual server_apps. + # Supports all App#find options. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. + # Supports all App#find options. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. + # Supports all App#find options. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app + # Supports all App#find options. def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. + # Supports all App#find options. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. - # Post-deploy only. + # Post-deploy only. Supports all App#find options. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Run the restart script of a deployed app on the specified # deploy servers. Raises an exception on failure. - # Post-deploy only. + # Post-deploy only. Supports all App#find options. def restart! options=nil with_server_apps options, :msg => "Running restart script", :send => :restart! end ## - # Runs bundler on deploy servers. + # Runs bundler on deploy servers. Supports all App#find options. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] end ## - # Runs GemInstaller on deploy servers. + # Runs GemInstaller on deploy servers. Supports all App#find options. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. - # Post-deploy only. + # Post-deploy only. Supports all App#find options. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run the given script of a deployed app on the specified # deploy servers. Raises an exception on failure. - # Post-deploy only. + # Post-deploy only. Supports all App#find options. def run_script! name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script!, name, options] end ## # Run a sass task on any or all deploy servers. + # Supports all App#find options. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. + # Supports all App#find options. - def shell_env env_hash=nil + def shell_env env_hash=nil, options=nil env_hash ||= {} @shell_env.merge!(env_hash) - with_server_apps :all, + with_server_apps options, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. - # Post-deploy only. + # Post-deploy only. Supports all App#find options. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Run the start script of a deployed app on the specified # deploy servers. Raises an exception on failure. - # Post-deploy only. + # Post-deploy only. Supports all App#find options. def start! options=nil with_server_apps options, :msg => "Running start script", :send => [:start!, options] end ## # Get a hash of which deploy server apps are :running or :down. - # Post-deploy only. + # Post-deploy only. Supports all App#find options. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. - # Post-deploy only. + # Post-deploy only. Supports all App#find options. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end ## # Run the stop script of a deployed app on the specified # deploy servers. Raises an exception on failure. - # Post-deploy only. + # Post-deploy only. Supports all App#find options. def stop! options=nil with_server_apps options, :msg => "Running stop script", :send => :stop! end ## - # Use sudo on deploy servers. Set to true/false, or + # Use sudo on all the app's deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. + # Supports all App#find options. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! + # Supports all App#find options. - def threaded_each(options=nil, &block) + def threaded_each options=nil, &block mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end - ## - # Upload common rake tasks from the sunshine lib. - # app.upload_tasks - # #=> upload all tasks - # app.upload_tasks 'app', 'common', :role => :web - # #=> upload app and common rake files - # - # Allows standard DeployServerDispatcher#find options, plus: - # :remote_path:: str - the remote absolute path to upload the files to - - def upload_tasks *files - options = Hash === files.last ? files.last.dup : {} - - options.delete(:remote_path) - options = :all if options.empty? - - with_server_apps options, - :msg => "Uploading tasks: #{files.join(" ")}", - :send => [:upload_tasks, *files] - end - - ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end + # Supports all App#find options. def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here # end # # Note: App#with_server_apps calls App#with_session. If you do not need # or want a server connection you can pass :no_session. def with_server_apps search_options, options={} options = search_options.merge options if Hash === search_options message = options[:msg] method = options[:no_threads] ? :each : :threaded_each auto_session = !options[:no_session] block = lambda do |*| send(method, search_options) do |server_app| if block_given? yield(server_app) elsif options[:send] server_app.send(*options[:send]) end end end msg_block = lambda do |*| if message Sunshine.logger.info(:app, message, &block) else block.call end end auto_session ? with_session(&msg_block) : msg_block.call end ## # Runs block ensuring a connection to remote_shells. # Connecting and disconnecting will be ignored if a session # already exists. Supports all App#find options. # # Ensures that servers are disconnected after the block is run # if servers were not previously connected. def with_session options=nil with_filter options do prev_connection = connected? begin connect unless prev_connection yield self ensure disconnect unless prev_connection end end end private ## # Set all the app paths based on the root deploy path. def set_deploy_paths path @root_path = path || File.join(Sunshine.web_directory, @name) @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end ## # Set the app's deploy servers: # server_apps_from_config "some_server" # #=> [<ServerApp @host="some_server"...>] # # server_apps_from_config ["svr1", "svr2", "svr3"] # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] # # remote_shells = [["svr1", {:roles => "web db app"}], "svr2", "svr3"] # server_apps_from_config remote_shells # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] def server_apps_from_config shells shells = [*shells].compact shells.map{|shell| ServerApp.new(*[self,*shell]) } end ## # Set the app's repo: # repo_from_config SvnRepo.new("myurl") # repo_from_config :type => :svn, :url => "myurl" def repo_from_config repo_def case repo_def when Sunshine::Repo repo_def when Hash Sunshine::Repo.new_of_type repo_def[:type], repo_def[:url], repo_def else Sunshine::Repo.detect Sunshine::PATH end end ## # Load a yml config file, parses it with erb and resolves deploy env # inheritance. def config_from_file config_file, erb_binding=binding, env=@deploy_env return {} unless config_file config_data = YAML.load build_erb(config_file, erb_binding) load_config_for config_data, env end ## # Loads an app yml config file, gets the default config # and the current deploy env and returns a merged config hash. def load_config_for config_hash, env return {} unless config_hash deploy_env_config = (config_hash[env] || {}).dup deploy_env_config[:inherits] ||= [] deploy_env_config[:inherits].unshift(:default) if :default != env && config_hash[:default] merge_config_inheritance deploy_env_config, config_hash end ## # Recursively merges config hashes based on the value at :inherits def merge_config_inheritance main_config, all_configs new_config = {} parents = [*main_config[:inherits]].compact parents.each do |config_name| parent = all_configs[config_name] parent = merge_config_inheritance parent, all_configs new_config = new_config.merge parent end new_config.merge main_config # Two merges important for inheritance order end end end diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index 4f2aa7b..90f9636 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -160,586 +160,547 @@ module Sunshine build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No status for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path, :sunshine_version => Sunshine::VERSION }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec self.root_path, 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's restart script. Raises an exception on failure. # Post-deploy only. def restart! # Permissions are handled by the script, use: :sudo => false run_script! :restart, :sudo => false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the root_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} run_script! name, options, &block rescue false end ## # Runs a script from the root_path. Raises an exception if the status # code is not 0. # Post-deploy only. def run_script! name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script! :status, :sudo => false true rescue CmdError => e return false if e.exit_code == Daemon::STATUS_DOWN_CODE raise e end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Run the app's start script. Raises an exception on failure. # Post-deploy only. def start! options=nil options ||= {} if running? return unless options[:force] stop! end # Permissions are handled by the script, use: :sudo => false run_script! :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's stop script. Raises an exception on failure. # Post-deploy only. def stop! # Permissions are handled by the script, use: :sudo => false run_script! :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} excludes = scm_info.delete :exclude if scm_info[:exclude] excludes = [excludes].flatten.compact excludes.map!{|e| "--exclude #{e}"} repo = RsyncRepo.new code_dir, :flags => excludes repo.checkout_to self.checkout_path, @shell @info[:scm] = scm_info end - ## - # Upload common rake tasks from a local path or the sunshine lib. - # app.upload_tasks - # #=> upload all tasks - # app.upload_tasks 'app', 'common', ... - # #=> upload app and common rake files - # - # File paths may also be used instead of the file's base name but - # directory structures will not be followed: - # app.upload_tasks 'lib/common/app.rake', 'lib/do_thing.rake' - # - # Allows options: - # :local_path:: str - the path to get rake tasks from - # :remote_path:: str - the remote absolute path to upload the files to - - def upload_tasks *files - options = Hash === files[-1] ? files.delete_at(-1) : {} - remote_path = options[:remote_path] || "#{self.checkout_path}/lib/tasks" - local_path = options[:local_path] || "#{Sunshine::ROOT}/templates/tasks" - - @shell.call "mkdir -p #{remote_path}" - - files.map! do |file| - if File.basename(file) == file - File.join(local_path, "#{file}.rake") - else - file - end - end - - files = Dir.glob("#{Sunshine::ROOT}/templates/tasks/*") if files.empty? - - files.each do |file| - remote_file = File.join remote_path, File.basename(file) - @shell.upload file, remote_file - end - end - - ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end end end diff --git a/test/unit/test_app.rb b/test/unit/test_app.rb index d40c9ae..a5a0ac7 100644 --- a/test/unit/test_app.rb +++ b/test/unit/test_app.rb @@ -49,594 +49,551 @@ class TestApp < Test::Unit::TestCase def test_initialize_with_file_object file = File.open TEST_APP_CONFIG_FILE app = Sunshine::App.new file config = YAML.load_file(TEST_APP_CONFIG_FILE)[:default] assert_attributes_equal config, app end def test_initialize_with_options assert_attributes_equal @config, @app end def test_initialize_with_options_and_config_file app = Sunshine::App.new TEST_APP_CONFIG_FILE, @config assert_attributes_equal @config, app end def test_app_deploy yield_called = false @app.deploy do |app| assert app.connected? yield_called = true end assert [email protected]? setup_cmd = "test -d #{@app.checkout_path} && rm -rf #{@app.checkout_path}"+ " || echo false" mkdir_cmd = "mkdir -p #{@app.checkout_path}" checkout_cmd = "svn checkout " + "#{@app.repo.scm_flags} #{@app.repo.url} #{@app.checkout_path}" run_results = [ "mkdir -p #{@app.server_apps.first.directories.join(" ")}", setup_cmd, mkdir_cmd, checkout_cmd, "ln -sfT #{@app.checkout_path} #{@app.current_path}" ] @app.each do |server_app| use_remote_shell server_app.shell run_results.each_index do |i| assert_ssh_call run_results[i] end end assert yield_called end TEST_CONFIG = <<-STR :conf1: :common: "conf1" :from_conf1: true :not_conf4: "conf1" :conf2: :inherits: :conf1 :common: "conf2" :from_conf2: true :not_conf4: "conf2" :conf3: :common: "conf3" :from_conf3: true :not_conf4: "conf3" :conf4: :inherits: - :conf2 - :conf3 :common: "conf4" :from_conf4: true STR def test_merge_config_inheritance all_configs = YAML.load TEST_CONFIG main_conf = all_configs[:conf2] main_conf = @app.send(:merge_config_inheritance, main_conf, all_configs) assert main_conf[:from_conf1] assert_equal "conf2", main_conf[:common] end def test_multiple_merge_config_inheritance all_configs = YAML.load TEST_CONFIG main_conf = all_configs[:conf4] main_conf = @app.send(:merge_config_inheritance, main_conf, all_configs) assert main_conf[:from_conf1] assert main_conf[:from_conf2] assert main_conf[:from_conf3] assert_equal "conf4", main_conf[:common] assert_equal "conf3", main_conf[:not_conf4] end class MockError < Exception; end def test_app_deploy_error_handling [ MockError, Sunshine::DeployError ].each do |error| begin app = Sunshine::App.deploy @config do |app| raise error, "#{error} was not caught" end rescue MockError => e assert_equal MockError, e.class end end end def test_revert set_mock_response_for @app, 0, "ls -rc1 #{@app.deploys_path}" => [:out, "last_deploy_dir"] @app.revert! @app.each do |sa| use_remote_shell sa.shell assert_ssh_call "rm -rf #{@app.checkout_path}" assert_ssh_call "ls -rc1 #{@app.deploys_path}" last_deploy = "#{@app.deploys_path}/last_deploy_dir" assert_ssh_call "ln -sfT #{last_deploy} #{@app.current_path}" end end def test_build_control_scripts scripts_list = %w{start stop restart custom env} @app.server_apps.each do |sa| sa.shell.mock :file?, :return => false end @app.add_to_script :start, "start script" @app.add_to_script :stop, "stop script" @app.add_to_script :custom, "custom script" @app.build_control_scripts each_remote_shell do |ds| scripts_list.each do |script| assert_rsync(/#{script}/, "#{ds.host}:#{@app.scripts_path}/#{script}") end end end def test_build_deploy_info_file @app.build_deploy_info_file each_remote_shell do |ds| assert_rsync(/info/, "#{ds.host}:#{@app.scripts_path}/info") end end def test_build_erb erb_file = File.join(@tmpdir, "tmp.erb") FileUtils.mkdir_p @tmpdir File.open(erb_file, "w+") do |f| f.write "<%= name %>" end name = "test name" local_name = @app.build_erb(erb_file, binding) app_name = @app.build_erb(erb_file) assert_equal name, local_name assert_equal @app.name, app_name end def test_call calls = 0 @app.call "test call", :sudo => true do |type, data, inn| calls += 1 end assert_equal calls, @app.server_apps.length args = ["test call", {:sudo => true}] @app.each do |server_app| assert server_app.shell.method_called?(:call, :args => args) end end def test_checkout_codebase @app.checkout_codebase each_remote_shell do |ds| path = @app.checkout_path setup_cmd = "test -d #{path} && rm -rf #{path} || echo false" url = @app.repo.url flags = @app.repo.scm_flags checkout_cmd = "svn checkout #{flags} #{url} #{path}" assert_ssh_call setup_cmd assert_ssh_call checkout_cmd end end def test_checkout_local_codebase tmp_path = File.join Sunshine::TMP_DIR, "#{@app.name}_checkout" @app.repo.extend MockObject @app.repo.mock :checkout_to, :args => [tmp_path], :return => {:test => "scm info"} @app.each do |sa| sa.mock :upload_codebase end @app.checkout_codebase :copy => true @app.each do |sa| assert sa.method_called?(:upload_codebase, :args => [tmp_path, {:test => "scm info", :exclude => []}]) end end def test_checkout_local_codebase_with_exludes Sunshine.exclude_paths.concat ["path1/", "path2/"] tmp_path = File.join Sunshine::TMP_DIR, "#{@app.name}_checkout" @app.repo.extend MockObject @app.repo.mock :checkout_to, :args => [tmp_path], :return => {:test => "scm info"} @app.each do |sa| sa.mock :upload_codebase end @app.checkout_codebase :copy => true, :exclude => ["path3/", "path4/"] @app.each do |sa| assert sa.method_called?(:upload_codebase, :args => [tmp_path, {:test => "scm info", :exclude => ["path1/", "path2/", "path3/", "path4/"]}]) end end def test_deployed? set_mock_response_for @app, 0, "cat #{@app.root_path}/info" => [:out, "---\n:deploy_name: '#{@app.deploy_name}'"] deployed = @app.deployed? state = true @app.server_apps.each do |sa| assert sa.method_called?(:deployed?) set_mock_response_for sa.shell, 0, "cat #{@app.current_path}/info" => [:out, "---\n:deploy_name: '#{@app.deploy_name}'"] state = false unless sa.deployed? end assert_equal state, deployed assert deployed end def test_install_deps nginx_dep = Sunshine.dependencies.get 'nginx' ruby_dep = Sunshine.dependencies.get 'ruby' yum_sudo = Sunshine::Yum.sudo check_nginx = "test \"$(yum list installed #{nginx_dep.pkg} | "+ "grep -c #{nginx_dep.pkg})\" -ge 1" check_ruby = "test \"$(yum list installed #{ruby_dep.pkg} | "+ "grep -c #{ruby_dep.pkg})\" -ge 1" set_mock_response_for @app, 1, "apt-get --version" => [:err, ""] set_mock_response_for @app, 0, "yum --version" => [:out, "1.0"] set_mock_response_for @app, 1, {check_nginx => [:err, ""], check_ruby => [:err, ""]}, {:sudo => yum_sudo} @app.install_deps 'ruby', nginx_dep, :no_threads => true each_remote_shell do |ds| [nginx_dep, ruby_dep].each do |dep| check = dep.instance_variable_get "@check" install = dep.instance_variable_get "@install" assert_ssh_call check, ds, :sudo => yum_sudo assert_ssh_call install, ds, :sudo => yum_sudo end end end def test_install_gem_deps rake_dep = Sunshine.dependencies.get 'rake' bundler_dep = Sunshine.dependencies.get 'bundler' gem_sudo = Sunshine::Gem.sudo checks = { rake_dep => "gem list #{rake_dep.pkg} -i --version '>=0.8'", bundler_dep => "gem list #{bundler_dep.pkg} -i --version '>=0.9'" } checks.values.each do |check| set_mock_response_for @app, 1, {check => [:err, ""]}, {:sudo => gem_sudo} end @app.install_deps 'rake', bundler_dep, :no_threads => true each_remote_shell do |ds| [rake_dep, bundler_dep].each do |dep| check = dep.instance_variable_get "@check" install = dep.instance_variable_get "@install" assert_ssh_call check, ds, :sudo => gem_sudo assert_ssh_call install, ds, :sudo => gem_sudo end end end def test_find_all app = Sunshine::App.new :repo => {:type => "svn", :url => @svn_url}, :remote_shells => [ "user@some_server.com", ["server2.com", {:roles => "web db"}] ] server_apps = app.server_apps assert_equal server_apps, app.find assert_equal server_apps, app.find({}) assert_equal server_apps, app.find(:all) assert_equal server_apps, app.find(nil) end def test_find app = Sunshine::App.new :repo => {:type => "svn", :url => @svn_url}, :remote_shells => [ "user@some_server.com", ["server2.com", {:roles => "web db"}] ] server_apps = app.server_apps assert_equal server_apps, app.find(:role => :web) assert_equal server_apps, app.find(:role => :db) assert_equal [server_apps[0]], app.find(:role => :all) assert_equal [server_apps[0]], app.find(:role => :blarg) assert_equal [server_apps[0]], app.find(:user => 'user') assert_equal [server_apps[0]], app.find(:host => 'some_server.com') assert_equal [server_apps[1]], app.find(:host => 'server2.com') end def test_make_app_directories @app.make_app_directories each_remote_shell do |ds| assert_ssh_call "mkdir -p #{@app.server_apps.first.directories.join(" ")}" end end def test_rake @app.rake("test:task") each_remote_shell do |ds| assert_ssh_call "cd #{@app.checkout_path} && rake test:task" end end def test_register_as_deployed @app.register_as_deployed each_remote_shell do |ds| assert_ssh_call "test -d #{@app.root_path}" yml_list = {@app.name => @app.root_path}.to_yaml path = ds.expand_path(Sunshine::APP_LIST_PATH) assert ds.method_called?(:make_file, :args => [path, yml_list]) end end def test_remove_old_deploys returned_dirs = %w{old_deploy1 old_deploy2 old_deploy3 main_deploy} old_deploys = returned_dirs[0..-2].map{|d| "#{@app.deploys_path}/#{d}"} list_cmd = "ls -rc1 #{@app.deploys_path}" rm_cmd = "rm -rf #{old_deploys.join(" ")}" set_mock_response_for @app, 0, list_cmd => [:out, returned_dirs.join("\n")] Sunshine.setup 'max_deploy_versions' => 1 @app.remove_old_deploys each_remote_shell do |ds| assert_ssh_call list_cmd assert_ssh_call rm_cmd end end def test_run_post_user_lambdas lambdas_ran = 0 count = 5 count.times do @app.after_user_script do |app| lambdas_ran = lambdas_ran.next end end assert_equal 0, lambdas_ran @app.run_post_user_lambdas assert_equal count, lambdas_ran end def test_shell_env new_env = { "PATH" => "/etc/lib:$PATH", "RACK_ENV" => "test", "RAILS_ENV" => "test" } @app.shell_env new_env assert_equal new_env, @app.shell_env end def test_symlink_current_dir @app.symlink_current_dir each_remote_shell do |ds| assert_ssh_call "ln -sfT #{@app.checkout_path} #{@app.current_path}" end end def test_threaded_each_errors err_host = "some_server.com" finished = 0 @app.threaded_each do |server_app| if server_app.shell.host == err_host raise Sunshine::DeployError, server_app.shell.host else finished = finished.next end end raise "Didn't raise threaded error when it should have" rescue Sunshine::DeployError => e host = @app.server_apps.first.shell.host assert_equal host, e.message assert_equal (@app.server_apps.length - 1), finished end - def test_upload_tasks - path = "/path/to/tasks" - - @app.upload_tasks 'common', 'tpkg', - :host => 'some_server.com', - :remote_path => path - - shell = @app.find(:host => 'some_server.com').first.shell - - use_remote_shell shell - - assert_ssh_call "mkdir -p /path/to/tasks" - - %w{common tpkg}.each do |task| - from = "#{Sunshine::ROOT}/templates/tasks/#{task}.rake" - to = "#{shell.host}:#{path}/#{task}.rake" - - assert_rsync from, to - end - end - - - def test_upload_tasks_simple - @app.upload_tasks - - path = "#{@app.checkout_path}/lib/tasks" - - tasks = - Dir.glob("#{Sunshine::ROOT}/templates/tasks/*").map{|t| File.basename t} - - each_remote_shell do |ds| - assert_ssh_call "mkdir -p #{path}" - - tasks.each do |task| - from = "#{Sunshine::ROOT}/templates/tasks/#{task}" - to = "#{ds.host}:#{path}/#{task}" - - assert_rsync from, to - end - end - end - - def test_with_filter app = Sunshine::App.new :repo => {:type => "svn", :url => @svn_url}, :remote_shells => ["[email protected]", "[email protected]"] assert_equal 2, app.server_apps.length app.with_filter :host => 'server1.com' do |app| assert_equal 1, app.server_apps.length assert_equal 'server1.com', app.server_apps.first.shell.host end assert_equal 2, app.server_apps.length end def test_sudo_assignment @app.sudo = "someuser" @app.each do |server_app| assert_equal "someuser", server_app.shell.sudo end end private def assert_attributes_equal(attr_hash, app) assert_equal attr_hash[:name], app.name assert_equal attr_hash[:repo][:url], app.repo.url assert_equal attr_hash[:root_path], app.root_path attr_hash[:remote_shells].each_with_index do |server_def, i| shell = Sunshine::RemoteShell.new(*server_def) assert_equal shell, app.server_apps[i].shell end end end diff --git a/test/unit/test_server_app.rb b/test/unit/test_server_app.rb index 2ac3a13..70d1def 100644 --- a/test/unit/test_server_app.rb +++ b/test/unit/test_server_app.rb @@ -1,559 +1,492 @@ require 'test_helper' class TestServerApp < Test::Unit::TestCase def setup mock_svn_response @app = mock_app @app.repo.extend MockObject @sa = Sunshine::ServerApp.new @app, mock_remote_shell @sa.extend MockObject use_remote_shell @sa.shell end def test_from_info_file info_data = @sa.get_deploy_info.to_yaml @sa.shell.mock :call, :args => "cat info/path", :return => info_data server_app = Sunshine::ServerApp.from_info_file "info/path", @sa.shell assert_equal @sa.root_path, server_app.root_path assert_equal @sa.checkout_path, server_app.checkout_path assert_equal @sa.current_path, server_app.current_path assert_equal @sa.deploys_path, server_app.deploys_path assert_equal @sa.log_path, server_app.log_path assert_equal @sa.shared_path, server_app.shared_path assert_equal @sa.scripts_path, server_app.scripts_path assert_equal @sa.roles, server_app.roles assert_equal @sa.shell.env, server_app.shell_env assert_equal @sa.name, server_app.name assert_equal @sa.deploy_name, server_app.deploy_name end def test_init default_info = {:ports => {}} assert_equal default_info, @sa.info assert_equal @app, @sa.app assert_equal Hash.new, @sa.scripts assert_equal [:all], @sa.roles end def test_init_roles sa = Sunshine::ServerApp.new @app, "host", :roles => "role1 role2" assert_equal [:role1, :role2], sa.roles sa = Sunshine::ServerApp.new @app, "host", :roles => %w{role3 role4} assert_equal [:role3, :role4], sa.roles end def test_add_shell_paths @sa.add_shell_paths "test/path1", "test/path2" assert_equal "test/path1:test/path2:$PATH", @sa.shell_env['PATH'] @sa.add_shell_paths "test/path3", "test/path4" assert_equal "test/path3:test/path4:test/path1:test/path2:$PATH", @sa.shell_env['PATH'] end def test_app_attr sa_root_path = "local/server_app/path" sa_deploy_name = "local_deploy_name" @sa = Sunshine::ServerApp.new "test", "host", :root_path => sa_root_path, :deploy_name => sa_deploy_name assert_equal sa_root_path, @sa.root_path assert_equal sa_deploy_name, @sa.deploy_name assert_equal "test", @sa.name @sa.app = @app assert_not_equal sa_root_path, @sa.root_path assert_not_equal sa_deploy_name, @sa.deploy_name assert_not_equal "test", @sa.name assert_equal @app.root_path, @sa.root_path assert_equal @app.deploy_name, @sa.deploy_name assert_equal @app.name, @sa.name end def test_build_control_scripts @sa.scripts[:start] << "start" @sa.scripts[:stop] << "stop" @sa.scripts[:custom] << "custom" @sa.build_control_scripts [:start, :stop, :custom].each do |script| content = @sa.make_bash_script script, @sa.scripts[script] assert @sa.method_called?(:write_script, :args => [script, content]) end content = @sa.make_env_bash_script assert @sa.method_called?(:write_script, :args => ["env", content]) content = @sa.make_bash_script :restart, ["#{@sa.app.root_path}/stop", "#{@sa.app.root_path}/start"] assert @sa.method_called?(:write_script, :args => [:restart, content]) end def test_build_deploy_info_file @sa.shell.mock :file?, :return => false args = ["#{@app.scripts_path}/info", @sa.get_deploy_info.to_yaml] @sa.build_deploy_info_file assert @sa.shell.method_called?(:make_file, :args => args) args = ["#{@app.scripts_path}/info", "#{@app.root_path}/info"] assert @sa.shell.method_called?(:symlink, :args => args) end def test_checkout_repo @sa.checkout_repo @app.repo repo = @sa.app.repo args = [@app.checkout_path, @sa.shell] assert repo.method_called?(:checkout_to, :args => args) info = @app.repo.checkout_to @app.checkout_path, @sa.shell assert_equal info, @sa.info[:scm] end def test_deploy_details deploy_details = {:item => "thing"} other_details = {:key => "value"} @sa.shell.mock :call, :args => ["cat #{@sa.root_path}/info"], :return => other_details.to_yaml @sa.instance_variable_set "@deploy_details", deploy_details assert_equal deploy_details, @sa.deploy_details assert_equal other_details, @sa.deploy_details(true) end def test_not_deployed? @sa.mock :deploy_details, :args => [true], :return => nil assert_equal false, @sa.deployed? end def test_server_checked_deployed? @sa.mock :deploy_details, :args => [true], :return => {:deploy_name => @sa.deploy_name} assert_equal true, @sa.deployed? end def test_cached_details_deployed? @sa.instance_variable_set "@deploy_details", :deploy_name => @sa.deploy_name assert_equal true, @sa.deployed? end def test_get_deploy_info test_info = { :deployed_at => Time.now.to_s, :deployed_as => @sa.shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(@app.checkout_path), :name => @sa.name, :env => @sa.shell_env, :roles => @sa.roles, :path => @app.root_path, :sunshine_version => Sunshine::VERSION }.merge @sa.info deploy_info = @sa.get_deploy_info deploy_info.each do |key, val| next if key == :deployed_at assert_equal test_info[key], val end end def test_has_all_roles assert @sa.has_roles?([:web, :app, :blarg]) assert @sa.has_roles?([:web, :app, :blarg], true) end def test_has_roles @sa.roles = [:web, :app] assert @sa.has_roles?(:web) assert @sa.has_roles?([:web, :app]) assert [email protected]_roles?([:blarg, :web, :app]) assert @sa.has_roles?([:blarg, :web, :app], true) end def test_install_deps nginx_dep = Sunshine.dependencies.get 'nginx', :prefer => @sa.pkg_manager @sa.install_deps "ruby", nginx_dep assert_dep_install 'ruby', Sunshine::Yum assert_dep_install 'nginx', Sunshine::Yum end def test_install_deps_bad_type nginx_dep = Sunshine.dependencies.get 'nginx' @sa.install_deps nginx_dep, :type => Sunshine::Gem raise "Didn't raise missing dependency when it should have." rescue Sunshine::MissingDependency => e assert_equal "No dependency 'nginx' [Sunshine::Gem]", e.message end def test_make_app_directories @sa.make_app_directories assert_server_call "mkdir -p #{@sa.directories.join(" ")}" end def test_make_bash_script app_script = @sa.make_bash_script "blah", [1,2,3,4] assert_bash_script "blah", [1,2,3,4], app_script end def test_make_env_bash_script @sa.shell.env = {"BLAH" => "blarg", "HOME" => "/home/blah"} test_script = "#!/bin/bash\nenv BLAH=blarg HOME=/home/blah \"$@\"" assert_equal test_script, @sa.make_env_bash_script end def test_rake @sa.rake "db:migrate" assert_dep_install 'rake', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && rake db:migrate" end def test_register_as_deployed Sunshine::AddCommand.extend MockObject unless MockObject === Sunshine::AddCommand @sa.register_as_deployed args = [@app.root_path, {'servers' => [@sa.shell]}] assert Sunshine::AddCommand.method_called?(:exec, :args => args) end def test_remove_old_deploys Sunshine.setup 'max_deploy_versions' => 3 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_server_call "rm -rf #{removed.join(" ")}" end def test_remove_old_deploys_unnecessary Sunshine.setup 'max_deploy_versions' => 5 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.mock :call, :args => ["ls -1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_not_called "rm -rf #{removed.join(" ")}" end def test_revert! deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" last_deploy = "#{@app.deploys_path}/ploy5" assert_server_call "ln -sfT #{last_deploy} #{@app.current_path}" end def test_no_previous_revert! @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" end def test_run_bundler @sa.run_bundler assert_dep_install 'bundler', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && gem bundle" end def test_run_geminstaller @sa.run_geminstaller assert_dep_install 'geminstaller', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && geminstaller -e" end def test_running? set_mock_response_for @sa, 0, "#{@sa.root_path}/status" => [:out, "THE SYSTEM OK!"] assert_equal true, @sa.running? end def test_not_running? set_mock_response_for @sa, 13, "#{@sa.root_path}/status" => [:err, "THE SYSTEM IS DOWN!"] assert_equal false, @sa.running? end def test_errored_running? set_mock_response_for @sa, 1, "#{@sa.root_path}/status" => [:err, "KABLAM!"] assert_raises Sunshine::CmdError do @sa.running? end end def test_sass sass_files = %w{file1 file2 file3} @sa.sass(*sass_files) assert_dep_install 'haml', @sa.pkg_manager sass_files.each do |file| sass_file = "public/stylesheets/sass/#{file}.sass" css_file = "public/stylesheets/#{file}.css" assert_server_call \ "cd #{@app.checkout_path} && sass #{sass_file} #{css_file}" end end def test_shell_env assert_equal @sa.shell.env, @sa.shell_env end def test_symlink_current_dir @sa.symlink_current_dir assert_server_call "ln -sfT #{@app.checkout_path} #{@app.current_path}" end - def test_upload_tasks - files = %w{task1 task2} - - @sa.upload_tasks(*files) - - assert_server_call "mkdir -p #{@app.checkout_path}/lib/tasks" - - files.each do |f| - args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", - "#{@app.checkout_path}/lib/tasks/#{f}.rake"] - - assert @sa.shell.method_called?(:upload, :args => args) - end - end - - - def test_upload_tasks_with_remote_path - files = %w{task1 task2} - path = "/path/to/remote/tasks" - - @sa.upload_tasks files[0], files[1], :remote_path => path - - assert_server_call "mkdir -p #{path}" - - files.each do |f| - args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", - "#{path}/#{f}.rake"] - - assert @sa.shell.method_called?(:upload, :args => args) - end - end - - - def test_upload_tasks_with_local_path - files = %w{task1 task2} - path = "/path/to/local/tasks" - args = files.dup << {:local_path => path} - - @sa.upload_tasks(*args) - - assert_server_call "mkdir -p #{@sa.checkout_path}/lib/tasks" - - files.each do |f| - args = ["#{path}/#{f}.rake", - "#{@sa.checkout_path}/lib/tasks/#{f}.rake"] - - assert @sa.shell.method_called?(:upload, :args => args) - end - end - - - def test_upload_tasks_all - files = Dir.glob("templates/tasks/*").map{|f| File.basename(f, ".rake")} - - @sa.upload_tasks - - assert_server_call "mkdir -p #{@app.checkout_path}/lib/tasks" - - files.each do |f| - args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", - "#{@app.checkout_path}/lib/tasks/#{f}.rake"] - - assert @sa.shell.method_called?(:upload, :args => args) - end - end - - def test_upload_codebase @sa.shell.mock(:upload) @sa.upload_codebase "tmp/thing/", :test_scm => "info" assert_equal({:test_scm => "info"} , @sa.info[:scm]) assert @sa.shell.method_called?( :upload, :args => ["tmp/thing/", @sa.checkout_path, {:flags => ["--exclude .svn/","--exclude .git/"]}]) end def test_upload_codebase_with_exclude @sa.shell.mock(:upload) @sa.upload_codebase "tmp/thing/", :test_scm => "info", :exclude => "bad/path/" assert_equal({:test_scm => "info"} , @sa.info[:scm]) assert @sa.shell.method_called?( :upload, :args => ["tmp/thing/", @sa.checkout_path, {:flags => ["--exclude bad/path/", "--exclude .svn/", "--exclude .git/"]}]) end def test_upload_codebase_with_excludes @sa.shell.mock(:upload) @sa.upload_codebase "tmp/thing/", :test_scm => "info", :exclude => ["bad/path/", "other/exclude/"] assert_equal({:test_scm => "info"} , @sa.info[:scm]) assert @sa.shell.method_called?( :upload, :args => ["tmp/thing/", @sa.checkout_path, {:flags => ["--exclude bad/path/", "--exclude other/exclude/", "--exclude .svn/", "--exclude .git/"]}]) end def test_write_script @sa.shell.mock :file?, :return => false @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert @sa.shell.method_called?(:make_file, :args => args) end def test_symlink_scripts_to_root @sa.shell.mock :call, :args => ["ls -1 #{@sa.scripts_path}"], :return => "script_name\n" args = ["#{@app.scripts_path}/script_name", "#{@app.root_path}/script_name"] @sa.symlink_scripts_to_root assert @sa.shell.method_called?(:symlink, :args => args) end def test_write_script_existing @sa.shell.mock :file?, :return => true @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert [email protected]_called?(:make_file, :args => args) end end
jcasts/sunshine
d20fe8408cc92eee699b593504a7df4978dbbca9
bumping version for release
diff --git a/History.txt b/History.txt index 27d9396..9cffd96 100644 --- a/History.txt +++ b/History.txt @@ -1,369 +1,375 @@ +=== 1.2.2 / 2010-10-13 + +* Bugfixes: + + * Added support for ruby 1.9.2 + === 1.2.1 / 2010-10-05 * Improvements: * Added customizable behaviors for sigint and failures during deploys. * Added Sunshine irb shell to work directly with deploying apps. * Added ability to launch a pseudo terminal from a RemoteShell. * Added exit code to CmdError. * Added exclude paths for checkout by copy. * Bugfixes: * Fixed custom scripts. * Fixed deploy env defaults. * Removed Shell#update_timeout as it was unnecessary. * RemoteShell rsync recurses by default. * Fixed start and stop script permissions when calling sunshine commands. === 1.2.0 / 2010-09-08 * Improvements: * Added better support for custom env/start/stop/restart scripts. * Added scripts sunshine command to call custom scripts remotely. * Deploy env defaults to ENV 'DEPLOY_ENV', 'env', 'RACK_ENV', or 'RAILS_ENV'. * Bugfixes: * ServerApp#run_geminstaller no longer defaults to using sudo. * Added better extensible package manager checking to ServerApp. * Fixed Cronjob functionality and added array support. === 1.1.2 / 2010-04-15 * Improvements: * Added array support to App#find. * Added auto registration of Dependency subclasses for scalability. * Added call to App#start in App#deploy. * Bugfixes: * Fixed bug where env wouldn't be applied correctly in control scripts. * Changed App#with_filter to actually change the App#server_apps attribute. * Shell#env_cmd now returns a flattened array. * Added actual check of running process to Daemon#status_cmd. === 1.1.1 / 2010-04-05 * Improvements: * Added Repo subclass registration for greater expandability. * Added support for checking out codebases locally then rsync-ing them. * Bugfixes: * Fixed RemoteShell login script lingering after disconnect. === 1.1.0 / 2010-04-02 * Improvements: * Support for server clustering with the ServerCluster class. * Added Daemon#status method. * Added the -R option for loading external libraries and gems. * Added support for Thin and MongrelRails. * Added Server support for max connections configuration. * Bugfixes: * Daemons no longer create control scripts if they aren't used. * Fixed Rsync repo to auto append "/" to urls for correct rsyncing. === 1.0.3 / 2010-03-26 * Improvements: * Added App#call method. * Added App#with_session and Shell#with_session to reduce login prompts. * Bugfixes: * Geminstaller now always installs with sudo. * Fixed permissions issues with running servers on ports < 1024. * Fixed healthcheck middleware. === 1.0.2 / 2010-03-25 * Bugfixes: * Fixed apache passenger dependency to run as sudo. * Fixed a bug in Repo::detect === 1.0.1 / 2010-03-25 * Bugfixes: * Added json dependency === 1.0.0 / 2010-03-25 * Improvements: * Added auto_dependencies config to turn on/off auto installing things. * Added healthcheck middleware support. * Added support for Apache2 and its passenger implementation. * Removed all Atti-specific code for public release. * Bugfixes: * Fixed Nginx passenger implementation. === 0.0.6 / 2010-03-19 * Major: * Removed DeployServerDispatcher. Dispatching now happens at the App level. * Moved Settler into Sunshine and renamed it to DependencyLib. * Improvements: * Added INT signal handling to exit deploys and close connections gracefully. * Added dependency installation methods apt_install, gem_install, tpkg_install and yum_install to App and ServerApp. * Extended functionality of ServerApp#upload_tasks. * ServerApp now support being instatiated with an App instance (for coordinated deploys) or just with an app name (for post-deploy usage). * Added a Sunshine rakefile template for task-based deploys. Available through: sunshine --rakefile [COPY_TO] * App#name gets auto-assigned by repo info if not provided. * Sunshine::web_directory used to determine App#deploy_path when missing. * Repo#detect now returns a Repo object instead of an array. * Added start/stop/restart/status methods to DeployServerApp. * ServerApp instances with unspecified roles get all roles by default. * App config files now use erb parsing. Any key/value passed the App constructor as a hash should be passed to the erb binding along with the deploy_env. * Added support to bundler for defining multiple dependencies with the same name, and different package managers. * Bugfixes: * Added setup checking to Daemon to only run setup when needed. * Moved healthcheck from App to ServerApp and improved the api. * Renamed DeployServerApp to ServerApp. * Renamed App#deploy_path and App#deploys_dir to App#root_path and App#deploys_path. * Renamed the 'deploy' command to 'run' to more accurately express it's use. * RsyncRepo#do_checkout fixed to match standard Repo#do_checkout methods. * Sunshine::DATA and Sunshine::PATH are now set when running standalone ruby deploy files. === 0.0.5 / 2010-02-26 * Sunshine::App: * Use of DeployServerDispatcher threading * Fixed control script creation to be deploy_server specific (takes roles into account) * Added AttiApp class for ATTi app deployment. * Constuctor supports :deploy_name option for nameable deploys. Defaults to the timestamp. * Auto-detects if the script's directory is a checked out repo and uses it if no repo information was given. * Support for running sass. * Sunshine::DeployServerDispatcher: * Added threading support * Sunshine::Repo: * Added support for detecting a repo type based on a path: Repo.detect [path [, console_or_deploy_server]] #=> [:git, "git://url/of/git/repo", {:tree => "master", ...}] * Moved info instance methods to the class * Support for git-svn: SvnRepo.git_svn? path * Changed the checkout_to method signature * Sunshine::Server: * Added support for ar_sendmail server. === 0.0.4 / 2010-02-12 * Added sudo functionality: * Support for :sudo option on Sunshine::App, Sunshine::Server, and Sunshine::DeployServer constructors, and attr_accessor :sudo * Settler Dependency classes support a default sudo value: Sunshine::Dependencies::Gem.sudo = true # use sudo Sunshine::Dependencies::Gem.sudo = "usr" # use sudo -u usr Sunshine::Dependencies::Gem.sudo = false # ensure sudo is off Sunshine::Dependencies::Gem.sudo = nil # use :call obj precedence * App supports passing a (yml) file object to the constructor. Useful for passing file DATA if desired: app = Sunshine::App.new Sunshine::DATA app.deploy!{|app| Sunshine::Rainbows.new(app).restart } __END__ #yaml for app goes here... * App class changes: * Changed the format of the App#checkout_path directory * Logrotate setup now has to be called explicitely * Commands functionality expanded: * Support for --sudo and --sudo=user on all Sunshine commands * Added --format option for control commands. Supports txt, yml, json. * Control scripts generated on the remote server now keep deploy-time shell_env variables: * Run commands with the --no-env option to run without deploy shell_env variables. * Run any script with the app's env variables using: /path/to/app/env some_command /path/to/app/env EXTRA_VAR=some_value some_command Supports all options the env command supports. * Dependency handling now supports apt. * DeployServers now support passing custom flags for ssh and rsync: deploy_server = DeployServer.new "svr.com", :rsync_flags => [...] deploy_server.call "some_command", :sudo => "user", :flags => '-C' deploy_server.upload "from", "to", :sudo => "user", :flags => ['--chmod=ugo=rwX', '-b'] deploy_server.download "from", "to", :flags => '--ignore-existing' * Repo implementation has significantly changed: * Added support for git repo. * Info about a repo is now retrieved with Repo#get_repo_info: repo.get_repo_info deploy_server, checkout_path * Repo constructor supports options hash with :flags option. === 0.0.3 / 2010-01-29 * Many small bugfixes * Tests, tests, and more tests * Changed DeployServer api * DeployServer#run is not longer supported, use DeployServer#call * Constructor supports a spaced delimited list for roles: DeployServer.new "myhost.com", :roles => "web db other" * Changed how deploy server yaml is parsed. Should parse to be valid on: DeployServer.new *parsed_yaml Example Given: :deploy_servers : - server1.com - - server2.com - - server3.com - :roles : web db other :ssh_flags : '-o ControlMaster=auto' === 0.0.2 / 2010-01-15 * Added Control Commands * add, deploy, list, restart, rm, start, stop * Application support * Changed VERSION file to info and its format to yaml * Deployed apps now have a start, stop and restart script * Added Crontab and log rotation support * Functional changes * Ditched net/ssh and net/scp for ssh and rsync through Open4 * Fixed and updated dependencies to use Yum * Support for sunshine user configuration in ~/.sunshine * Rake tasks * Support to run the app's rake tasks * Built in default ATTi rake tasks === 0.0.1 / 2009-11-18 * 1 major enhancement * First release! diff --git a/lib/sunshine.rb b/lib/sunshine.rb index 84ce799..64ec819 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,441 +1,441 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'yaml' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' require 'irb' # Turn off EOF tracking to be able to prompt on deploy exceptions. HighLine.track_eof = false ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. - VERSION = '1.2.1' + VERSION = '1.2.2' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { 'interactive' => true, 'auto_dependencies' => true, 'deploy_env' => :development, 'exception_behavior' => :revert, 'exclude_paths' => [], 'level' => 'info', 'max_deploy_versions' => 5, 'remote_checkouts' => false, 'timeout' => 300, 'sigint_behavior' => :revert, 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end ## # Defines what to do when deploy raises an exception. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.exception_behavior @config['exception_behavior'] end ## # Array of paths or globs that should be excluded from the checkout. # Does not work with remote_checkouts enabled. def self.exclude_paths @config['exclude_paths'] end ## # Should sunshine ever ask for user input? True by default. # Overridden in the config or with the -a option. def self.interactive? @config['interactive'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end ## # Defines what to do when sigint is sent during deploys. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.sigint_behavior @config['sigint_behavior'] end ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config unless File.file? USER_CONFIG_FILE File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" msg << DEFAULT_CONFIG.to_yaml self.exit 1, msg end load_config_file USER_CONFIG_FILE @config['deploy_env'] = ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] || @config['deploy_env'] @config end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset TrapStack.trap_signal :INT do |msg| $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" logger.info :INT, msg end TrapStack.add_trap "Disconnecting all remote shells." do RemoteShell.disconnect_all end require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' require 'sunshine/trap_stack' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' require 'sunshine/healthcheck' require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies'
jcasts/sunshine
e189671482687251c346a9c1994cb18f5555f081
fixed YAML deprecation warnings in tests
diff --git a/test/test_helper.rb b/test/test_helper.rb index f760109..29eb480 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,28 +1,26 @@ require 'sunshine' require 'test/unit' require 'helper_methods' include HelperMethods require 'test/mocks/mock_object' require 'test/mocks/mock_open4' unless defined? TEST_APP_CONFIG_FILE TEST_APP_CONFIG_FILE = "test/fixtures/app_configs/test_app.yml" end Sunshine.setup({'remote_checkouts' => true}, true) unless MockObject === Sunshine.shell Sunshine.shell.extend MockObject Sunshine.shell.mock :<<, :return => nil Sunshine.shell.mock :write, :return => nil end -YAML.extend MockObject unless MockObject === YAML - unless Sunshine::Dependency.include? MockObject Sunshine::Dependency.send(:include, MockObject) end diff --git a/test/unit/test_sunshine.rb b/test/unit/test_sunshine.rb index 19b56c5..2ea6e4b 100644 --- a/test/unit/test_sunshine.rb +++ b/test/unit/test_sunshine.rb @@ -1,169 +1,172 @@ require 'test/test_helper' class TestSunshine < Test::Unit::TestCase def setup mock_yaml_load_file end def test_default_config config = Sunshine::DEFAULT_CONFIG Sunshine.setup config assert Sunshine::Shell === Sunshine.shell assert_equal config['deploy_env'].to_s, Sunshine.deploy_env assert_equal !config['auto'], Sunshine.interactive? assert Sunshine::Output === Sunshine.logger assert_equal Logger::INFO, Sunshine.logger.level assert_equal config['max_deploy_versions'], Sunshine.max_deploy_versions assert_equal config['trace'], Sunshine.trace? end def test_find_command assert !Sunshine.find_command('st') assert_equal Sunshine::StartCommand, Sunshine.find_command('sta') assert_equal Sunshine::StopCommand, Sunshine.find_command('sto') assert_equal Sunshine::AddCommand, Sunshine.find_command('a') Sunshine::COMMANDS.each do |cmd| const = Sunshine.const_get "#{cmd.capitalize}Command" assert_equal const, Sunshine.find_command(cmd) end end def test_exec_run_command mock_sunshine_exit mock_sunshine_command Sunshine::RunCommand Sunshine.run %w{run somefile.rb -l debug -e prod --no-trace} assert_command Sunshine::RunCommand, [['somefile.rb'], Sunshine.config] end def test_exec_control_commands mock_sunshine_exit %w{add list restart rm start stop}.each do |name| cmd = Sunshine.const_get("#{name.capitalize}Command") mock_sunshine_command cmd argv = [name, 'thing1', 'thing2', '-r', 'remoteserver.com'] Sunshine.run argv servers = [Sunshine::RemoteShell.new("remoteserver.com")] args = [%w{thing1 thing2}, Sunshine.config] assert_command cmd, args assert_equal servers, Sunshine.config['servers'] argv = [name, 'thing1', 'thing2', '-v'] Sunshine.run argv servers = [Sunshine.shell] args = [%w{thing1 thing2}, Sunshine.config] assert_command cmd, args assert_equal servers, Sunshine.config['servers'] assert Sunshine.config['verbose'] end end def test_exec_local_cmd mock_sunshine_exit mock_sunshine_command Sunshine::RmCommand Sunshine.run %w{rm app1 app2} dsd = [Sunshine.shell] args = [['app1', 'app2'], Sunshine.setup] assert_command Sunshine::RmCommand, args assert_equal dsd, Sunshine.setup['servers'] end def test_exit assert_sunshine_exit_status [true], 0 assert_sunshine_exit_status [false], 1 assert_sunshine_exit_status [0, "success!"], 0, "success!" assert_sunshine_exit_status [2, "failed!"], 2, "failed!" end def assert_sunshine_exit_status args, expected_status, msg="" args.map!{|a| a.inspect.gsub("\"", "\\\"")} args = args.join(",") cmd = "ruby -Ilib -e \"require 'sunshine'; Sunshine.exit(#{args})\"" pid, inn, out, err = Open4.popen4(*cmd) status = Process.waitpid2(pid).last out_data = out.read err_data = err.read out.close err.close inn.close assert_equal expected_status, status.exitstatus if expected_status == 0 assert_equal msg, out_data.strip else assert_equal msg, err_data.strip end end def assert_command cmd, args assert cmd.call_log.include?([:exec, args]) end def mock_sunshine_command cmd cmd.instance_eval do undef exec undef call_log if defined?(call_log) def call_log @call_log ||= [] end def exec *args call_log << [:exec, args] true end end end def mock_sunshine_exit Sunshine.instance_eval do undef exit def exit *args end end end def mock_yaml_load_file - YAML.mock :load_file, :args => [Sunshine::USER_CONFIG_FILE], - :return => Sunshine::DEFAULT_CONFIG + YAML.instance_eval do + undef load_file + def load_file file + Sunshine::DEFAULT_CONFIG + end + end end - end
jcasts/sunshine
0af939eec24e0e7fc2c6c2c173b377eff6839c53
made sudo prompt configurable on shell class to allow other languages
diff --git a/lib/sunshine/shell.rb b/lib/sunshine/shell.rb index 22157c6..e9cdd58 100644 --- a/lib/sunshine/shell.rb +++ b/lib/sunshine/shell.rb @@ -1,432 +1,444 @@ module Sunshine ## # The Shell class handles local input, output and execution to the shell. class Shell include Open4 LOCAL_USER = `whoami`.chomp LOCAL_HOST = `hostname`.chomp - SUDO_FAILED = /^Sorry, try again./ - SUDO_PROMPT = /^Password:/ + class << self + # The message to match in stderr to determine logging in has failed. + # Defaults to: + # /^Sorry, try again./ + attr_accessor :sudo_failed_matcher + + # The message to match in stderr to determine a password is required. + # Defaults to: + # /^Password:/ + attr_accessor :sudo_prompt_matcher + end + + self.sudo_failed_matcher = /^Sorry, try again./ + self.sudo_prompt_matcher = /^Password:/ attr_reader :user, :host, :password, :input, :output, :mutex attr_accessor :env, :sudo, :timeout def initialize output = $stdout, options={} @output = output $stdin.sync @input = HighLine.new $stdin @user = LOCAL_USER @host = LOCAL_HOST @sudo = options[:sudo] @env = options[:env] || {} @password = options[:password] @timeout = options[:timeout] || Sunshine.timeout @mutex = nil end ## # Checks for equality def == shell @host == shell.host && @user == shell.user rescue false end ## # Prompt the user for input. def ask(*args, &block) sync{ @input.ask(*args, &block) } end ## # Prompt the user to agree. def agree(*args, &block) sync{ @input.agree(*args, &block) } end ## # Execute a command on the local system and return the output. def call cmd, options={}, &block Sunshine.logger.info @host, "Running: #{cmd}" do execute sudo_cmd(cmd, options), &block end end ## # Prompt the user to make a choice. def choose &block sync{ @input.choose(&block) } end ## # Close the output IO. (Required by the Logger class) def close @output.close end ## # Returns true. Compatibility method with RemoteShell. def connect true end ## # Returns true. Compatibility method with RemoteShell. def connected? true end ## # Returns true. Compatibility method with RemoteShell. def disconnect true end ## # Copies a file. Compatibility method with RemoteShell. def download from_path, to_path, options={}, &block Sunshine.logger.info @host, "Copying #{from_path} -> #{to_path}" do FileUtils.cp_r from_path, to_path end end alias upload download ## # Expands the path. Compatibility method with RemoteShell. def expand_path path File.expand_path path end ## # Checks if file exists. Compatibility method with RemoteShell. def file? filepath File.file? filepath end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " pid = fork do exec sudo_cmd(env_cmd(cmd)).to_a.join(" ") end Process.waitpid pid end end ## # Write a file. Compatibility method with RemoteShell. def make_file filepath, content, options={} File.open(filepath, "w+"){|f| f.write(content)} end ## # Get the name of the OS def os_name @os_name ||= call("uname -s").strip.downcase end ## # Prompt the user for a password def prompt_for_password host_info = [@user, @host].compact.join("@") @password = ask("#{host_info} Password:") do |q| q.echo = false end end ## # Build an env command if an env_hash is passed def env_cmd cmd, env_hash=@env if env_hash && !env_hash.empty? env_vars = env_hash.map{|e| e.join("=")} cmd = ["env", env_vars, cmd].flatten end cmd end ## # Wrap command in quotes and escape as needed. def quote_cmd cmd cmd = [*cmd].join(" ") "'#{cmd.gsub(/'/){|s| "'\\''"}}'" end ## # Build an sh -c command def sh_cmd cmd ["sh", "-c", quote_cmd(cmd)] end ## # Build a command with sudo. # If sudo_val is nil, it is considered to mean "pass-through" # and the default shell sudo will be used. # If sudo_val is false, the cmd will be returned unchanged. # If sudo_val is true, the returned command will be prefaced # with sudo -H # If sudo_val is a String, the command will be prefaced # with sudo -H -u string_value def sudo_cmd cmd, sudo_val=nil sudo_val = sudo_val[:sudo] if Hash === sudo_val sudo_val = @sudo if sudo_val.nil? case sudo_val when true ["sudo", "-H", cmd].flatten when String ["sudo", "-H", "-u", sudo_val, cmd].flatten else cmd end end ## # Force symlinking a directory. def symlink target, symlink_name call "ln -sfT #{target} #{symlink_name}" rescue false end ## # Synchronize a block with the current mutex if it exists. def sync if @mutex @mutex.synchronize{ yield } else yield end end ## # Returns true if command was run successfully, otherwise returns false. def system cmd, options=nil call(cmd, options) && true rescue false end ## # Checks if timeout occurred. def timed_out? start_time, max_time=@timeout return unless max_time Time.now.to_i - start_time.to_i > max_time end ## # Execute a block while setting the shell's mutex. # Sets the mutex to its original value on exit. # Executing commands with a mutex is used for user prompts. def with_mutex mutex old_mutex, @mutex = @mutex, mutex yield @mutex = old_mutex end ## # Runs the passed block within a connection session. # If the shell is already connected, connecting and disconnecting # is ignored; otherwise, the session method will ensure that # the shell's connection gets closed after the block has been # executed. def with_session prev_connection = connected? connect unless prev_connection yield disconnect unless prev_connection end ## # Write string to stdout (by default). def write str @output.write str end alias << write ## # Execute a command with open4 and loop until the process exits. # The cmd argument may be a string or an array. If a block is passed, # it will be called when data is received and passed the stream type # and stream string value: # shell.execute "test -s 'blah' && echo 'true'" do |stream, str| # stream #=> :stdout # string #=> 'true' # end # # The method returns the output from the stdout stream by default, and # raises a CmdError if the exit status of the command is not zero. def execute cmd cmd = [cmd] unless Array === cmd pid, inn, out, err = popen4(*cmd) inn.sync = true log_methods = {out => :debug, err => :error} result, status = process_streams(pid, out, err) do |stream, data| stream_name = :out if stream == out stream_name = :err if stream == err stream_name = :inn if stream == inn # User blocks should run with sync threads to avoid badness. sync do Sunshine.logger.send log_methods[stream], "#{@host}:#{stream_name}", data yield(stream_name, data, inn) if block_given? end if password_required?(stream_name, data) then kill_process(pid) unless Sunshine.interactive? send_password_to_stream(inn, data) end end raise_command_failed(status, cmd) unless status.success? result[out].join.chomp ensure inn.close rescue nil out.close rescue nil err.close rescue nil end private def raise_command_failed(status, cmd) err = CmdError.new status.exitstatus, [*cmd].join(" ") raise err end def password_required? stream_name, data - stream_name == :err && data =~ SUDO_PROMPT + stream_name == :err && data =~ Shell.sudo_prompt_matcher end def send_password_to_stream inn, data - prompt_for_password if data =~ SUDO_FAILED + prompt_for_password if data =~ Shell.sudo_failed_matcher inn.puts @password || prompt_for_password end def kill_process pid, kill_type="KILL" begin Process.kill kill_type, pid Process.wait rescue end end def process_streams pid, *streams result = Hash.new{|h,k| h[k] = []} start_time = Time.now # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 raise TimeoutError if timed_out? start_time next if selected.nil? or selected.empty? selected.each do |stream| start_time = Time.now if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) yield(stream, data) result[stream] << data end end return result, status end end end
jcasts/sunshine
f7ed790f27333180eeef992713a93ca7309d51c0
renamed Shell#syscall to Shell#system ot better reflect its function
diff --git a/History.txt b/History.txt index 60c6c53..27d9396 100644 --- a/History.txt +++ b/History.txt @@ -1,367 +1,369 @@ === 1.2.1 / 2010-10-05 * Improvements: * Added customizable behaviors for sigint and failures during deploys. * Added Sunshine irb shell to work directly with deploying apps. * Added ability to launch a pseudo terminal from a RemoteShell. * Added exit code to CmdError. * Added exclude paths for checkout by copy. * Bugfixes: * Fixed custom scripts. * Fixed deploy env defaults. * Removed Shell#update_timeout as it was unnecessary. * RemoteShell rsync recurses by default. + * Fixed start and stop script permissions when calling sunshine commands. + === 1.2.0 / 2010-09-08 * Improvements: * Added better support for custom env/start/stop/restart scripts. * Added scripts sunshine command to call custom scripts remotely. * Deploy env defaults to ENV 'DEPLOY_ENV', 'env', 'RACK_ENV', or 'RAILS_ENV'. * Bugfixes: * ServerApp#run_geminstaller no longer defaults to using sudo. * Added better extensible package manager checking to ServerApp. * Fixed Cronjob functionality and added array support. === 1.1.2 / 2010-04-15 * Improvements: * Added array support to App#find. * Added auto registration of Dependency subclasses for scalability. * Added call to App#start in App#deploy. * Bugfixes: * Fixed bug where env wouldn't be applied correctly in control scripts. * Changed App#with_filter to actually change the App#server_apps attribute. * Shell#env_cmd now returns a flattened array. * Added actual check of running process to Daemon#status_cmd. === 1.1.1 / 2010-04-05 * Improvements: * Added Repo subclass registration for greater expandability. * Added support for checking out codebases locally then rsync-ing them. * Bugfixes: * Fixed RemoteShell login script lingering after disconnect. === 1.1.0 / 2010-04-02 * Improvements: * Support for server clustering with the ServerCluster class. * Added Daemon#status method. * Added the -R option for loading external libraries and gems. * Added support for Thin and MongrelRails. * Added Server support for max connections configuration. * Bugfixes: * Daemons no longer create control scripts if they aren't used. * Fixed Rsync repo to auto append "/" to urls for correct rsyncing. === 1.0.3 / 2010-03-26 * Improvements: * Added App#call method. * Added App#with_session and Shell#with_session to reduce login prompts. * Bugfixes: * Geminstaller now always installs with sudo. * Fixed permissions issues with running servers on ports < 1024. * Fixed healthcheck middleware. === 1.0.2 / 2010-03-25 * Bugfixes: * Fixed apache passenger dependency to run as sudo. * Fixed a bug in Repo::detect === 1.0.1 / 2010-03-25 * Bugfixes: * Added json dependency === 1.0.0 / 2010-03-25 * Improvements: * Added auto_dependencies config to turn on/off auto installing things. * Added healthcheck middleware support. * Added support for Apache2 and its passenger implementation. * Removed all Atti-specific code for public release. * Bugfixes: * Fixed Nginx passenger implementation. === 0.0.6 / 2010-03-19 * Major: * Removed DeployServerDispatcher. Dispatching now happens at the App level. * Moved Settler into Sunshine and renamed it to DependencyLib. * Improvements: * Added INT signal handling to exit deploys and close connections gracefully. * Added dependency installation methods apt_install, gem_install, tpkg_install and yum_install to App and ServerApp. * Extended functionality of ServerApp#upload_tasks. * ServerApp now support being instatiated with an App instance (for coordinated deploys) or just with an app name (for post-deploy usage). * Added a Sunshine rakefile template for task-based deploys. Available through: sunshine --rakefile [COPY_TO] * App#name gets auto-assigned by repo info if not provided. * Sunshine::web_directory used to determine App#deploy_path when missing. * Repo#detect now returns a Repo object instead of an array. * Added start/stop/restart/status methods to DeployServerApp. * ServerApp instances with unspecified roles get all roles by default. * App config files now use erb parsing. Any key/value passed the App constructor as a hash should be passed to the erb binding along with the deploy_env. * Added support to bundler for defining multiple dependencies with the same name, and different package managers. * Bugfixes: * Added setup checking to Daemon to only run setup when needed. * Moved healthcheck from App to ServerApp and improved the api. * Renamed DeployServerApp to ServerApp. * Renamed App#deploy_path and App#deploys_dir to App#root_path and App#deploys_path. * Renamed the 'deploy' command to 'run' to more accurately express it's use. * RsyncRepo#do_checkout fixed to match standard Repo#do_checkout methods. * Sunshine::DATA and Sunshine::PATH are now set when running standalone ruby deploy files. === 0.0.5 / 2010-02-26 * Sunshine::App: * Use of DeployServerDispatcher threading * Fixed control script creation to be deploy_server specific (takes roles into account) * Added AttiApp class for ATTi app deployment. * Constuctor supports :deploy_name option for nameable deploys. Defaults to the timestamp. * Auto-detects if the script's directory is a checked out repo and uses it if no repo information was given. * Support for running sass. * Sunshine::DeployServerDispatcher: * Added threading support * Sunshine::Repo: * Added support for detecting a repo type based on a path: Repo.detect [path [, console_or_deploy_server]] #=> [:git, "git://url/of/git/repo", {:tree => "master", ...}] * Moved info instance methods to the class * Support for git-svn: SvnRepo.git_svn? path * Changed the checkout_to method signature * Sunshine::Server: * Added support for ar_sendmail server. === 0.0.4 / 2010-02-12 * Added sudo functionality: * Support for :sudo option on Sunshine::App, Sunshine::Server, and Sunshine::DeployServer constructors, and attr_accessor :sudo * Settler Dependency classes support a default sudo value: Sunshine::Dependencies::Gem.sudo = true # use sudo Sunshine::Dependencies::Gem.sudo = "usr" # use sudo -u usr Sunshine::Dependencies::Gem.sudo = false # ensure sudo is off Sunshine::Dependencies::Gem.sudo = nil # use :call obj precedence * App supports passing a (yml) file object to the constructor. Useful for passing file DATA if desired: app = Sunshine::App.new Sunshine::DATA app.deploy!{|app| Sunshine::Rainbows.new(app).restart } __END__ #yaml for app goes here... * App class changes: * Changed the format of the App#checkout_path directory * Logrotate setup now has to be called explicitely * Commands functionality expanded: * Support for --sudo and --sudo=user on all Sunshine commands * Added --format option for control commands. Supports txt, yml, json. * Control scripts generated on the remote server now keep deploy-time shell_env variables: * Run commands with the --no-env option to run without deploy shell_env variables. * Run any script with the app's env variables using: /path/to/app/env some_command /path/to/app/env EXTRA_VAR=some_value some_command Supports all options the env command supports. * Dependency handling now supports apt. * DeployServers now support passing custom flags for ssh and rsync: deploy_server = DeployServer.new "svr.com", :rsync_flags => [...] deploy_server.call "some_command", :sudo => "user", :flags => '-C' deploy_server.upload "from", "to", :sudo => "user", :flags => ['--chmod=ugo=rwX', '-b'] deploy_server.download "from", "to", :flags => '--ignore-existing' * Repo implementation has significantly changed: * Added support for git repo. * Info about a repo is now retrieved with Repo#get_repo_info: repo.get_repo_info deploy_server, checkout_path * Repo constructor supports options hash with :flags option. === 0.0.3 / 2010-01-29 * Many small bugfixes * Tests, tests, and more tests * Changed DeployServer api * DeployServer#run is not longer supported, use DeployServer#call * Constructor supports a spaced delimited list for roles: DeployServer.new "myhost.com", :roles => "web db other" * Changed how deploy server yaml is parsed. Should parse to be valid on: DeployServer.new *parsed_yaml Example Given: :deploy_servers : - server1.com - - server2.com - - server3.com - :roles : web db other :ssh_flags : '-o ControlMaster=auto' === 0.0.2 / 2010-01-15 * Added Control Commands * add, deploy, list, restart, rm, start, stop * Application support * Changed VERSION file to info and its format to yaml * Deployed apps now have a start, stop and restart script * Added Crontab and log rotation support * Functional changes * Ditched net/ssh and net/scp for ssh and rsync through Open4 * Fixed and updated dependencies to use Yum * Support for sunshine user configuration in ~/.sunshine * Rake tasks * Support to run the app's rake tasks * Built in default ATTi rake tasks === 0.0.1 / 2009-11-18 * 1 major enhancement * First release! diff --git a/lib/sunshine/package_managers/apt.rb b/lib/sunshine/package_managers/apt.rb index 304c6b0..417ad3c 100644 --- a/lib/sunshine/package_managers/apt.rb +++ b/lib/sunshine/package_managers/apt.rb @@ -1,58 +1,58 @@ module Sunshine ## # The Apt dependency class supports basic apt-get features: # # dependency_lib.instance_eval do # apt "ruby", :version => '1.9' # end # # See the Dependency class for more info. class Apt < Dependency self.sudo = true def initialize(name, options={}, &block) super(name, options) do pkg_name = build_pkg_name @pkg.dup, options install "apt-get install -y #{pkg_name}" uninstall "apt-get remove -y #{pkg_name}" @pkg = "#{@pkg}-#{options[:version]}" if options[:version] check_test "apt-cache search ^#{@pkg} | grep -c ^#{@pkg}", '-ge 1' instance_eval(&block) if block_given? end end ## # Checks if dependency type is valid for a given shell. def self.system_manager? shell=nil - (shell || Sunshine.shell).syscall "apt-get --version" + (shell || Sunshine.shell).system "apt-get --version" end private def build_pkg_name pkg_name, options={} pkg_name << "=#{options[:version]}" if options[:version] pkg_name end def run_command(command, options={}) if @dependency_lib if @dependency_lib.exist?('apt') @dependency_lib.install 'apt', options end end super end end end diff --git a/lib/sunshine/package_managers/yum.rb b/lib/sunshine/package_managers/yum.rb index c7f4254..58fdfd0 100644 --- a/lib/sunshine/package_managers/yum.rb +++ b/lib/sunshine/package_managers/yum.rb @@ -1,70 +1,70 @@ module Sunshine ## # The Yum dependency class supports most of yum's installation features: # # dependency_lib.instance_eval do # yum "ruby", :version => '1.9', # :rel => 'release-num', # :arch => 'i386', # :epoch => 'some-epoch' # end # # See the Dependency class for more info. class Yum < Dependency self.sudo = true def initialize(name, options={}, &block) super(name, options) do pkg_name = build_pkg_name @pkg.dup, options install "yum install -y #{pkg_name}" uninstall "yum remove -y #{pkg_name}" check_test "yum list installed #{pkg_name} | grep -c #{@pkg}", '-ge 1' instance_eval(&block) if block_given? end end ## # Checks if dependency type is valid for a given shell. def self.system_manager? shell=nil - (shell || Sunshine.shell).syscall "yum --version" + (shell || Sunshine.shell).system "yum --version" end private def build_pkg_name pkg_name, options={} if options[:version] pkg_name << "-#{options[:version]}" if options[:rel] pkg_name << "-#{options[:rel]}" pkg_name = "#{options[:epoch]}:#{pkg_name}" if options[:arch] && options[:epoch] end end pkg_name << ".#{options[:arch]}" if options[:arch] pkg_name end def run_command(command, options={}) if @dependency_lib if @dependency_lib.exist?('yum') @dependency_lib.install 'yum', options end end super end end end diff --git a/lib/sunshine/remote_shell.rb b/lib/sunshine/remote_shell.rb index cc8536d..b5415a8 100644 --- a/lib/sunshine/remote_shell.rb +++ b/lib/sunshine/remote_shell.rb @@ -1,272 +1,272 @@ module Sunshine ## # Keeps an SSH connection open to a server the app will be deployed to. # Deploy servers use the ssh command and support any ssh feature. # By default, deploy servers use the ControlMaster feature to share # socket connections, with the ControlPath = ~/.ssh/sunshine-%r%h:%p # # Setting session-persistant environment variables is supported by # accessing the @env attribute. class RemoteShell < Shell ## # The loop to keep the ssh connection open. LOGIN_LOOP = "echo ok; echo ready; "+ "for (( ; ; )); do kill -0 $PPID && sleep 10 || exit; done;" LOGIN_TIMEOUT = 30 ## # Closes all remote shell connections. def self.disconnect_all return unless defined?(@remote_shells) @remote_shells.each{|rs| rs.disconnect} end ## # Registers a remote shell for global access from the class. # Handled automatically on initialization. def self.register remote_shell (@remote_shells ||= []) << remote_shell end attr_reader :host, :user, :pid attr_accessor :ssh_flags, :rsync_flags ## # Remote shells essentially need a host and optional user. # Typical instantiation is done through either of these methods: # RemoteShell.new "user@host" # RemoteShell.new "host", :user => "user" # # The constructor also supports the following options: # :env:: hash - hash of environment variables to set for the ssh session # :password:: string - password for ssh login; if missing the deploy server # will attempt to prompt the user for a password. def initialize host, options={} super $stdout, options @host, @user = host.split("@").reverse @user ||= options[:user] @rsync_flags = ["-azrP"] @rsync_flags.concat [*options[:rsync_flags]] if options[:rsync_flags] @ssh_flags = [ "-o ControlMaster=auto", "-o ControlPath=~/.ssh/sunshine-%r@%h:%p" ] @ssh_flags.concat ["-l", @user] if @user @ssh_flags.concat [*options[:ssh_flags]] if options[:ssh_flags] @pid, @inn, @out, @err = nil self.class.register self end ## # Runs a command via SSH. Optional block is passed the # stream(stderr, stdout) and string data. def call command_str, options={}, &block Sunshine.logger.info @host, "Running: #{command_str}" do execute build_remote_cmd(command_str, options), &block end end ## # Connect to host via SSH and return process pid def connect return true if connected? cmd = ssh_cmd quote_cmd(LOGIN_LOOP), :sudo => false @pid, @inn, @out, @err = popen4 cmd.join(" ") @inn.sync = true data = "" ready = nil start_time = Time.now.to_i until ready || @out.eof? data << @out.readpartial(1024) ready = data =~ /ready/ raise TimeoutError if timed_out?(start_time, LOGIN_TIMEOUT) end unless connected? disconnect host_info = [@user, @host].compact.join("@") raise ConnectionError, "Can't connect to #{host_info}" end @inn.close @pid end ## # Check if SSH session is open and returns process pid def connected? Process.kill(0, @pid) && @pid rescue false end ## # Disconnect from host def disconnect @inn.close rescue nil @out.close rescue nil @err.close rescue nil kill_process @pid, "HUP" rescue nil @pid = nil end ## # Download a file via rsync def download from_path, to_path, options={}, &block from_path = "#{@host}:#{from_path}" Sunshine.logger.info @host, "Downloading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Expand a path: # shell.expand_path "~user/thing" # #=> "/home/user/thing" def expand_path path dir = File.dirname path full_dir = call "cd #{dir} && pwd" File.join full_dir, File.basename(path) end ## # Checks if the given file exists def file? filepath - syscall "test -f #{filepath}" + self.system "test -f #{filepath}" end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " cmd = quote_cmd cmd pid = fork do exec \ ssh_cmd(sudo_cmd(env_cmd(cmd)), :flags => "-t").to_a.join(" ") end Process.waitpid pid end end ## # Create a file remotely def make_file filepath, content, options={} temp_filepath = "#{TMP_DIR}/#{File.basename(filepath)}_#{Time.now.to_i}#{rand(10000)}" File.open(temp_filepath, "w+"){|f| f.write(content)} self.upload temp_filepath, filepath, options File.delete(temp_filepath) end ## # Builds an ssh command with permissions, env, etc. def build_remote_cmd cmd, options={} cmd = sh_cmd cmd cmd = env_cmd cmd cmd = sudo_cmd cmd, options cmd = ssh_cmd cmd, options end ## # Uploads a file via rsync. def upload from_path, to_path, options={}, &block to_path = "#{@host}:#{to_path}" Sunshine.logger.info @host, "Uploading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Figure out which rsync flags to use. def build_rsync_flags options flags = @rsync_flags.dup remote_rsync = 'rsync' rsync_sudo = sudo_cmd remote_rsync, options unless rsync_sudo == remote_rsync flags << "--rsync-path='#{ rsync_sudo.join(" ") }'" end flags << "-e \"ssh #{@ssh_flags.join(' ')}\"" if @ssh_flags flags.concat [*options[:flags]] if options[:flags] flags end ## # Creates an rsync command. def rsync_cmd from_path, to_path, options={} cmd = ["rsync", build_rsync_flags(options), from_path, to_path] cmd.flatten.compact.join(" ") end ## # Wraps the command in an ssh call. def ssh_cmd cmd, options=nil options ||= {} flags = [*options[:flags]].concat @ssh_flags ["ssh", flags, @host, cmd].flatten.compact end end end diff --git a/lib/sunshine/shell.rb b/lib/sunshine/shell.rb index e242531..22157c6 100644 --- a/lib/sunshine/shell.rb +++ b/lib/sunshine/shell.rb @@ -1,432 +1,432 @@ module Sunshine ## # The Shell class handles local input, output and execution to the shell. class Shell include Open4 LOCAL_USER = `whoami`.chomp LOCAL_HOST = `hostname`.chomp SUDO_FAILED = /^Sorry, try again./ SUDO_PROMPT = /^Password:/ attr_reader :user, :host, :password, :input, :output, :mutex attr_accessor :env, :sudo, :timeout def initialize output = $stdout, options={} @output = output $stdin.sync @input = HighLine.new $stdin @user = LOCAL_USER @host = LOCAL_HOST @sudo = options[:sudo] @env = options[:env] || {} @password = options[:password] @timeout = options[:timeout] || Sunshine.timeout @mutex = nil end ## # Checks for equality def == shell @host == shell.host && @user == shell.user rescue false end ## # Prompt the user for input. def ask(*args, &block) sync{ @input.ask(*args, &block) } end ## # Prompt the user to agree. def agree(*args, &block) sync{ @input.agree(*args, &block) } end ## # Execute a command on the local system and return the output. def call cmd, options={}, &block Sunshine.logger.info @host, "Running: #{cmd}" do execute sudo_cmd(cmd, options), &block end end ## # Prompt the user to make a choice. def choose &block sync{ @input.choose(&block) } end ## # Close the output IO. (Required by the Logger class) def close @output.close end ## # Returns true. Compatibility method with RemoteShell. def connect true end ## # Returns true. Compatibility method with RemoteShell. def connected? true end ## # Returns true. Compatibility method with RemoteShell. def disconnect true end ## # Copies a file. Compatibility method with RemoteShell. def download from_path, to_path, options={}, &block Sunshine.logger.info @host, "Copying #{from_path} -> #{to_path}" do FileUtils.cp_r from_path, to_path end end alias upload download ## # Expands the path. Compatibility method with RemoteShell. def expand_path path File.expand_path path end ## # Checks if file exists. Compatibility method with RemoteShell. def file? filepath File.file? filepath end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " pid = fork do exec sudo_cmd(env_cmd(cmd)).to_a.join(" ") end Process.waitpid pid end end ## # Write a file. Compatibility method with RemoteShell. def make_file filepath, content, options={} File.open(filepath, "w+"){|f| f.write(content)} end ## # Get the name of the OS def os_name @os_name ||= call("uname -s").strip.downcase end ## # Prompt the user for a password def prompt_for_password host_info = [@user, @host].compact.join("@") @password = ask("#{host_info} Password:") do |q| q.echo = false end end ## # Build an env command if an env_hash is passed def env_cmd cmd, env_hash=@env if env_hash && !env_hash.empty? env_vars = env_hash.map{|e| e.join("=")} cmd = ["env", env_vars, cmd].flatten end cmd end ## # Wrap command in quotes and escape as needed. def quote_cmd cmd cmd = [*cmd].join(" ") "'#{cmd.gsub(/'/){|s| "'\\''"}}'" end ## # Build an sh -c command def sh_cmd cmd ["sh", "-c", quote_cmd(cmd)] end ## # Build a command with sudo. # If sudo_val is nil, it is considered to mean "pass-through" # and the default shell sudo will be used. # If sudo_val is false, the cmd will be returned unchanged. # If sudo_val is true, the returned command will be prefaced # with sudo -H # If sudo_val is a String, the command will be prefaced # with sudo -H -u string_value def sudo_cmd cmd, sudo_val=nil sudo_val = sudo_val[:sudo] if Hash === sudo_val sudo_val = @sudo if sudo_val.nil? case sudo_val when true ["sudo", "-H", cmd].flatten when String ["sudo", "-H", "-u", sudo_val, cmd].flatten else cmd end end ## # Force symlinking a directory. def symlink target, symlink_name call "ln -sfT #{target} #{symlink_name}" rescue false end ## # Synchronize a block with the current mutex if it exists. def sync if @mutex @mutex.synchronize{ yield } else yield end end ## # Returns true if command was run successfully, otherwise returns false. - def syscall cmd, options=nil + def system cmd, options=nil call(cmd, options) && true rescue false end ## # Checks if timeout occurred. def timed_out? start_time, max_time=@timeout return unless max_time Time.now.to_i - start_time.to_i > max_time end ## # Execute a block while setting the shell's mutex. # Sets the mutex to its original value on exit. # Executing commands with a mutex is used for user prompts. def with_mutex mutex old_mutex, @mutex = @mutex, mutex yield @mutex = old_mutex end ## # Runs the passed block within a connection session. # If the shell is already connected, connecting and disconnecting # is ignored; otherwise, the session method will ensure that # the shell's connection gets closed after the block has been # executed. def with_session prev_connection = connected? connect unless prev_connection yield disconnect unless prev_connection end ## # Write string to stdout (by default). def write str @output.write str end alias << write ## # Execute a command with open4 and loop until the process exits. # The cmd argument may be a string or an array. If a block is passed, # it will be called when data is received and passed the stream type # and stream string value: # shell.execute "test -s 'blah' && echo 'true'" do |stream, str| # stream #=> :stdout # string #=> 'true' # end # # The method returns the output from the stdout stream by default, and # raises a CmdError if the exit status of the command is not zero. def execute cmd cmd = [cmd] unless Array === cmd pid, inn, out, err = popen4(*cmd) inn.sync = true log_methods = {out => :debug, err => :error} result, status = process_streams(pid, out, err) do |stream, data| stream_name = :out if stream == out stream_name = :err if stream == err stream_name = :inn if stream == inn # User blocks should run with sync threads to avoid badness. sync do Sunshine.logger.send log_methods[stream], "#{@host}:#{stream_name}", data yield(stream_name, data, inn) if block_given? end if password_required?(stream_name, data) then kill_process(pid) unless Sunshine.interactive? send_password_to_stream(inn, data) end end raise_command_failed(status, cmd) unless status.success? result[out].join.chomp ensure inn.close rescue nil out.close rescue nil err.close rescue nil end private def raise_command_failed(status, cmd) err = CmdError.new status.exitstatus, [*cmd].join(" ") raise err end def password_required? stream_name, data stream_name == :err && data =~ SUDO_PROMPT end def send_password_to_stream inn, data prompt_for_password if data =~ SUDO_FAILED inn.puts @password || prompt_for_password end def kill_process pid, kill_type="KILL" begin Process.kill kill_type, pid Process.wait rescue end end def process_streams pid, *streams result = Hash.new{|h,k| h[k] = []} start_time = Time.now # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 raise TimeoutError if timed_out? start_time next if selected.nil? or selected.empty? selected.each do |stream| start_time = Time.now if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) yield(stream, data) result[stream] << data end end return result, status end end end
jcasts/sunshine
277fcc548d7d03b7349a498619c50e1a774a2767
fix for checkout with excludes
diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index 888043f..60b9fb1 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -89,1039 +89,1040 @@ module Sunshine # App.new "config.yml", :deploy_env => :qa_special # # # Another way of instantiating an App is to pass it a hash. Unlike the yaml # config file, the hash is not on a per-environment basis and isexpected # to already have the correct values for the given environment. # The following is equivalent to loading the above :default environment: # # App.new :remote_shells => "dev.myserver.com", # :repo => { # :type => :svn, # :url => "http://subversion/repo/tags/release-001" # } # # In theory, the minimum amount of information required to instantiate # an app is the repo and remote_shells. If the repo option is omitted, # the App will attempt to detect if the pwd is a checkout out repo and # use that information. If you would like to deploy an application that # is not under source countrol, you may do so by using Sunshine::RsyncRepo, # or passing :rsync in your hash as your repo type. # # # Options supported by App.new are the following: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. class App ## # Initialize and deploy an application. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] @on_sigint = @on_exception = nil end ## # Call a command on specified server apps. # Supports any App#find and Shell#call options. def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Connect server apps. Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected and returns a boolean. # Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected and returns a boolean. # Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect server apps. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # If the deploy fails or an exception is raised, it will attempt to # run the Sunshine.failed_deploy_behavior, which is set to :revert by # default. However, this is not true of ssh connection failures. # # If the deploy is interrupted by a SIGINT, it will attempt to run # the Sunshine.sigint_behavior, which is set to :revert by default. # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil state = { :success => false, :stopped => false, :symlinked => false } Sunshine.logger.info :app, "Beginning #{@name} deploy" with_session options do |app| interruptable state do raise DeployError, "No servers defined for #{@name}" if @server_apps.empty? make_app_directories checkout_codebase state[:stopped] = true if stop state[:symlinked] = true if symlink_current_dir yield self if block_given? run_post_user_lambdas health :enable build_control_scripts build_deploy_info_file build_crontab register_as_deployed state[:success] = true if start! :force => true end remove_old_deploys if state[:success] rescue Sunshine.logger.error :app, "Could not remove old deploys" state[:success] &&= deployed? end Sunshine.logger.info :app, "Finished #{@name} deploy" if state[:success] state[:success] end ## # Handles SIGINTs and exceptions according to rules set by # Sunshine.sigint_behavior and Sunshine.exception_behavior # or with the override hooks App#on_sigint and App#on_exception. def interruptable options={} interrupt_trap = TrapStack.add_trap "Interrupted #{@name}" do handle_sigint options end yield if block_given? rescue => e Sunshine.logger.error :app, "#{e.class}: #{e.message}" do Sunshine.logger.error '>>', e.backtrace.join("\n") end handle_exception e, options ensure TrapStack.delete_trap interrupt_trap end ## # Calls the Apps on_sigint hook or the default Sunshine.sigint_behavior. def handle_sigint state={} return @on_sigint.call(state) if @on_sigint handle_interruption Sunshine.sigint_behavior, state end ## # Calls the Apps on_exception hook or the default # Sunshine.exception_behavior. def handle_exception exception, state={} return @on_exception.call(exception, state) if @on_exception handle_interruption Sunshine.exception_behavior, state end ## # Set this to define the behavior of SIGINT during a deploy. # Defines what to do when an INT signal is received when running # a proc through App#interruptable. Used primarily to catch SIGINTs # during deploys. Passes the block a hash with the state of the deploy: # # app.on_sigint do |deploy_state_hash| # deploy_state_hash # #=> {:stopped => true, :symlinked => true, :success => false} # end def on_sigint &block @on_sigint = block end ## # Set this to define the behavior of exceptions during a deploy. # Defines what to do when an exception is received when running # a proc through App#interruptable. Used primarily to catch exceptions # during deploys. Passes the block the exception and a hash with the # state of the deploy: # # app.on_exception do |exception, deploy_state_hash| # # do something... # end def on_exception &block @on_exception = block end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. def handle_interruption behavior, state={} case behavior when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :revert revert! if state[:symlinked] start if state[:stopped] when Sunshine.interactive? && :console self.console! when Sunshine.interactive? && :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" menu.choice(:revert) { handle_interruption :revert, state } menu.choice(:console){ handle_interruption :console, state } menu.choice(:exit) { handle_interruption :exit, state } end else raise DeployError, "Deploy of #{@name} was interrupted." end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil - copy_option = options[:copy] if options + copy_option = options[:copy] if options + exclude = options.delete(:exclude) if options if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path scm_info[:exclude] = - [Sunshine.exclude_paths, options.delete(:exclude)].flatten.compact + [Sunshine.exclude_paths, exclude].flatten.compact with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Run the restart script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def restart! options=nil with_server_apps options, :msg => "Running restart script", :send => :restart! end ## # Runs bundler on deploy servers. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] end ## # Runs GemInstaller on deploy servers. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run the given script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def run_script! name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script!, name, options] end ## # Run a sass task on any or all deploy servers. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. def shell_env env_hash=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Run the start script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def start! options=nil with_server_apps options, :msg => "Running start script", :send => [:start!, options] end ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. # Post-deploy only. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end ## # Run the stop script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def stop! options=nil with_server_apps options, :msg => "Running stop script", :send => :stop! end ## # Use sudo on deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! def threaded_each(options=nil, &block) mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end ## # Upload common rake tasks from the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', :role => :web # #=> upload app and common rake files # # Allows standard DeployServerDispatcher#find options, plus: # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files.last ? files.last.dup : {} options.delete(:remote_path) options = :all if options.empty? with_server_apps options, :msg => "Uploading tasks: #{files.join(" ")}", :send => [:upload_tasks, *files] end ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here
jcasts/sunshine
5c11e83bc4aa9d2f71a66ae8f23c7cb2ae34b751
changed how daemon log files get chowned so that calling touch is not required/chown
diff --git a/lib/sunshine/daemon.rb b/lib/sunshine/daemon.rb index 3e28921..fcbcfaf 100644 --- a/lib/sunshine/daemon.rb +++ b/lib/sunshine/daemon.rb @@ -1,490 +1,490 @@ module Sunshine ## # An abstract class to wrap simple daemon software setup and start/stop. # # Child classes are expected to at least provide a start and stop bash script # by either overloading the start_cmd and stop_cmd methods, or by setting # @start_cmd and @stop_cmd. A restart_cmd method or @restart_cmd attribute # may also be specified if restart requires more functionality than simply # calling start_cmd && stop_cmd. class Daemon START_FAILED_CODE = 10 STOP_FAILED_CODE = 11 RESTART_FAILED_CODE = 12 STATUS_DOWN_CODE = 13 ## # Returns an array of method names to assign to the binder # for template rendering. def self.binder_methods [:app, :name, :bin, :pid, :processes, :config_path, :log_file, :timeout] end ## # Returns the short, snake-case version of the class: # Sunshine::Daemon.short_name # #=> "daemon" def self.short_name @short_name ||= self.underscore self.to_s.split("::").last end ## # Turn camelcase into underscore. Used for Daemon#name. def self.underscore str str.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2').downcase end attr_reader :app, :name attr_accessor :bin, :pid, :processes, :timeout, :sudo, :server_apps attr_accessor :config_template, :config_path, :config_file attr_writer :start_cmd, :stop_cmd, :restart_cmd, :status_cmd # Daemon objects need only an App object to be instantiated but many options # are available for customization: # # :bin:: bin_path - Set the daemon app bin path (e.g. usr/local/nginx) # defaults to svr_name. # # :processes:: prcss_num - Number of processes daemon should run; # defaults to 1. # # :config_file:: name - Remote file name the daemon should load; # defaults to svr_name.conf # # :config_path:: path - Remote path daemon configs will be uploaded to; # defaults to app.current_path/daemons/svr_name # # :config_template:: path - Glob path to tempates to render and upload; # defaults to sunshine_path/templates/svr_name/* # # :log_path:: path - Path to where the log files should be output; # defaults to app.log_path. # # :pid:: pid_path - Set the pid; default: app.shared_path/pids/svr_name.pid # defaults to app.shared_path/pids/svr_name.pid. # # :sudo:: bool|str - Define if sudo should be used to run the daemon, # and/or with what user. # # :timeout:: int - Timeout to use for daemon config, defaults to 0. # # The Daemon constructor also supports any App#find options to narrow # the server apps to use. Note: subclasses such as Server already have # a default :role that can be overridden. def initialize app, options={} @options = options @app = app @name = options[:name] || self.class.short_name @pid = options[:pid] || "#{@app.shared_path}/pids/#{@name}.pid" @bin = options[:bin] || self.class.short_name @sudo = options[:sudo] @timeout = options[:timeout] || 0 @dep_name = options[:dep_name] || self.class.short_name @processes = options[:processes] || 1 @sigkill = 'QUIT' @config_template = options[:config_template] || "#{Sunshine::ROOT}/templates/#{self.class.short_name}/*" @config_path = options[:config_path] || "#{@app.current_path}/daemons/#{@name}" @config_file = options[:config_file] || "#{self.class.short_name}.conf" log_path = options[:log_path] || @app.log_path @log_files = { :stderr => "#{log_path}/#{@name}_stderr.log", :stdout => "#{log_path}/#{@name}_stdout.log" } @start_cmd = @stop_cmd = @restart_cmd = @status_cmd = nil @setup_successful = nil register_after_user_script end ## # Do something with each server app used by the daemon. def each_server_app(&block) @app.each(@options, &block) end ## # Setup the daemon, parse and upload config templates. # If a dependency with the daemon name exists in Sunshine.dependencies, # setup will attempt to install the dependency before uploading configs. # If a block is given it will be passed each server_app and binder object # which will be used for the building erb config templates. # See the ConfigBinding class for more information. def setup Sunshine.logger.info @name, "Setting up #{@name} daemon" do each_server_app do |server_app| # Build erb binding binder = config_binding server_app.shell configure_remote_dirs server_app.shell - touch_log_files server_app.shell + chown_log_files server_app.shell yield(server_app, binder) if block_given? server_app.install_deps @dep_name if Sunshine.dependencies.exist?(@dep_name) upload_config_files(server_app.shell, binder.get_binding) end end @setup_successful = true rescue => e raise DaemonError.new(e, "Could not setup #{@name}") end ## # Check if setup was run successfully. def has_setup? force=false return @setup_successful unless @setup_successful.nil? || force each_server_app do |server_app| unless server_app.shell.file? config_file_path return @setup_successful = false end end @setup_successful = true end ## # Start the daemon app after running setup. def start self.setup unless has_setup? Sunshine.logger.info @name, "Starting #{@name} daemon" do each_server_app do |server_app| begin server_app.shell.call _start_cmd, :sudo => pick_sudo(server_app.shell) yield(server_app) if block_given? rescue => e raise DaemonError.new(e, "Could not start #{@name}") end end end end ## # Check if the daemon is running on all servers def status each_server_app do |server_app| server_app.shell.call _status_cmd, :sudo => pick_sudo(server_app.shell) end true rescue CmdError => e false end ## # Stop the daemon app. def stop Sunshine.logger.info @name, "Stopping #{@name} daemon" do each_server_app do |server_app| begin server_app.shell.call _stop_cmd, :sudo => pick_sudo(server_app.shell) yield(server_app) if block_given? rescue => e raise DaemonError.new(e, "Could not stop #{@name}") end end end end ## # Restarts the daemon using the restart_cmd attribute if provided. # If restart_cmd is not provided, calls stop and start. def restart self.setup unless has_setup? Sunshine.logger.info @name, "Restarting #{@name} daemon" do each_server_app do |server_app| begin server_app.shell.call _restart_cmd, :sudo => pick_sudo(server_app.shell) yield(server_app) if block_given? rescue => e raise DaemonError.new(e, "Could not restart #{@name}") end end end end ## # Wrap a command with a fail-specific exitcode and message. def exit_on_failure cmd, exitcode=1, message=nil "(#{cmd}) || (echo '#{message}' && exit #{exitcode});" end ## # Gets the command that starts the daemon. # Should be overridden by child classes. def start_cmd return @start_cmd if @start_cmd raise DaemonError, "start_cmd undefined for #{@name}" end ## # Start command wrapped with an exit_on_failure handler. def _start_cmd exit_on_failure start_cmd, START_FAILED_CODE, "Could not start #{@name} for #{@app.name}" end ## # Default daemon stop command. def stop_cmd "test -f #{@pid} && kill -#{@sigkill} $(cat #{@pid}) && sleep 1 && "+ "rm -f #{@pid}" end ## # Stop command wrapped with an exit_on_failure handler. def _stop_cmd exit_on_failure stop_cmd, STOP_FAILED_CODE, "Could not kill #{@name} pid for #{@app.name}" end ## # Gets the command that restarts the daemon. # Should be overridden by child classes if different # from start_cmd && stop_cmd. def restart_cmd @restart_cmd end ## # Restart command wrapped with an exit_on_failure handler. def _restart_cmd if restart_cmd exit_on_failure restart_cmd, RESTART_FAILED_CODE, "Could not restart #{@name} for #{@app.name}" else "(#{_stop_cmd}) && (#{_start_cmd});" end end ## # Status command wrapped with an exit_on_failure handler. def status_cmd @status_cmd || "test -f #{@pid} && kill -0 $(cat #{@pid})" end ## # Get the command to check if the daemon is running. def _status_cmd exit_on_failure status_cmd, STATUS_DOWN_CODE, "#{@app.name} #{@name} is not running" end ## # Append or override daemon log file paths: # daemon.log_files :stderr => "/all_logs/stderr.log" def log_files hash @log_files.merge!(hash) end ## # Get the path of a log file: # daemon.log_file(:stderr) # #=> "/all_logs/stderr.log" def log_file key @log_files[key] end ## # Get the file path to the daemon's config file. def config_file_path "#{@config_path}/#{@config_file}" end ## # Upload config files and run them through erb with the provided # binding if necessary. def upload_config_files shell, setup_binding=binding config_template_files.each do |config_file| if File.extname(config_file) == ".erb" filename = File.basename(config_file[0..-5]) parsed_config = @app.build_erb(config_file, setup_binding) shell.make_file "#{@config_path}/#{filename}", parsed_config else filename = File.basename(config_file) shell.upload config_file, "#{@config_path}/#{filename}" end end end ## # Get the array of local config template files needed by the daemon. def config_template_files @config_template_files ||= Dir[@config_template].select{|f| File.file?(f)} end ## # Create and setup a binding for a given shell. def config_binding shell binder = Binder.new self binder.forward(*self.class.binder_methods) binder.set :shell, shell binder_sudo = pick_sudo(shell) binder.set :sudo, binder_sudo binder.set :expand_path do |path| shell.expand_path path end binder end ## # Pick which sudo to use between the daemon sudo and shell sudo. # (Useful when running servers on ports < 1024) def pick_sudo shell self.sudo.nil? ? shell.sudo : self.sudo end ## # Make sure all the remote directories needed by the daemon exist. def configure_remote_dirs shell dirs = @log_files.values.map{|f| File.dirname(f)} dirs << File.dirname(@pid) dirs << @config_path dirs.delete_if{|d| d == "."} dirs = dirs.join(" ") shell.call "mkdir -p #{dirs}" end ## # Make sure log files are owned by the daemon's user. - def touch_log_files shell + def chown_log_files shell files = @log_files.values.join(" ") sudo = pick_sudo(shell) user = case sudo when true then 'root' when String then sudo else nil end - shell.call "touch #{files}", :sudo => true - shell.call "chown #{user} #{files}", :sudo => true if user + return unless user + shell.call "chown -f #{user} #{files}", :sudo => true rescue nil end ## # Setup what should be run after the user block on App#deploy. def register_after_user_script @app.after_user_script do |app| next unless has_setup? each_server_app do |sa| sudo = pick_sudo sa.shell %w{start stop restart status}.each do |script| script_file = "#{@config_path}/#{script}" cmd = send "_#{script}_cmd" sa.shell.make_file script_file, cmd, :flags => '--chmod=ugo=rwx' cmd = sa.shell.sudo_cmd "#{@app.root_path}/env #{script_file}", sudo sa.scripts[script.to_sym] << [*cmd].join(" ") end end end end end end diff --git a/test/unit/test_server.rb b/test/unit/test_server.rb index 2209653..0981952 100644 --- a/test/unit/test_server.rb +++ b/test/unit/test_server.rb @@ -1,309 +1,309 @@ require 'test/test_helper' class TestServer < Test::Unit::TestCase class Server < Sunshine::Server def start_cmd "test start cmd" end def stop_cmd "test stop cmd" end end def setup mock_remote_shell_popen4 @app = Sunshine::App.new(TEST_APP_CONFIG_FILE).extend MockObject @server_app = @app.server_apps.first.extend MockObject @app.server_apps.first.shell.extend MockObject @server = Server.new @app @rainbows = Sunshine::Rainbows.new(@app).extend MockObject use_remote_shell @server_app.shell end def test_initialize assert_server_init config = { :point_to => @server, :pid => "path/to/pid", :bin => "path/to/bin", :port => 1234, :processes => 10, :server_name => "serv1.com", :server_apps => ["remote_shell_test"], :config_template => "template.erb", :config_path => "path/to/config", :config_file => "conf_filename.conf", :log_path => "path/to/logs", :sudo => "sudouser" } svr = Server.new @app, config config[:target] = config[:point_to] config[:stderr] = "#{config[:log_path]}/server_stderr.log" config[:stdout] = "#{config[:log_path]}/server_stdout.log" assert_server_init svr, config end def test_setup server = @rainbows server.setup do |sa, binder| assert_equal @server_app, sa assert_equal sa.shell, binder.shell assert_equal sa.shell.host, binder.server_name assert_equal @rainbows.send(:pick_sudo, sa.shell), binder.sudo end server.each_server_app do |sa| assert sa.method_called?(:install_deps, :args => ["rainbows"]) assert server.method_called?(:configure_remote_dirs, :args => [sa.shell]) - assert server.method_called?(:touch_log_files, :args => [sa.shell]) + assert server.method_called?(:chown_log_files, :args => [sa.shell]) assert server.method_called?(:upload_config_files, :args => [sa.shell]) end assert_rsync(/rainbows\.conf/, "some_server.com:"+ "/usr/local/my_user/other_app/current/daemons/rainbows/rainbows.conf") assert server.has_setup? end def test_has_setup? server = @rainbows assert_equal nil, server.instance_variable_get("@setup_successful") @server_app.shell.mock :file?, :args => [server.config_file_path], :return => false assert_equal false, server.has_setup? @server_app.shell.mock :file?, :args => [server.config_file_path], :return => true assert_equal false, server.has_setup? assert_equal true, server.has_setup?(true) end def test_new_cluster cluster = Sunshine::Server.new_cluster 3, @app, :port => 5000 assert_equal Sunshine::ServerCluster, cluster.class assert Array === cluster assert_equal 3, cluster.length cluster.each_with_index do |server, index| port = 5000 + index assert_equal Sunshine::Server, server.class assert_equal port, server.port assert_equal "server.#{port}", server.name end end def test_start server = @rainbows @server_app.shell.mock :file?, :args => [server.config_file_path], :return => false server.start do |sa| assert_equal @server_app, sa assert_ssh_call server._start_cmd, sa.shell, :sudo => true end assert server.method_called?(:setup) end def test_start_missing_setup server = @rainbows @server_app.shell.mock :file?, :args => [server.config_file_path], :return => true server.start do |sa| assert_equal @server_app, sa assert_ssh_call server._start_cmd, sa.shell, :sudo => true end assert !server.method_called?(:setup) end def test_stop server = @rainbows server.stop do |sa| assert_equal @server_app, sa assert_ssh_call server._stop_cmd, sa.shell, :sudo => true end end def test_restart server = @rainbows server.restart do |sa| assert_equal @server_app, sa assert_ssh_call server._restart_cmd, sa.shell, :sudo => true end end def test_restart_missing_setup server = @rainbows @server_app.shell.mock :file?, :args => [server.config_file_path], :return => true server.restart assert !server.method_called?(:setup) end def test_restart_with_cmd server = @rainbows server.instance_variable_set("@restart_cmd", "RESTART!!1!") @server_app.shell.mock :file?, :args => [server.config_file_path], :return => false server.restart do |sa| assert_equal @server_app, sa assert_ssh_call server._restart_cmd, sa.shell, :sudo => true end assert server.method_called?(:setup) end def test_log_files @server.log_files :test_log => "/path/test_log.log", :another_test => "/path/another_test.log" assert_equal "/path/test_log.log", @server.log_file(:test_log) assert_equal "/path/another_test.log", @server.log_file(:another_test) end def test_upload_config_files server = @rainbows server.mock :config_template_files, :return => ["rainbows.conf.erb", "test/non_erb.conf"] @app.mock :build_erb, :return => "test_config" server.upload_config_files @server_app.shell args = ["#{server.config_path}/rainbows.conf", "test_config"] assert @server_app.shell.method_called?(:make_file, :args => args) args = ["test/non_erb.conf", "#{server.config_path}/non_erb.conf"] assert @server_app.shell.method_called?(:upload, :args => args) end def test_config_template_files files = Dir["#{Sunshine::ROOT}/templates/rainbows/*"].select{|f| File.file?(f)} assert_equal files, @rainbows.config_template_files end def test_register_after_user_script server = @rainbows assert @app.method_called?(:after_user_script) # called on Server#init @app.run_post_user_lambdas server.each_server_app do |sa| %w{start stop restart status}.each do |script| script_file = "#{@app.root_path}/env #{server.config_path}/#{script}" cmd = sa.shell.sudo_cmd script_file, server.send(:pick_sudo, sa.shell) assert sa.scripts[script.to_sym].include?(cmd.join(" ")) end assert_equal server.port, sa.info[:ports][server.pid] end end def test_pick_sudo ds = @rainbows.app.server_apps.first.shell assert_equal true, @rainbows.send(:pick_sudo, ds) @rainbows.sudo = true assert_equal true, @rainbows.send(:pick_sudo, ds) ds.sudo = true @rainbows.sudo = false assert_equal false, @rainbows.send(:pick_sudo, ds) ds.sudo = "blah" @rainbows.sudo = true assert_equal true, @rainbows.send(:pick_sudo, ds) @rainbows.sudo = "local" assert_equal "local", @rainbows.send(:pick_sudo, ds) end ## # Helper methods def assert_dir_in arr, file assert arr.include?(File.dirname(file)) end def assert_server_init server=@server, user_config={} config = { :app => @app, :target => @app, :name => "server", :pid => "#{@app.shared_path}/pids/server.pid", :bin => "server", :port => 80, :processes => 1, :server_name => nil, :config_file => "server.conf", :config_path => "#{@app.current_path}/daemons/server", :config_template => "#{Sunshine::ROOT}/templates/server/*", :stderr => "#{@app.log_path}/server_stderr.log", :stdout => "#{@app.log_path}/server_stdout.log" }.merge(user_config) assert_equal config[:app], server.app assert_equal config[:bin], server.bin assert_equal config[:pid], server.pid assert_equal config[:port], server.port assert_equal config[:name], server.name assert_equal config[:target], server.target assert_equal config[:processes], server.processes assert_equal config[:server_name], server.server_name assert_equal config[:config_path], server.config_path assert_equal config[:config_file], server.config_file assert_equal config[:config_template], server.config_template assert_equal config[:stderr], server.log_file(:stderr) assert_equal config[:stdout], server.log_file(:stdout) config_file_path = "#{config[:config_path]}/#{config[:config_file]}" assert_equal config_file_path, server.config_file_path end end
jcasts/sunshine
d0a76de647e9434175b044897eb8d5e817248625
added exclude paths for checkouts by rsync
diff --git a/History.txt b/History.txt index 8261f21..60c6c53 100644 --- a/History.txt +++ b/History.txt @@ -1,363 +1,367 @@ === 1.2.1 / 2010-10-05 * Improvements: * Added customizable behaviors for sigint and failures during deploys. * Added Sunshine irb shell to work directly with deploying apps. * Added ability to launch a pseudo terminal from a RemoteShell. * Added exit code to CmdError. + * Added exclude paths for checkout by copy. + * Bugfixes: * Fixed custom scripts. * Fixed deploy env defaults. * Removed Shell#update_timeout as it was unnecessary. + * RemoteShell rsync recurses by default. + === 1.2.0 / 2010-09-08 * Improvements: * Added better support for custom env/start/stop/restart scripts. * Added scripts sunshine command to call custom scripts remotely. * Deploy env defaults to ENV 'DEPLOY_ENV', 'env', 'RACK_ENV', or 'RAILS_ENV'. * Bugfixes: * ServerApp#run_geminstaller no longer defaults to using sudo. * Added better extensible package manager checking to ServerApp. * Fixed Cronjob functionality and added array support. === 1.1.2 / 2010-04-15 * Improvements: * Added array support to App#find. * Added auto registration of Dependency subclasses for scalability. * Added call to App#start in App#deploy. * Bugfixes: * Fixed bug where env wouldn't be applied correctly in control scripts. * Changed App#with_filter to actually change the App#server_apps attribute. * Shell#env_cmd now returns a flattened array. * Added actual check of running process to Daemon#status_cmd. === 1.1.1 / 2010-04-05 * Improvements: * Added Repo subclass registration for greater expandability. * Added support for checking out codebases locally then rsync-ing them. * Bugfixes: * Fixed RemoteShell login script lingering after disconnect. === 1.1.0 / 2010-04-02 * Improvements: * Support for server clustering with the ServerCluster class. * Added Daemon#status method. * Added the -R option for loading external libraries and gems. * Added support for Thin and MongrelRails. * Added Server support for max connections configuration. * Bugfixes: * Daemons no longer create control scripts if they aren't used. * Fixed Rsync repo to auto append "/" to urls for correct rsyncing. === 1.0.3 / 2010-03-26 * Improvements: * Added App#call method. * Added App#with_session and Shell#with_session to reduce login prompts. * Bugfixes: * Geminstaller now always installs with sudo. * Fixed permissions issues with running servers on ports < 1024. * Fixed healthcheck middleware. === 1.0.2 / 2010-03-25 * Bugfixes: * Fixed apache passenger dependency to run as sudo. * Fixed a bug in Repo::detect === 1.0.1 / 2010-03-25 * Bugfixes: * Added json dependency === 1.0.0 / 2010-03-25 * Improvements: * Added auto_dependencies config to turn on/off auto installing things. * Added healthcheck middleware support. * Added support for Apache2 and its passenger implementation. * Removed all Atti-specific code for public release. * Bugfixes: * Fixed Nginx passenger implementation. === 0.0.6 / 2010-03-19 * Major: * Removed DeployServerDispatcher. Dispatching now happens at the App level. * Moved Settler into Sunshine and renamed it to DependencyLib. * Improvements: * Added INT signal handling to exit deploys and close connections gracefully. * Added dependency installation methods apt_install, gem_install, tpkg_install and yum_install to App and ServerApp. * Extended functionality of ServerApp#upload_tasks. * ServerApp now support being instatiated with an App instance (for coordinated deploys) or just with an app name (for post-deploy usage). * Added a Sunshine rakefile template for task-based deploys. Available through: sunshine --rakefile [COPY_TO] * App#name gets auto-assigned by repo info if not provided. * Sunshine::web_directory used to determine App#deploy_path when missing. * Repo#detect now returns a Repo object instead of an array. * Added start/stop/restart/status methods to DeployServerApp. * ServerApp instances with unspecified roles get all roles by default. * App config files now use erb parsing. Any key/value passed the App constructor as a hash should be passed to the erb binding along with the deploy_env. * Added support to bundler for defining multiple dependencies with the same name, and different package managers. * Bugfixes: * Added setup checking to Daemon to only run setup when needed. * Moved healthcheck from App to ServerApp and improved the api. * Renamed DeployServerApp to ServerApp. * Renamed App#deploy_path and App#deploys_dir to App#root_path and App#deploys_path. * Renamed the 'deploy' command to 'run' to more accurately express it's use. * RsyncRepo#do_checkout fixed to match standard Repo#do_checkout methods. * Sunshine::DATA and Sunshine::PATH are now set when running standalone ruby deploy files. === 0.0.5 / 2010-02-26 * Sunshine::App: * Use of DeployServerDispatcher threading * Fixed control script creation to be deploy_server specific (takes roles into account) * Added AttiApp class for ATTi app deployment. * Constuctor supports :deploy_name option for nameable deploys. Defaults to the timestamp. * Auto-detects if the script's directory is a checked out repo and uses it if no repo information was given. * Support for running sass. * Sunshine::DeployServerDispatcher: * Added threading support * Sunshine::Repo: * Added support for detecting a repo type based on a path: Repo.detect [path [, console_or_deploy_server]] #=> [:git, "git://url/of/git/repo", {:tree => "master", ...}] * Moved info instance methods to the class * Support for git-svn: SvnRepo.git_svn? path * Changed the checkout_to method signature * Sunshine::Server: * Added support for ar_sendmail server. === 0.0.4 / 2010-02-12 * Added sudo functionality: * Support for :sudo option on Sunshine::App, Sunshine::Server, and Sunshine::DeployServer constructors, and attr_accessor :sudo * Settler Dependency classes support a default sudo value: Sunshine::Dependencies::Gem.sudo = true # use sudo Sunshine::Dependencies::Gem.sudo = "usr" # use sudo -u usr Sunshine::Dependencies::Gem.sudo = false # ensure sudo is off Sunshine::Dependencies::Gem.sudo = nil # use :call obj precedence * App supports passing a (yml) file object to the constructor. Useful for passing file DATA if desired: app = Sunshine::App.new Sunshine::DATA app.deploy!{|app| Sunshine::Rainbows.new(app).restart } __END__ #yaml for app goes here... * App class changes: * Changed the format of the App#checkout_path directory * Logrotate setup now has to be called explicitely * Commands functionality expanded: * Support for --sudo and --sudo=user on all Sunshine commands * Added --format option for control commands. Supports txt, yml, json. * Control scripts generated on the remote server now keep deploy-time shell_env variables: * Run commands with the --no-env option to run without deploy shell_env variables. * Run any script with the app's env variables using: /path/to/app/env some_command /path/to/app/env EXTRA_VAR=some_value some_command Supports all options the env command supports. * Dependency handling now supports apt. * DeployServers now support passing custom flags for ssh and rsync: deploy_server = DeployServer.new "svr.com", :rsync_flags => [...] deploy_server.call "some_command", :sudo => "user", :flags => '-C' deploy_server.upload "from", "to", :sudo => "user", :flags => ['--chmod=ugo=rwX', '-b'] deploy_server.download "from", "to", :flags => '--ignore-existing' * Repo implementation has significantly changed: * Added support for git repo. * Info about a repo is now retrieved with Repo#get_repo_info: repo.get_repo_info deploy_server, checkout_path * Repo constructor supports options hash with :flags option. === 0.0.3 / 2010-01-29 * Many small bugfixes * Tests, tests, and more tests * Changed DeployServer api * DeployServer#run is not longer supported, use DeployServer#call * Constructor supports a spaced delimited list for roles: DeployServer.new "myhost.com", :roles => "web db other" * Changed how deploy server yaml is parsed. Should parse to be valid on: DeployServer.new *parsed_yaml Example Given: :deploy_servers : - server1.com - - server2.com - - server3.com - :roles : web db other :ssh_flags : '-o ControlMaster=auto' === 0.0.2 / 2010-01-15 * Added Control Commands * add, deploy, list, restart, rm, start, stop * Application support * Changed VERSION file to info and its format to yaml * Deployed apps now have a start, stop and restart script * Added Crontab and log rotation support * Functional changes * Ditched net/ssh and net/scp for ssh and rsync through Open4 * Fixed and updated dependencies to use Yum * Support for sunshine user configuration in ~/.sunshine * Rake tasks * Support to run the app's rake tasks * Built in default ATTi rake tasks === 0.0.1 / 2009-11-18 * 1 major enhancement * First release! diff --git a/lib/sunshine.rb b/lib/sunshine.rb index 146f2f0..84ce799 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,439 +1,441 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'yaml' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' require 'irb' # Turn off EOF tracking to be able to prompt on deploy exceptions. HighLine.track_eof = false ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. VERSION = '1.2.1' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { 'interactive' => true, 'auto_dependencies' => true, 'deploy_env' => :development, 'exception_behavior' => :revert, + 'exclude_paths' => [], 'level' => 'info', 'max_deploy_versions' => 5, 'remote_checkouts' => false, 'timeout' => 300, 'sigint_behavior' => :revert, 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end ## # Defines what to do when deploy raises an exception. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.exception_behavior @config['exception_behavior'] end ## # Array of paths or globs that should be excluded from the checkout. + # Does not work with remote_checkouts enabled. def self.exclude_paths @config['exclude_paths'] end ## # Should sunshine ever ask for user input? True by default. # Overridden in the config or with the -a option. def self.interactive? @config['interactive'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end ## # Defines what to do when sigint is sent during deploys. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.sigint_behavior @config['sigint_behavior'] end ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config unless File.file? USER_CONFIG_FILE File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" msg << DEFAULT_CONFIG.to_yaml self.exit 1, msg end load_config_file USER_CONFIG_FILE @config['deploy_env'] = ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] || @config['deploy_env'] @config end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset TrapStack.trap_signal :INT do |msg| $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" logger.info :INT, msg end TrapStack.add_trap "Disconnecting all remote shells." do RemoteShell.disconnect_all end require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' require 'sunshine/trap_stack' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' require 'sunshine/healthcheck' require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies' diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index fa25489..888043f 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -102,1024 +102,1027 @@ module Sunshine # # In theory, the minimum amount of information required to instantiate # an app is the repo and remote_shells. If the repo option is omitted, # the App will attempt to detect if the pwd is a checkout out repo and # use that information. If you would like to deploy an application that # is not under source countrol, you may do so by using Sunshine::RsyncRepo, # or passing :rsync in your hash as your repo type. # # # Options supported by App.new are the following: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. class App ## # Initialize and deploy an application. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] @on_sigint = @on_exception = nil end ## # Call a command on specified server apps. # Supports any App#find and Shell#call options. def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Connect server apps. Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected and returns a boolean. # Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected and returns a boolean. # Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect server apps. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # If the deploy fails or an exception is raised, it will attempt to # run the Sunshine.failed_deploy_behavior, which is set to :revert by # default. However, this is not true of ssh connection failures. # # If the deploy is interrupted by a SIGINT, it will attempt to run # the Sunshine.sigint_behavior, which is set to :revert by default. # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil state = { :success => false, :stopped => false, :symlinked => false } Sunshine.logger.info :app, "Beginning #{@name} deploy" with_session options do |app| interruptable state do raise DeployError, "No servers defined for #{@name}" if @server_apps.empty? make_app_directories checkout_codebase state[:stopped] = true if stop state[:symlinked] = true if symlink_current_dir yield self if block_given? run_post_user_lambdas health :enable build_control_scripts build_deploy_info_file build_crontab register_as_deployed state[:success] = true if start! :force => true end remove_old_deploys if state[:success] rescue Sunshine.logger.error :app, "Could not remove old deploys" state[:success] &&= deployed? end Sunshine.logger.info :app, "Finished #{@name} deploy" if state[:success] state[:success] end ## # Handles SIGINTs and exceptions according to rules set by # Sunshine.sigint_behavior and Sunshine.exception_behavior # or with the override hooks App#on_sigint and App#on_exception. def interruptable options={} interrupt_trap = TrapStack.add_trap "Interrupted #{@name}" do handle_sigint options end yield if block_given? rescue => e Sunshine.logger.error :app, "#{e.class}: #{e.message}" do Sunshine.logger.error '>>', e.backtrace.join("\n") end handle_exception e, options ensure TrapStack.delete_trap interrupt_trap end ## # Calls the Apps on_sigint hook or the default Sunshine.sigint_behavior. def handle_sigint state={} return @on_sigint.call(state) if @on_sigint handle_interruption Sunshine.sigint_behavior, state end ## # Calls the Apps on_exception hook or the default # Sunshine.exception_behavior. def handle_exception exception, state={} return @on_exception.call(exception, state) if @on_exception handle_interruption Sunshine.exception_behavior, state end ## # Set this to define the behavior of SIGINT during a deploy. # Defines what to do when an INT signal is received when running # a proc through App#interruptable. Used primarily to catch SIGINTs # during deploys. Passes the block a hash with the state of the deploy: # # app.on_sigint do |deploy_state_hash| # deploy_state_hash # #=> {:stopped => true, :symlinked => true, :success => false} # end def on_sigint &block @on_sigint = block end ## # Set this to define the behavior of exceptions during a deploy. # Defines what to do when an exception is received when running # a proc through App#interruptable. Used primarily to catch exceptions # during deploys. Passes the block the exception and a hash with the # state of the deploy: # # app.on_exception do |exception, deploy_state_hash| # # do something... # end def on_exception &block @on_exception = block end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. def handle_interruption behavior, state={} case behavior when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :revert revert! if state[:symlinked] start if state[:stopped] when Sunshine.interactive? && :console self.console! when Sunshine.interactive? && :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" menu.choice(:revert) { handle_interruption :revert, state } menu.choice(:console){ handle_interruption :console, state } menu.choice(:exit) { handle_interruption :exit, state } end else raise DeployError, "Deploy of #{@name} was interrupted." end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil copy_option = options[:copy] if options if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path + scm_info[:exclude] = + [Sunshine.exclude_paths, options.delete(:exclude)].flatten.compact + with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Run the restart script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def restart! options=nil with_server_apps options, :msg => "Running restart script", :send => :restart! end ## # Runs bundler on deploy servers. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] end ## # Runs GemInstaller on deploy servers. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run the given script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def run_script! name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script!, name, options] end ## # Run a sass task on any or all deploy servers. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. def shell_env env_hash=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Run the start script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def start! options=nil with_server_apps options, :msg => "Running start script", :send => [:start!, options] end ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. # Post-deploy only. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end ## # Run the stop script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def stop! options=nil with_server_apps options, :msg => "Running stop script", :send => :stop! end ## # Use sudo on deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! def threaded_each(options=nil, &block) mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end ## # Upload common rake tasks from the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', :role => :web # #=> upload app and common rake files # # Allows standard DeployServerDispatcher#find options, plus: # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files.last ? files.last.dup : {} options.delete(:remote_path) options = :all if options.empty? with_server_apps options, :msg => "Uploading tasks: #{files.join(" ")}", :send => [:upload_tasks, *files] end ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here # end diff --git a/lib/sunshine/repo.rb b/lib/sunshine/repo.rb index 25edad6..caae354 100644 --- a/lib/sunshine/repo.rb +++ b/lib/sunshine/repo.rb @@ -1,147 +1,148 @@ module Sunshine ## # An abstract class to wrap simple basic scm features. The primary function # of repo objects is to get information about the scm branch that is being # deployed and to check it out on remote deploy servers: # svn = SvnRepo.new "svn://path/to/repo", :flags => "--ignore-externals" # # The :flags option can be a String or an Array and supports any scm # checkout (or clone for git) options. class Repo ## # Adds subclasses to a repo_types hash for easy def self.inherited subclass @@repo_types ||= {} # Turn Sunshine::ScmNameRepo into :scm_name class_key = subclass.to_s.split("::").last class_key = $1 if class_key =~ /(\w+)Repo$/ class_key.gsub!(/([a-z0-9])([A-Z])/, '\1_\2') class_key = class_key.downcase @@repo_types[class_key] = subclass end ## # Creates a new repo subclass object: # Repo.new_of_type :svn, "https://path/to/repo/tags/releasetag" # Repo.new_of_type :git, "[email protected]:repo/path" def self.new_of_type repo_type, url, options={} repo_class = @@repo_types[repo_type.to_s] raise RepoError, "Invalid type #{repo_type.inspect}" unless repo_class repo_class.new(url, options) end ## # Looks for .git and .svn directories and determines if the passed path # is a recognized repo. Does not check for RsyncRepo since it's a # special case. Returns the appropriate repo object: # Repo.detect "path/to/svn/repo/dir" # #=> <SvnRepo @url="svn://url/of/checked/out/repo"> # Repo.detect "path/to/git/repo/dir" # #=> <GitRepo, @url="git://url/of/git/repo", @branch="master"> # Repo.detect "invalid/repo/path" # #=> nil def self.detect path=".", shell=nil @@repo_types.values.each do |repo| if repo.valid? path info = repo.get_info path, shell return repo.new(info[:url], info) end end nil end ## # Gets repo information for the specified dir - Implemented by subclass def self.get_info path=".", shell=nil raise RepoError, "The 'get_info' method must be implemented by child classes" end ## # Checks if current working directory is a valid repo. # Defaults to false. Subclasses must override this method to enable # auto detecting of a given scm implementation. def self.valid? *args false end - attr_reader :url, :scm + attr_accessor :url, :scm, :flags def initialize url, options={} @scm = self.class.name.split("::").last.sub('Repo', '').downcase @url = url.to_s @flags = [*options[:flags]].compact end ## # Checkout code to a shell and return an info log hash: # repo.chekout_to "some/path", remote_shell # #=> {:revision => 123, :committer => 'someone', :date => time_obj ...} def checkout_to path, shell=nil shell ||= Sunshine.shell shell.call "test -d #{path} && rm -rf #{path} || echo false" shell.call "mkdir -p #{path}" - do_checkout path, shell - get_repo_info path, shell + do_checkout path, shell + get_repo_info path, shell end + ## # Checkout the repo - implemented by subclass def do_checkout path, shell raise RepoError, "The 'do_checkout' method must be implemented by child classes" end ## # Get the project name of the specified repo - implemented by subclass def name raise RepoError, "The 'name' method must be implemented by child classes" end ## # Returns the set scm flags as a string def scm_flags @flags.join(" ") end ## # Returns the repo information as a hash. def get_repo_info path=".", shell=nil defaults = {:type => @scm, :url => @url, :path => path} defaults.merge self.class.get_info(path, shell) end end end diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index d7ab8a3..4f2aa7b 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -149,591 +149,597 @@ module Sunshine end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No status for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path, :sunshine_version => Sunshine::VERSION }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec self.root_path, 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's restart script. Raises an exception on failure. # Post-deploy only. def restart! # Permissions are handled by the script, use: :sudo => false run_script! :restart, :sudo => false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the root_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} run_script! name, options, &block rescue false end ## # Runs a script from the root_path. Raises an exception if the status # code is not 0. # Post-deploy only. def run_script! name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script! :status, :sudo => false true rescue CmdError => e return false if e.exit_code == Daemon::STATUS_DOWN_CODE raise e end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Run the app's start script. Raises an exception on failure. # Post-deploy only. def start! options=nil options ||= {} if running? return unless options[:force] stop! end # Permissions are handled by the script, use: :sudo => false run_script! :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's stop script. Raises an exception on failure. # Post-deploy only. def stop! # Permissions are handled by the script, use: :sudo => false run_script! :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} - RsyncRepo.new(code_dir).checkout_to self.checkout_path, @shell + excludes = scm_info.delete :exclude if scm_info[:exclude] + excludes = [excludes].flatten.compact + excludes.map!{|e| "--exclude #{e}"} + + repo = RsyncRepo.new code_dir, :flags => excludes + repo.checkout_to self.checkout_path, @shell + @info[:scm] = scm_info end ## # Upload common rake tasks from a local path or the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', ... # #=> upload app and common rake files # # File paths may also be used instead of the file's base name but # directory structures will not be followed: # app.upload_tasks 'lib/common/app.rake', 'lib/do_thing.rake' # # Allows options: # :local_path:: str - the path to get rake tasks from # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files[-1] ? files.delete_at(-1) : {} remote_path = options[:remote_path] || "#{self.checkout_path}/lib/tasks" local_path = options[:local_path] || "#{Sunshine::ROOT}/templates/tasks" @shell.call "mkdir -p #{remote_path}" files.map! do |file| if File.basename(file) == file File.join(local_path, "#{file}.rake") else file end end files = Dir.glob("#{Sunshine::ROOT}/templates/tasks/*") if files.empty? files.each do |file| remote_file = File.join remote_path, File.basename(file) @shell.upload file, remote_file end end ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end end end diff --git a/test/unit/test_app.rb b/test/unit/test_app.rb index 2330efc..a14e458 100644 --- a/test/unit/test_app.rb +++ b/test/unit/test_app.rb @@ -1,599 +1,642 @@ require 'test/test_helper' class TestApp < Test::Unit::TestCase def setup mock_remote_shell_popen4 @svn_url = "svn://subversion/path/to/app_name/trunk" @config = { :name => "app_name", :remote_checkout => true, :repo => {:type => "svn", :url => @svn_url}, :remote_shells => ["user@some_server.com", ["server2.com", {:roles => "web db"}]], :root_path => "/usr/local/my_user/app_name"} @app = Sunshine::App.new @config @app.each do |server_app| server_app.extend MockObject server_app.shell.extend MockObject end @tmpdir = File.join Dir.tmpdir, "test_sunshine_#{$$}" mock_svn_response @app.repo.url end def teardown + Sunshine.exclude_paths.clear FileUtils.rm_rf @tmpdir end def test_initialize_without_name app = Sunshine::App.new :repo => {:type => "svn", :url => @svn_url}, :remote_shells => ["user@some_server.com"] assert_equal "app_name", app.name end def test_initialize_with_config_file app = Sunshine::App.new TEST_APP_CONFIG_FILE config = YAML.load_file(TEST_APP_CONFIG_FILE)[:default] assert_attributes_equal config, app end def test_initialize_with_file_object file = File.open TEST_APP_CONFIG_FILE app = Sunshine::App.new file config = YAML.load_file(TEST_APP_CONFIG_FILE)[:default] assert_attributes_equal config, app end def test_initialize_with_options assert_attributes_equal @config, @app end def test_initialize_with_options_and_config_file app = Sunshine::App.new TEST_APP_CONFIG_FILE, @config assert_attributes_equal @config, app end def test_app_deploy yield_called = false @app.deploy do |app| assert app.connected? yield_called = true end assert [email protected]? setup_cmd = "test -d #{@app.checkout_path} && rm -rf #{@app.checkout_path}"+ " || echo false" mkdir_cmd = "mkdir -p #{@app.checkout_path}" checkout_cmd = "svn checkout " + "#{@app.repo.scm_flags} #{@app.repo.url} #{@app.checkout_path}" run_results = [ "mkdir -p #{@app.server_apps.first.directories.join(" ")}", setup_cmd, mkdir_cmd, checkout_cmd, "ln -sfT #{@app.checkout_path} #{@app.current_path}" ] @app.each do |server_app| use_remote_shell server_app.shell run_results.each_index do |i| assert_ssh_call run_results[i] end end assert yield_called end TEST_CONFIG = <<-STR :conf1: :common: "conf1" :from_conf1: true :not_conf4: "conf1" :conf2: :inherits: :conf1 :common: "conf2" :from_conf2: true :not_conf4: "conf2" :conf3: :common: "conf3" :from_conf3: true :not_conf4: "conf3" :conf4: :inherits: - :conf2 - :conf3 :common: "conf4" :from_conf4: true STR def test_merge_config_inheritance all_configs = YAML.load TEST_CONFIG main_conf = all_configs[:conf2] main_conf = @app.send(:merge_config_inheritance, main_conf, all_configs) assert main_conf[:from_conf1] assert_equal "conf2", main_conf[:common] end def test_multiple_merge_config_inheritance all_configs = YAML.load TEST_CONFIG main_conf = all_configs[:conf4] main_conf = @app.send(:merge_config_inheritance, main_conf, all_configs) assert main_conf[:from_conf1] assert main_conf[:from_conf2] assert main_conf[:from_conf3] assert_equal "conf4", main_conf[:common] assert_equal "conf3", main_conf[:not_conf4] end class MockError < Exception; end def test_app_deploy_error_handling [ MockError, Sunshine::DeployError ].each do |error| begin app = Sunshine::App.deploy @config do |app| raise error, "#{error} was not caught" end rescue MockError => e assert_equal MockError, e.class end end end def test_revert set_mock_response_for @app, 0, "ls -rc1 #{@app.deploys_path}" => [:out, "last_deploy_dir"] @app.revert! @app.each do |sa| use_remote_shell sa.shell assert_ssh_call "rm -rf #{@app.checkout_path}" assert_ssh_call "ls -rc1 #{@app.deploys_path}" last_deploy = "#{@app.deploys_path}/last_deploy_dir" assert_ssh_call "ln -sfT #{last_deploy} #{@app.current_path}" end end def test_build_control_scripts scripts_list = %w{start stop restart custom env} @app.server_apps.each do |sa| sa.shell.mock :file?, :return => false end @app.add_to_script :start, "start script" @app.add_to_script :stop, "stop script" @app.add_to_script :custom, "custom script" @app.build_control_scripts each_remote_shell do |ds| scripts_list.each do |script| assert_rsync(/#{script}/, "#{ds.host}:#{@app.scripts_path}/#{script}") end end end def test_build_deploy_info_file @app.build_deploy_info_file each_remote_shell do |ds| assert_rsync(/info/, "#{ds.host}:#{@app.scripts_path}/info") end end def test_build_erb erb_file = File.join(@tmpdir, "tmp.erb") FileUtils.mkdir_p @tmpdir File.open(erb_file, "w+") do |f| f.write "<%= name %>" end name = "test name" local_name = @app.build_erb(erb_file, binding) app_name = @app.build_erb(erb_file) assert_equal name, local_name assert_equal @app.name, app_name end def test_call calls = 0 @app.call "test call", :sudo => true do |type, data, inn| calls += 1 end assert_equal calls, @app.server_apps.length args = ["test call", {:sudo => true}] @app.each do |server_app| assert server_app.shell.method_called?(:call, :args => args) end end def test_checkout_codebase @app.checkout_codebase each_remote_shell do |ds| path = @app.checkout_path setup_cmd = "test -d #{path} && rm -rf #{path} || echo false" url = @app.repo.url flags = @app.repo.scm_flags checkout_cmd = "svn checkout #{flags} #{url} #{path}" assert_ssh_call setup_cmd assert_ssh_call checkout_cmd end end + def test_checkout_local_codebase + tmp_path = File.join Sunshine::TMP_DIR, "#{@app.name}_checkout" + @app.repo.extend MockObject + @app.repo.mock :checkout_to, :args => [tmp_path], + :return => {:test => "scm info"} + + @app.each do |sa| + sa.mock :upload_codebase + end + + @app.checkout_codebase :copy => true + + @app.each do |sa| + assert sa.method_called?(:upload_codebase, + :args => [tmp_path, {:test => "scm info", :exclude => []}]) + end + end + + + def test_checkout_local_codebase_with_exludes + Sunshine.exclude_paths.concat ["path1/", "path2/"] + + tmp_path = File.join Sunshine::TMP_DIR, "#{@app.name}_checkout" + @app.repo.extend MockObject + + @app.repo.mock :checkout_to, :args => [tmp_path], + :return => {:test => "scm info"} + + @app.each do |sa| + sa.mock :upload_codebase + end + + @app.checkout_codebase :copy => true, :exclude => ["path3/", "path4/"] + + @app.each do |sa| + assert sa.method_called?(:upload_codebase, + :args => [tmp_path, {:test => "scm info", + :exclude => ["path1/", "path2/", "path3/", "path4/"]}]) + end + end + + def test_deployed? set_mock_response_for @app, 0, "cat #{@app.root_path}/info" => [:out, "---\n:deploy_name: '#{@app.deploy_name}'"] deployed = @app.deployed? state = true @app.server_apps.each do |sa| assert sa.method_called?(:deployed?) set_mock_response_for sa.shell, 0, "cat #{@app.current_path}/info" => [:out, "---\n:deploy_name: '#{@app.deploy_name}'"] state = false unless sa.deployed? end assert_equal state, deployed assert deployed end def test_install_deps nginx_dep = Sunshine.dependencies.get 'nginx' ruby_dep = Sunshine.dependencies.get 'ruby' yum_sudo = Sunshine::Yum.sudo check_nginx = "test \"$(yum list installed #{nginx_dep.pkg} | "+ "grep -c #{nginx_dep.pkg})\" -ge 1" check_ruby = "test \"$(yum list installed #{ruby_dep.pkg} | "+ "grep -c #{ruby_dep.pkg})\" -ge 1" set_mock_response_for @app, 1, "apt-get --version" => [:err, ""] set_mock_response_for @app, 0, "yum --version" => [:out, "1.0"] set_mock_response_for @app, 1, {check_nginx => [:err, ""], check_ruby => [:err, ""]}, {:sudo => yum_sudo} @app.install_deps 'ruby', nginx_dep each_remote_shell do |ds| [nginx_dep, ruby_dep].each do |dep| check = "test \"$(yum list installed #{dep.pkg} | grep -c #{dep.pkg})\" -ge 1" install = dep.instance_variable_get "@install" assert_ssh_call check, ds, :sudo => yum_sudo assert_ssh_call install, ds, :sudo => yum_sudo end end end def test_install_gem_deps rake_dep = Sunshine.dependencies.get 'rake' bundler_dep = Sunshine.dependencies.get 'bundler' gem_sudo = Sunshine::Gem.sudo checks = { rake_dep => "gem list #{rake_dep.pkg} -i --version '>=0.8'", bundler_dep => "gem list #{bundler_dep.pkg} -i --version '>=0.9'" } checks.values.each do |check| set_mock_response_for @app, 1, {check => [:err, ""]}, {:sudo => gem_sudo} end @app.install_deps 'rake', bundler_dep each_remote_shell do |ds| [rake_dep, bundler_dep].each do |dep| install = dep.instance_variable_get "@install" assert_ssh_call checks[dep], ds, :sudo => gem_sudo assert_ssh_call install, ds, :sudo => gem_sudo end end end def test_find_all app = Sunshine::App.new :repo => {:type => "svn", :url => @svn_url}, :remote_shells => [ "user@some_server.com", ["server2.com", {:roles => "web db"}] ] server_apps = app.server_apps assert_equal server_apps, app.find assert_equal server_apps, app.find({}) assert_equal server_apps, app.find(:all) assert_equal server_apps, app.find(nil) end def test_find app = Sunshine::App.new :repo => {:type => "svn", :url => @svn_url}, :remote_shells => [ "user@some_server.com", ["server2.com", {:roles => "web db"}] ] server_apps = app.server_apps assert_equal server_apps, app.find(:role => :web) assert_equal server_apps, app.find(:role => :db) assert_equal [server_apps[0]], app.find(:role => :all) assert_equal [server_apps[0]], app.find(:role => :blarg) assert_equal [server_apps[0]], app.find(:user => 'user') assert_equal [server_apps[0]], app.find(:host => 'some_server.com') assert_equal [server_apps[1]], app.find(:host => 'server2.com') end def test_make_app_directories @app.make_app_directories each_remote_shell do |ds| assert_ssh_call "mkdir -p #{@app.server_apps.first.directories.join(" ")}" end end def test_rake @app.rake("test:task") each_remote_shell do |ds| assert_ssh_call "cd #{@app.checkout_path} && rake test:task" end end def test_register_as_deployed @app.register_as_deployed each_remote_shell do |ds| assert_ssh_call "test -d #{@app.root_path}" yml_list = {@app.name => @app.root_path}.to_yaml path = ds.expand_path(Sunshine::APP_LIST_PATH) assert ds.method_called?(:make_file, :args => [path, yml_list]) end end def test_remove_old_deploys returned_dirs = %w{old_deploy1 old_deploy2 old_deploy3 main_deploy} old_deploys = returned_dirs[0..-2].map{|d| "#{@app.deploys_path}/#{d}"} list_cmd = "ls -rc1 #{@app.deploys_path}" rm_cmd = "rm -rf #{old_deploys.join(" ")}" set_mock_response_for @app, 0, list_cmd => [:out, returned_dirs.join("\n")] Sunshine.setup 'max_deploy_versions' => 1 @app.remove_old_deploys each_remote_shell do |ds| assert_ssh_call list_cmd assert_ssh_call rm_cmd end end def test_run_post_user_lambdas lambdas_ran = 0 count = 5 count.times do @app.after_user_script do |app| lambdas_ran = lambdas_ran.next end end assert_equal 0, lambdas_ran @app.run_post_user_lambdas assert_equal count, lambdas_ran end def test_shell_env new_env = { "PATH" => "/etc/lib:$PATH", "RACK_ENV" => "test", "RAILS_ENV" => "test" } @app.shell_env new_env assert_equal new_env, @app.shell_env end def test_symlink_current_dir @app.symlink_current_dir each_remote_shell do |ds| assert_ssh_call "ln -sfT #{@app.checkout_path} #{@app.current_path}" end end def test_threaded_each_errors err_host = "some_server.com" finished = 0 @app.threaded_each do |server_app| if server_app.shell.host == err_host raise Sunshine::DeployError, server_app.shell.host else finished = finished.next end end raise "Didn't raise threaded error when it should have" rescue Sunshine::DeployError => e host = @app.server_apps.first.shell.host assert_equal host, e.message assert_equal (@app.server_apps.length - 1), finished end def test_upload_tasks path = "/path/to/tasks" @app.upload_tasks 'common', 'tpkg', :host => 'some_server.com', :remote_path => path shell = @app.find(:host => 'some_server.com').first.shell use_remote_shell shell assert_ssh_call "mkdir -p /path/to/tasks" %w{common tpkg}.each do |task| from = "#{Sunshine::ROOT}/templates/tasks/#{task}.rake" to = "#{shell.host}:#{path}/#{task}.rake" assert_rsync from, to end end def test_upload_tasks_simple @app.upload_tasks path = "#{@app.checkout_path}/lib/tasks" tasks = Dir.glob("#{Sunshine::ROOT}/templates/tasks/*").map{|t| File.basename t} each_remote_shell do |ds| assert_ssh_call "mkdir -p #{path}" tasks.each do |task| from = "#{Sunshine::ROOT}/templates/tasks/#{task}" to = "#{ds.host}:#{path}/#{task}" assert_rsync from, to end end end def test_with_filter app = Sunshine::App.new :repo => {:type => "svn", :url => @svn_url}, :remote_shells => ["[email protected]", "[email protected]"] assert_equal 2, app.server_apps.length app.with_filter :host => 'server1.com' do |app| assert_equal 1, app.server_apps.length assert_equal 'server1.com', app.server_apps.first.shell.host end assert_equal 2, app.server_apps.length end def test_sudo_assignment @app.sudo = "someuser" @app.each do |server_app| assert_equal "someuser", server_app.shell.sudo end end private def assert_attributes_equal(attr_hash, app) assert_equal attr_hash[:name], app.name assert_equal attr_hash[:repo][:url], app.repo.url assert_equal attr_hash[:root_path], app.root_path attr_hash[:remote_shells].each_with_index do |server_def, i| shell = Sunshine::RemoteShell.new(*server_def) assert_equal shell, app.server_apps[i].shell end end end diff --git a/test/unit/test_server_app.rb b/test/unit/test_server_app.rb index 9ea2627..2ac3a13 100644 --- a/test/unit/test_server_app.rb +++ b/test/unit/test_server_app.rb @@ -1,515 +1,559 @@ require 'test_helper' class TestServerApp < Test::Unit::TestCase def setup mock_svn_response @app = mock_app @app.repo.extend MockObject @sa = Sunshine::ServerApp.new @app, mock_remote_shell @sa.extend MockObject use_remote_shell @sa.shell end def test_from_info_file info_data = @sa.get_deploy_info.to_yaml @sa.shell.mock :call, :args => "cat info/path", :return => info_data server_app = Sunshine::ServerApp.from_info_file "info/path", @sa.shell assert_equal @sa.root_path, server_app.root_path assert_equal @sa.checkout_path, server_app.checkout_path assert_equal @sa.current_path, server_app.current_path assert_equal @sa.deploys_path, server_app.deploys_path assert_equal @sa.log_path, server_app.log_path assert_equal @sa.shared_path, server_app.shared_path assert_equal @sa.scripts_path, server_app.scripts_path assert_equal @sa.roles, server_app.roles assert_equal @sa.shell.env, server_app.shell_env assert_equal @sa.name, server_app.name assert_equal @sa.deploy_name, server_app.deploy_name end def test_init default_info = {:ports => {}} assert_equal default_info, @sa.info assert_equal @app, @sa.app assert_equal Hash.new, @sa.scripts assert_equal [:all], @sa.roles end def test_init_roles sa = Sunshine::ServerApp.new @app, "host", :roles => "role1 role2" assert_equal [:role1, :role2], sa.roles sa = Sunshine::ServerApp.new @app, "host", :roles => %w{role3 role4} assert_equal [:role3, :role4], sa.roles end def test_add_shell_paths @sa.add_shell_paths "test/path1", "test/path2" assert_equal "test/path1:test/path2:$PATH", @sa.shell_env['PATH'] @sa.add_shell_paths "test/path3", "test/path4" assert_equal "test/path3:test/path4:test/path1:test/path2:$PATH", @sa.shell_env['PATH'] end def test_app_attr sa_root_path = "local/server_app/path" sa_deploy_name = "local_deploy_name" @sa = Sunshine::ServerApp.new "test", "host", :root_path => sa_root_path, :deploy_name => sa_deploy_name assert_equal sa_root_path, @sa.root_path assert_equal sa_deploy_name, @sa.deploy_name assert_equal "test", @sa.name @sa.app = @app assert_not_equal sa_root_path, @sa.root_path assert_not_equal sa_deploy_name, @sa.deploy_name assert_not_equal "test", @sa.name assert_equal @app.root_path, @sa.root_path assert_equal @app.deploy_name, @sa.deploy_name assert_equal @app.name, @sa.name end def test_build_control_scripts @sa.scripts[:start] << "start" @sa.scripts[:stop] << "stop" @sa.scripts[:custom] << "custom" @sa.build_control_scripts [:start, :stop, :custom].each do |script| content = @sa.make_bash_script script, @sa.scripts[script] assert @sa.method_called?(:write_script, :args => [script, content]) end content = @sa.make_env_bash_script assert @sa.method_called?(:write_script, :args => ["env", content]) content = @sa.make_bash_script :restart, ["#{@sa.app.root_path}/stop", "#{@sa.app.root_path}/start"] assert @sa.method_called?(:write_script, :args => [:restart, content]) end def test_build_deploy_info_file @sa.shell.mock :file?, :return => false args = ["#{@app.scripts_path}/info", @sa.get_deploy_info.to_yaml] @sa.build_deploy_info_file assert @sa.shell.method_called?(:make_file, :args => args) args = ["#{@app.scripts_path}/info", "#{@app.root_path}/info"] assert @sa.shell.method_called?(:symlink, :args => args) end def test_checkout_repo @sa.checkout_repo @app.repo repo = @sa.app.repo args = [@app.checkout_path, @sa.shell] assert repo.method_called?(:checkout_to, :args => args) info = @app.repo.checkout_to @app.checkout_path, @sa.shell assert_equal info, @sa.info[:scm] end def test_deploy_details deploy_details = {:item => "thing"} other_details = {:key => "value"} @sa.shell.mock :call, :args => ["cat #{@sa.root_path}/info"], :return => other_details.to_yaml @sa.instance_variable_set "@deploy_details", deploy_details assert_equal deploy_details, @sa.deploy_details assert_equal other_details, @sa.deploy_details(true) end def test_not_deployed? @sa.mock :deploy_details, :args => [true], :return => nil assert_equal false, @sa.deployed? end def test_server_checked_deployed? @sa.mock :deploy_details, :args => [true], :return => {:deploy_name => @sa.deploy_name} assert_equal true, @sa.deployed? end def test_cached_details_deployed? @sa.instance_variable_set "@deploy_details", :deploy_name => @sa.deploy_name assert_equal true, @sa.deployed? end def test_get_deploy_info test_info = { :deployed_at => Time.now.to_s, :deployed_as => @sa.shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(@app.checkout_path), :name => @sa.name, :env => @sa.shell_env, :roles => @sa.roles, :path => @app.root_path, :sunshine_version => Sunshine::VERSION }.merge @sa.info deploy_info = @sa.get_deploy_info deploy_info.each do |key, val| next if key == :deployed_at assert_equal test_info[key], val end end def test_has_all_roles assert @sa.has_roles?([:web, :app, :blarg]) assert @sa.has_roles?([:web, :app, :blarg], true) end def test_has_roles @sa.roles = [:web, :app] assert @sa.has_roles?(:web) assert @sa.has_roles?([:web, :app]) assert [email protected]_roles?([:blarg, :web, :app]) assert @sa.has_roles?([:blarg, :web, :app], true) end def test_install_deps nginx_dep = Sunshine.dependencies.get 'nginx', :prefer => @sa.pkg_manager @sa.install_deps "ruby", nginx_dep assert_dep_install 'ruby', Sunshine::Yum assert_dep_install 'nginx', Sunshine::Yum end def test_install_deps_bad_type nginx_dep = Sunshine.dependencies.get 'nginx' @sa.install_deps nginx_dep, :type => Sunshine::Gem raise "Didn't raise missing dependency when it should have." rescue Sunshine::MissingDependency => e assert_equal "No dependency 'nginx' [Sunshine::Gem]", e.message end def test_make_app_directories @sa.make_app_directories assert_server_call "mkdir -p #{@sa.directories.join(" ")}" end def test_make_bash_script app_script = @sa.make_bash_script "blah", [1,2,3,4] assert_bash_script "blah", [1,2,3,4], app_script end def test_make_env_bash_script @sa.shell.env = {"BLAH" => "blarg", "HOME" => "/home/blah"} test_script = "#!/bin/bash\nenv BLAH=blarg HOME=/home/blah \"$@\"" assert_equal test_script, @sa.make_env_bash_script end def test_rake @sa.rake "db:migrate" assert_dep_install 'rake', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && rake db:migrate" end def test_register_as_deployed Sunshine::AddCommand.extend MockObject unless MockObject === Sunshine::AddCommand @sa.register_as_deployed args = [@app.root_path, {'servers' => [@sa.shell]}] assert Sunshine::AddCommand.method_called?(:exec, :args => args) end def test_remove_old_deploys Sunshine.setup 'max_deploy_versions' => 3 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_server_call "rm -rf #{removed.join(" ")}" end def test_remove_old_deploys_unnecessary Sunshine.setup 'max_deploy_versions' => 5 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.mock :call, :args => ["ls -1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_not_called "rm -rf #{removed.join(" ")}" end def test_revert! deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" last_deploy = "#{@app.deploys_path}/ploy5" assert_server_call "ln -sfT #{last_deploy} #{@app.current_path}" end def test_no_previous_revert! @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" end def test_run_bundler @sa.run_bundler assert_dep_install 'bundler', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && gem bundle" end def test_run_geminstaller @sa.run_geminstaller assert_dep_install 'geminstaller', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && geminstaller -e" end def test_running? set_mock_response_for @sa, 0, "#{@sa.root_path}/status" => [:out, "THE SYSTEM OK!"] assert_equal true, @sa.running? end def test_not_running? set_mock_response_for @sa, 13, "#{@sa.root_path}/status" => [:err, "THE SYSTEM IS DOWN!"] assert_equal false, @sa.running? end def test_errored_running? set_mock_response_for @sa, 1, "#{@sa.root_path}/status" => [:err, "KABLAM!"] assert_raises Sunshine::CmdError do @sa.running? end end def test_sass sass_files = %w{file1 file2 file3} @sa.sass(*sass_files) assert_dep_install 'haml', @sa.pkg_manager sass_files.each do |file| sass_file = "public/stylesheets/sass/#{file}.sass" css_file = "public/stylesheets/#{file}.css" assert_server_call \ "cd #{@app.checkout_path} && sass #{sass_file} #{css_file}" end end def test_shell_env assert_equal @sa.shell.env, @sa.shell_env end def test_symlink_current_dir @sa.symlink_current_dir assert_server_call "ln -sfT #{@app.checkout_path} #{@app.current_path}" end def test_upload_tasks files = %w{task1 task2} @sa.upload_tasks(*files) assert_server_call "mkdir -p #{@app.checkout_path}/lib/tasks" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{@app.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_with_remote_path files = %w{task1 task2} path = "/path/to/remote/tasks" @sa.upload_tasks files[0], files[1], :remote_path => path assert_server_call "mkdir -p #{path}" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{path}/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_with_local_path files = %w{task1 task2} path = "/path/to/local/tasks" args = files.dup << {:local_path => path} @sa.upload_tasks(*args) assert_server_call "mkdir -p #{@sa.checkout_path}/lib/tasks" files.each do |f| args = ["#{path}/#{f}.rake", "#{@sa.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_all files = Dir.glob("templates/tasks/*").map{|f| File.basename(f, ".rake")} @sa.upload_tasks assert_server_call "mkdir -p #{@app.checkout_path}/lib/tasks" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{@app.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end + def test_upload_codebase + @sa.shell.mock(:upload) + + @sa.upload_codebase "tmp/thing/", :test_scm => "info" + assert_equal({:test_scm => "info"} , @sa.info[:scm]) + assert @sa.shell.method_called?( + :upload, :args => ["tmp/thing/", @sa.checkout_path, + {:flags => ["--exclude .svn/","--exclude .git/"]}]) + end + + + def test_upload_codebase_with_exclude + @sa.shell.mock(:upload) + + @sa.upload_codebase "tmp/thing/", + :test_scm => "info", + :exclude => "bad/path/" + + assert_equal({:test_scm => "info"} , @sa.info[:scm]) + assert @sa.shell.method_called?( + :upload, :args => ["tmp/thing/", @sa.checkout_path, + {:flags => ["--exclude bad/path/", + "--exclude .svn/", + "--exclude .git/"]}]) + end + + + def test_upload_codebase_with_excludes + @sa.shell.mock(:upload) + + @sa.upload_codebase "tmp/thing/", + :test_scm => "info", + :exclude => ["bad/path/", "other/exclude/"] + + assert_equal({:test_scm => "info"} , @sa.info[:scm]) + assert @sa.shell.method_called?( + :upload, :args => ["tmp/thing/", @sa.checkout_path, + {:flags => ["--exclude bad/path/", + "--exclude other/exclude/", + "--exclude .svn/", + "--exclude .git/"]}]) + end + + def test_write_script @sa.shell.mock :file?, :return => false @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert @sa.shell.method_called?(:make_file, :args => args) end def test_symlink_scripts_to_root @sa.shell.mock :call, :args => ["ls -1 #{@sa.scripts_path}"], :return => "script_name\n" args = ["#{@app.scripts_path}/script_name", "#{@app.root_path}/script_name"] @sa.symlink_scripts_to_root assert @sa.shell.method_called?(:symlink, :args => args) end def test_write_script_existing @sa.shell.mock :file?, :return => true @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert [email protected]_called?(:make_file, :args => args) end end
jcasts/sunshine
52b10c87571fe72db334cb2117c9b4ec428d5ae5
added auto-recurse to remote shell rsyncing
diff --git a/lib/sunshine/remote_shell.rb b/lib/sunshine/remote_shell.rb index 0efebd2..cc8536d 100644 --- a/lib/sunshine/remote_shell.rb +++ b/lib/sunshine/remote_shell.rb @@ -1,272 +1,272 @@ module Sunshine ## # Keeps an SSH connection open to a server the app will be deployed to. # Deploy servers use the ssh command and support any ssh feature. # By default, deploy servers use the ControlMaster feature to share # socket connections, with the ControlPath = ~/.ssh/sunshine-%r%h:%p # # Setting session-persistant environment variables is supported by # accessing the @env attribute. class RemoteShell < Shell ## # The loop to keep the ssh connection open. LOGIN_LOOP = "echo ok; echo ready; "+ "for (( ; ; )); do kill -0 $PPID && sleep 10 || exit; done;" LOGIN_TIMEOUT = 30 ## # Closes all remote shell connections. def self.disconnect_all return unless defined?(@remote_shells) @remote_shells.each{|rs| rs.disconnect} end ## # Registers a remote shell for global access from the class. # Handled automatically on initialization. def self.register remote_shell (@remote_shells ||= []) << remote_shell end attr_reader :host, :user, :pid attr_accessor :ssh_flags, :rsync_flags ## # Remote shells essentially need a host and optional user. # Typical instantiation is done through either of these methods: # RemoteShell.new "user@host" # RemoteShell.new "host", :user => "user" # # The constructor also supports the following options: # :env:: hash - hash of environment variables to set for the ssh session # :password:: string - password for ssh login; if missing the deploy server # will attempt to prompt the user for a password. def initialize host, options={} super $stdout, options @host, @user = host.split("@").reverse @user ||= options[:user] - @rsync_flags = ["-azP"] + @rsync_flags = ["-azrP"] @rsync_flags.concat [*options[:rsync_flags]] if options[:rsync_flags] @ssh_flags = [ "-o ControlMaster=auto", "-o ControlPath=~/.ssh/sunshine-%r@%h:%p" ] @ssh_flags.concat ["-l", @user] if @user @ssh_flags.concat [*options[:ssh_flags]] if options[:ssh_flags] @pid, @inn, @out, @err = nil self.class.register self end ## # Runs a command via SSH. Optional block is passed the # stream(stderr, stdout) and string data. def call command_str, options={}, &block Sunshine.logger.info @host, "Running: #{command_str}" do execute build_remote_cmd(command_str, options), &block end end ## # Connect to host via SSH and return process pid def connect return true if connected? cmd = ssh_cmd quote_cmd(LOGIN_LOOP), :sudo => false @pid, @inn, @out, @err = popen4 cmd.join(" ") @inn.sync = true data = "" ready = nil start_time = Time.now.to_i until ready || @out.eof? data << @out.readpartial(1024) ready = data =~ /ready/ raise TimeoutError if timed_out?(start_time, LOGIN_TIMEOUT) end unless connected? disconnect host_info = [@user, @host].compact.join("@") raise ConnectionError, "Can't connect to #{host_info}" end @inn.close @pid end ## # Check if SSH session is open and returns process pid def connected? Process.kill(0, @pid) && @pid rescue false end ## # Disconnect from host def disconnect @inn.close rescue nil @out.close rescue nil @err.close rescue nil kill_process @pid, "HUP" rescue nil @pid = nil end ## # Download a file via rsync def download from_path, to_path, options={}, &block from_path = "#{@host}:#{from_path}" Sunshine.logger.info @host, "Downloading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Expand a path: # shell.expand_path "~user/thing" # #=> "/home/user/thing" def expand_path path dir = File.dirname path full_dir = call "cd #{dir} && pwd" File.join full_dir, File.basename(path) end ## # Checks if the given file exists def file? filepath syscall "test -f #{filepath}" end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " cmd = quote_cmd cmd pid = fork do exec \ ssh_cmd(sudo_cmd(env_cmd(cmd)), :flags => "-t").to_a.join(" ") end Process.waitpid pid end end ## # Create a file remotely def make_file filepath, content, options={} temp_filepath = "#{TMP_DIR}/#{File.basename(filepath)}_#{Time.now.to_i}#{rand(10000)}" File.open(temp_filepath, "w+"){|f| f.write(content)} self.upload temp_filepath, filepath, options File.delete(temp_filepath) end ## # Builds an ssh command with permissions, env, etc. def build_remote_cmd cmd, options={} cmd = sh_cmd cmd cmd = env_cmd cmd cmd = sudo_cmd cmd, options cmd = ssh_cmd cmd, options end ## - # Uploads a file via rsync + # Uploads a file via rsync. def upload from_path, to_path, options={}, &block to_path = "#{@host}:#{to_path}" Sunshine.logger.info @host, "Uploading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Figure out which rsync flags to use. def build_rsync_flags options flags = @rsync_flags.dup remote_rsync = 'rsync' rsync_sudo = sudo_cmd remote_rsync, options unless rsync_sudo == remote_rsync flags << "--rsync-path='#{ rsync_sudo.join(" ") }'" end flags << "-e \"ssh #{@ssh_flags.join(' ')}\"" if @ssh_flags flags.concat [*options[:flags]] if options[:flags] flags end ## # Creates an rsync command. def rsync_cmd from_path, to_path, options={} cmd = ["rsync", build_rsync_flags(options), from_path, to_path] cmd.flatten.compact.join(" ") end ## # Wraps the command in an ssh call. def ssh_cmd cmd, options=nil options ||= {} flags = [*options[:flags]].concat @ssh_flags ["ssh", flags, @host, cmd].flatten.compact end end end diff --git a/lib/sunshine/repos/rsync_repo.rb b/lib/sunshine/repos/rsync_repo.rb index 300d130..8889a99 100644 --- a/lib/sunshine/repos/rsync_repo.rb +++ b/lib/sunshine/repos/rsync_repo.rb @@ -1,30 +1,30 @@ module Sunshine ## # Allows uploading code directly using rsync, instead of a scm. class RsyncRepo < Repo def self.get_info path=".", shell=nil {} end def initialize url, options={} super - @flags << '-r' << '--exclude .svn/' << '--exclude .git/' + @flags << '--exclude .svn/' << '--exclude .git/' @url << "/" unless @url[-1..-1] == "/" end def do_checkout path, shell shell.upload @url, path, :flags => @flags end def name File.basename @url end end end diff --git a/test/helper_methods.rb b/test/helper_methods.rb index 3aa29aa..1fe6d82 100644 --- a/test/helper_methods.rb +++ b/test/helper_methods.rb @@ -1,160 +1,160 @@ module HelperMethods def mock_app Sunshine::App.new(TEST_APP_CONFIG_FILE).extend MockObject end def mock_remote_shell host=nil host ||= "user@some_server.com" remote_shell = Sunshine::RemoteShell.new host remote_shell.extend MockOpen4 remote_shell.extend MockObject use_remote_shell remote_shell remote_shell.connect remote_shell end def mock_svn_response url=nil url ||= "svn://subversion/path/to/my_app/trunk" svn_response = <<-STR <?xml version="1.0"?> <log> <logentry revision="777"> <author>user</author> <date>2010-01-26T01:49:17.372152Z</date> <msg>finished testing server.rb</msg> </logentry> </log> STR Sunshine::SvnRepo.extend(MockObject) unless Sunshine::SvnRepo.is_a?(MockObject) Sunshine::SvnRepo.mock :svn_log, :return => svn_response Sunshine::SvnRepo.mock :get_svn_url, :return => url end def mock_remote_shell_popen4 Sunshine::RemoteShell.class_eval{ include MockOpen4 } end def set_mock_response_for obj, code, stream_vals={}, options={} case obj when Sunshine::App then obj.each do |sa| sa.shell.set_mock_response code, stream_vals, options end when Sunshine::ServerApp then obj.shell.set_mock_response code, stream_vals, options when Sunshine::RemoteShell then obj.set_mock_response code, stream_vals, options end end def assert_dep_install dep_name, prefered=nil args = [{:call => @remote_shell, :prefer => prefered}] dep = if Sunshine::Dependency === dep_name dep_name else Sunshine.dependencies.get(dep_name, :prefer => prefered) end assert dep.method_called?(:install!, :args => args), "Dependency '#{dep_name}' install was not called." end def assert_not_called *args assert !@remote_shell.method_called?(:call, :args => [*args]), "Command called by #{@remote_shell.host} but should't have:\n #{args[0]}" end def assert_server_call *args assert @remote_shell.method_called?(:call, :args => [*args]), "Command was not called by #{@remote_shell.host}:\n #{args[0]}" end def assert_bash_script name, cmds, check_value cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{@app.root_path}/env #{@app.root_path}/#{name} --no-env fi STR assert_equal bash, check_value end def assert_ssh_call expected, ds=@remote_shell, options={} expected = ds.build_remote_cmd(expected, options).join(" ") error_msg = "No such command in remote_shell log [#{ds.host}]\n#{expected}" error_msg << "\n\n#{ds.cmd_log.select{|c| c =~ /^ssh/}.join("\n\n")}" assert ds.cmd_log.include?(expected), error_msg end def assert_rsync from, to, ds=@remote_shell, sudo=false received = ds.cmd_log.last rsync_path = if sudo path = ds.sudo_cmd('rsync', sudo).join(' ') "--rsync-path='#{ path }' " end - rsync_cmd = "rsync -azP #{rsync_path}-e \"ssh #{ds.ssh_flags.join(' ')}\"" + rsync_cmd = "rsync -azrP #{rsync_path}-e \"ssh #{ds.ssh_flags.join(' ')}\"" error_msg = "No such command in remote_shell log [#{ds.host}]\n#{rsync_cmd}" error_msg << "#{from.inspect} #{to.inspect}" error_msg << "\n\n#{ds.cmd_log.select{|c| c =~ /^rsync/}.join("\n\n")}" if Regexp === from found = ds.cmd_log.select do |cmd| cmd_from = cmd.split(" ")[-2] cmd_to = cmd.split(" ").last cmd_from =~ from && cmd_to == to && cmd.index(rsync_cmd) == 0 end assert !found.empty?, error_msg else expected = "#{rsync_cmd} #{from} #{to}" assert ds.cmd_log.include?(expected), error_msg end end def use_remote_shell remote_shell @remote_shell = remote_shell end def each_remote_shell app=@app app.server_apps.each do |sa| use_remote_shell sa.shell yield(sa.shell) if block_given? end end end
jcasts/sunshine
1964b1678a465f2cb0b5606a6e9f3b26edafbce3
changed ServerApp#running? to only return on exit codes 0 and 13
diff --git a/lib/sunshine/daemon.rb b/lib/sunshine/daemon.rb index 25d0a27..3e28921 100644 --- a/lib/sunshine/daemon.rb +++ b/lib/sunshine/daemon.rb @@ -1,490 +1,490 @@ module Sunshine ## # An abstract class to wrap simple daemon software setup and start/stop. # # Child classes are expected to at least provide a start and stop bash script # by either overloading the start_cmd and stop_cmd methods, or by setting # @start_cmd and @stop_cmd. A restart_cmd method or @restart_cmd attribute # may also be specified if restart requires more functionality than simply # calling start_cmd && stop_cmd. class Daemon START_FAILED_CODE = 10 STOP_FAILED_CODE = 11 RESTART_FAILED_CODE = 12 - STATUS_FAILED_CODE = 13 + STATUS_DOWN_CODE = 13 ## # Returns an array of method names to assign to the binder # for template rendering. def self.binder_methods [:app, :name, :bin, :pid, :processes, :config_path, :log_file, :timeout] end ## # Returns the short, snake-case version of the class: # Sunshine::Daemon.short_name # #=> "daemon" def self.short_name @short_name ||= self.underscore self.to_s.split("::").last end ## # Turn camelcase into underscore. Used for Daemon#name. def self.underscore str str.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2').downcase end attr_reader :app, :name attr_accessor :bin, :pid, :processes, :timeout, :sudo, :server_apps attr_accessor :config_template, :config_path, :config_file attr_writer :start_cmd, :stop_cmd, :restart_cmd, :status_cmd # Daemon objects need only an App object to be instantiated but many options # are available for customization: # # :bin:: bin_path - Set the daemon app bin path (e.g. usr/local/nginx) # defaults to svr_name. # # :processes:: prcss_num - Number of processes daemon should run; # defaults to 1. # # :config_file:: name - Remote file name the daemon should load; # defaults to svr_name.conf # # :config_path:: path - Remote path daemon configs will be uploaded to; # defaults to app.current_path/daemons/svr_name # # :config_template:: path - Glob path to tempates to render and upload; # defaults to sunshine_path/templates/svr_name/* # # :log_path:: path - Path to where the log files should be output; # defaults to app.log_path. # # :pid:: pid_path - Set the pid; default: app.shared_path/pids/svr_name.pid # defaults to app.shared_path/pids/svr_name.pid. # # :sudo:: bool|str - Define if sudo should be used to run the daemon, # and/or with what user. # # :timeout:: int - Timeout to use for daemon config, defaults to 0. # # The Daemon constructor also supports any App#find options to narrow # the server apps to use. Note: subclasses such as Server already have # a default :role that can be overridden. def initialize app, options={} @options = options @app = app @name = options[:name] || self.class.short_name @pid = options[:pid] || "#{@app.shared_path}/pids/#{@name}.pid" @bin = options[:bin] || self.class.short_name @sudo = options[:sudo] @timeout = options[:timeout] || 0 @dep_name = options[:dep_name] || self.class.short_name @processes = options[:processes] || 1 @sigkill = 'QUIT' @config_template = options[:config_template] || "#{Sunshine::ROOT}/templates/#{self.class.short_name}/*" @config_path = options[:config_path] || "#{@app.current_path}/daemons/#{@name}" @config_file = options[:config_file] || "#{self.class.short_name}.conf" log_path = options[:log_path] || @app.log_path @log_files = { :stderr => "#{log_path}/#{@name}_stderr.log", :stdout => "#{log_path}/#{@name}_stdout.log" } @start_cmd = @stop_cmd = @restart_cmd = @status_cmd = nil @setup_successful = nil register_after_user_script end ## # Do something with each server app used by the daemon. def each_server_app(&block) @app.each(@options, &block) end ## # Setup the daemon, parse and upload config templates. # If a dependency with the daemon name exists in Sunshine.dependencies, # setup will attempt to install the dependency before uploading configs. # If a block is given it will be passed each server_app and binder object # which will be used for the building erb config templates. # See the ConfigBinding class for more information. def setup Sunshine.logger.info @name, "Setting up #{@name} daemon" do each_server_app do |server_app| # Build erb binding binder = config_binding server_app.shell configure_remote_dirs server_app.shell touch_log_files server_app.shell yield(server_app, binder) if block_given? server_app.install_deps @dep_name if Sunshine.dependencies.exist?(@dep_name) upload_config_files(server_app.shell, binder.get_binding) end end @setup_successful = true rescue => e raise DaemonError.new(e, "Could not setup #{@name}") end ## # Check if setup was run successfully. def has_setup? force=false return @setup_successful unless @setup_successful.nil? || force each_server_app do |server_app| unless server_app.shell.file? config_file_path return @setup_successful = false end end @setup_successful = true end ## # Start the daemon app after running setup. def start self.setup unless has_setup? Sunshine.logger.info @name, "Starting #{@name} daemon" do each_server_app do |server_app| begin server_app.shell.call _start_cmd, :sudo => pick_sudo(server_app.shell) yield(server_app) if block_given? rescue => e raise DaemonError.new(e, "Could not start #{@name}") end end end end ## # Check if the daemon is running on all servers def status each_server_app do |server_app| server_app.shell.call _status_cmd, :sudo => pick_sudo(server_app.shell) end true rescue CmdError => e false end ## # Stop the daemon app. def stop Sunshine.logger.info @name, "Stopping #{@name} daemon" do each_server_app do |server_app| begin server_app.shell.call _stop_cmd, :sudo => pick_sudo(server_app.shell) yield(server_app) if block_given? rescue => e raise DaemonError.new(e, "Could not stop #{@name}") end end end end ## # Restarts the daemon using the restart_cmd attribute if provided. # If restart_cmd is not provided, calls stop and start. def restart self.setup unless has_setup? Sunshine.logger.info @name, "Restarting #{@name} daemon" do each_server_app do |server_app| begin server_app.shell.call _restart_cmd, :sudo => pick_sudo(server_app.shell) yield(server_app) if block_given? rescue => e raise DaemonError.new(e, "Could not restart #{@name}") end end end end ## # Wrap a command with a fail-specific exitcode and message. def exit_on_failure cmd, exitcode=1, message=nil "(#{cmd}) || (echo '#{message}' && exit #{exitcode});" end ## # Gets the command that starts the daemon. # Should be overridden by child classes. def start_cmd return @start_cmd if @start_cmd raise DaemonError, "start_cmd undefined for #{@name}" end ## # Start command wrapped with an exit_on_failure handler. def _start_cmd exit_on_failure start_cmd, START_FAILED_CODE, "Could not start #{@name} for #{@app.name}" end ## # Default daemon stop command. def stop_cmd "test -f #{@pid} && kill -#{@sigkill} $(cat #{@pid}) && sleep 1 && "+ "rm -f #{@pid}" end ## # Stop command wrapped with an exit_on_failure handler. def _stop_cmd exit_on_failure stop_cmd, STOP_FAILED_CODE, "Could not kill #{@name} pid for #{@app.name}" end ## # Gets the command that restarts the daemon. # Should be overridden by child classes if different # from start_cmd && stop_cmd. def restart_cmd @restart_cmd end ## # Restart command wrapped with an exit_on_failure handler. def _restart_cmd if restart_cmd exit_on_failure restart_cmd, RESTART_FAILED_CODE, "Could not restart #{@name} for #{@app.name}" else "(#{_stop_cmd}) && (#{_start_cmd});" end end ## # Status command wrapped with an exit_on_failure handler. def status_cmd @status_cmd || "test -f #{@pid} && kill -0 $(cat #{@pid})" end ## # Get the command to check if the daemon is running. def _status_cmd - exit_on_failure status_cmd, STATUS_FAILED_CODE, + exit_on_failure status_cmd, STATUS_DOWN_CODE, "#{@app.name} #{@name} is not running" end ## # Append or override daemon log file paths: # daemon.log_files :stderr => "/all_logs/stderr.log" def log_files hash @log_files.merge!(hash) end ## # Get the path of a log file: # daemon.log_file(:stderr) # #=> "/all_logs/stderr.log" def log_file key @log_files[key] end ## # Get the file path to the daemon's config file. def config_file_path "#{@config_path}/#{@config_file}" end ## # Upload config files and run them through erb with the provided # binding if necessary. def upload_config_files shell, setup_binding=binding config_template_files.each do |config_file| if File.extname(config_file) == ".erb" filename = File.basename(config_file[0..-5]) parsed_config = @app.build_erb(config_file, setup_binding) shell.make_file "#{@config_path}/#{filename}", parsed_config else filename = File.basename(config_file) shell.upload config_file, "#{@config_path}/#{filename}" end end end ## # Get the array of local config template files needed by the daemon. def config_template_files @config_template_files ||= Dir[@config_template].select{|f| File.file?(f)} end ## # Create and setup a binding for a given shell. def config_binding shell binder = Binder.new self binder.forward(*self.class.binder_methods) binder.set :shell, shell binder_sudo = pick_sudo(shell) binder.set :sudo, binder_sudo binder.set :expand_path do |path| shell.expand_path path end binder end ## # Pick which sudo to use between the daemon sudo and shell sudo. # (Useful when running servers on ports < 1024) def pick_sudo shell self.sudo.nil? ? shell.sudo : self.sudo end ## # Make sure all the remote directories needed by the daemon exist. def configure_remote_dirs shell dirs = @log_files.values.map{|f| File.dirname(f)} dirs << File.dirname(@pid) dirs << @config_path dirs.delete_if{|d| d == "."} dirs = dirs.join(" ") shell.call "mkdir -p #{dirs}" end ## # Make sure log files are owned by the daemon's user. def touch_log_files shell files = @log_files.values.join(" ") sudo = pick_sudo(shell) user = case sudo when true then 'root' when String then sudo else nil end shell.call "touch #{files}", :sudo => true shell.call "chown #{user} #{files}", :sudo => true if user end ## # Setup what should be run after the user block on App#deploy. def register_after_user_script @app.after_user_script do |app| next unless has_setup? each_server_app do |sa| sudo = pick_sudo sa.shell %w{start stop restart status}.each do |script| script_file = "#{@config_path}/#{script}" cmd = send "_#{script}_cmd" sa.shell.make_file script_file, cmd, :flags => '--chmod=ugo=rwx' cmd = sa.shell.sudo_cmd "#{@app.root_path}/env #{script_file}", sudo sa.scripts[script.to_sym] << [*cmd].join(" ") end end end end end end diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index 5a927dd..d7ab8a3 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -25,710 +25,715 @@ module Sunshine # Explicitely assign the app's root path: # ServerApp.new "app_name", ..., :root_path => "/path/to/app_root" # # Assigning a specific deploy name to use can be done with the # :deploy_name option: # ServerApp.new "app_name", ..., :deploy_name => "deploy" class ServerApp ## # Define an attribute that will get a value from app, or locally if # @app isn't set. def self.app_attr *attribs attribs.each do |attrib| class_eval <<-STR, __FILE__, __LINE__ + 1 def #{attrib} @app ? @app.send(:#{attrib}) : @#{attrib} end STR end end ## # Creates dependency instance methods such as gem_install, yum_install, etc # on both App and ServerApp classes. def self.register_dependency_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = Hash === names.last ? names.delete_at(-1) : Hash.new names.each do |name| dep = #{dep_class}.new(name, options) dep.install! :call => @shell end end STR App.class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = names.last if Hash === names.last with_server_apps options, :msg => "Installing #{dep_class.short_name} packages", :send => [:#{dep_class.short_name}_install, *names] end STR end ## # Creates a ServerApp instance from a deploy info file. def self.from_info_file path, shell=nil shell ||= Sunshine.shell opts = YAML.load shell.call("cat #{path}") opts[:root_path] = opts.delete :path sa_shell = shell.dup sa_shell.env = opts[:env] || Hash.new sa_shell.connect if shell.connected? new opts[:name], sa_shell, opts end app_attr :name, :deploy_name app_attr :root_path, :checkout_path, :current_path app_attr :deploys_path, :log_path, :shared_path, :scripts_path attr_accessor :app, :roles, :scripts, :info, :shell, :crontab, :health attr_writer :pkg_manager ## # Create a server app instance. Supports the following # argument configurations: # # ServerApp.new app_inst, "myserver.com", :roles => :web # ServerApp.new "app_name", shell_inst, options_hash def initialize app, host, options={} @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell @health = Healthcheck.new shared_path, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No status for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path, :sunshine_version => Sunshine::VERSION }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec self.root_path, 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's restart script. Raises an exception on failure. # Post-deploy only. def restart! # Permissions are handled by the script, use: :sudo => false run_script! :restart, :sudo => false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the root_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} run_script! name, options, &block rescue false end ## # Runs a script from the root_path. Raises an exception if the status # code is not 0. # Post-deploy only. def run_script! name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false - run_script :status, :sudo => false + run_script! :status, :sudo => false + true + + rescue CmdError => e + return false if e.exit_code == Daemon::STATUS_DOWN_CODE + raise e end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Run the app's start script. Raises an exception on failure. # Post-deploy only. def start! options=nil options ||= {} if running? return unless options[:force] stop! end # Permissions are handled by the script, use: :sudo => false run_script! :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's stop script. Raises an exception on failure. # Post-deploy only. def stop! # Permissions are handled by the script, use: :sudo => false run_script! :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} RsyncRepo.new(code_dir).checkout_to self.checkout_path, @shell @info[:scm] = scm_info end ## # Upload common rake tasks from a local path or the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', ... # #=> upload app and common rake files # # File paths may also be used instead of the file's base name but # directory structures will not be followed: # app.upload_tasks 'lib/common/app.rake', 'lib/do_thing.rake' # # Allows options: # :local_path:: str - the path to get rake tasks from # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files[-1] ? files.delete_at(-1) : {} remote_path = options[:remote_path] || "#{self.checkout_path}/lib/tasks" local_path = options[:local_path] || "#{Sunshine::ROOT}/templates/tasks" @shell.call "mkdir -p #{remote_path}" files.map! do |file| if File.basename(file) == file File.join(local_path, "#{file}.rake") else file end end files = Dir.glob("#{Sunshine::ROOT}/templates/tasks/*") if files.empty? files.each do |file| remote_file = File.join remote_path, File.basename(file) @shell.upload file, remote_file end end ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end end end diff --git a/test/unit/test_server_app.rb b/test/unit/test_server_app.rb index 03eeff0..9ea2627 100644 --- a/test/unit/test_server_app.rb +++ b/test/unit/test_server_app.rb @@ -1,489 +1,515 @@ require 'test_helper' class TestServerApp < Test::Unit::TestCase def setup mock_svn_response @app = mock_app @app.repo.extend MockObject @sa = Sunshine::ServerApp.new @app, mock_remote_shell @sa.extend MockObject use_remote_shell @sa.shell end def test_from_info_file info_data = @sa.get_deploy_info.to_yaml @sa.shell.mock :call, :args => "cat info/path", :return => info_data server_app = Sunshine::ServerApp.from_info_file "info/path", @sa.shell assert_equal @sa.root_path, server_app.root_path assert_equal @sa.checkout_path, server_app.checkout_path assert_equal @sa.current_path, server_app.current_path assert_equal @sa.deploys_path, server_app.deploys_path assert_equal @sa.log_path, server_app.log_path assert_equal @sa.shared_path, server_app.shared_path assert_equal @sa.scripts_path, server_app.scripts_path assert_equal @sa.roles, server_app.roles assert_equal @sa.shell.env, server_app.shell_env assert_equal @sa.name, server_app.name assert_equal @sa.deploy_name, server_app.deploy_name end def test_init default_info = {:ports => {}} assert_equal default_info, @sa.info assert_equal @app, @sa.app assert_equal Hash.new, @sa.scripts assert_equal [:all], @sa.roles end def test_init_roles sa = Sunshine::ServerApp.new @app, "host", :roles => "role1 role2" assert_equal [:role1, :role2], sa.roles sa = Sunshine::ServerApp.new @app, "host", :roles => %w{role3 role4} assert_equal [:role3, :role4], sa.roles end def test_add_shell_paths @sa.add_shell_paths "test/path1", "test/path2" assert_equal "test/path1:test/path2:$PATH", @sa.shell_env['PATH'] @sa.add_shell_paths "test/path3", "test/path4" assert_equal "test/path3:test/path4:test/path1:test/path2:$PATH", @sa.shell_env['PATH'] end def test_app_attr sa_root_path = "local/server_app/path" sa_deploy_name = "local_deploy_name" @sa = Sunshine::ServerApp.new "test", "host", :root_path => sa_root_path, :deploy_name => sa_deploy_name assert_equal sa_root_path, @sa.root_path assert_equal sa_deploy_name, @sa.deploy_name assert_equal "test", @sa.name @sa.app = @app assert_not_equal sa_root_path, @sa.root_path assert_not_equal sa_deploy_name, @sa.deploy_name assert_not_equal "test", @sa.name assert_equal @app.root_path, @sa.root_path assert_equal @app.deploy_name, @sa.deploy_name assert_equal @app.name, @sa.name end def test_build_control_scripts @sa.scripts[:start] << "start" @sa.scripts[:stop] << "stop" @sa.scripts[:custom] << "custom" @sa.build_control_scripts [:start, :stop, :custom].each do |script| content = @sa.make_bash_script script, @sa.scripts[script] assert @sa.method_called?(:write_script, :args => [script, content]) end content = @sa.make_env_bash_script assert @sa.method_called?(:write_script, :args => ["env", content]) content = @sa.make_bash_script :restart, ["#{@sa.app.root_path}/stop", "#{@sa.app.root_path}/start"] assert @sa.method_called?(:write_script, :args => [:restart, content]) end def test_build_deploy_info_file @sa.shell.mock :file?, :return => false args = ["#{@app.scripts_path}/info", @sa.get_deploy_info.to_yaml] @sa.build_deploy_info_file assert @sa.shell.method_called?(:make_file, :args => args) args = ["#{@app.scripts_path}/info", "#{@app.root_path}/info"] assert @sa.shell.method_called?(:symlink, :args => args) end def test_checkout_repo @sa.checkout_repo @app.repo repo = @sa.app.repo args = [@app.checkout_path, @sa.shell] assert repo.method_called?(:checkout_to, :args => args) info = @app.repo.checkout_to @app.checkout_path, @sa.shell assert_equal info, @sa.info[:scm] end def test_deploy_details deploy_details = {:item => "thing"} other_details = {:key => "value"} @sa.shell.mock :call, :args => ["cat #{@sa.root_path}/info"], :return => other_details.to_yaml @sa.instance_variable_set "@deploy_details", deploy_details assert_equal deploy_details, @sa.deploy_details assert_equal other_details, @sa.deploy_details(true) end def test_not_deployed? @sa.mock :deploy_details, :args => [true], :return => nil assert_equal false, @sa.deployed? end def test_server_checked_deployed? @sa.mock :deploy_details, :args => [true], :return => {:deploy_name => @sa.deploy_name} assert_equal true, @sa.deployed? end def test_cached_details_deployed? @sa.instance_variable_set "@deploy_details", :deploy_name => @sa.deploy_name assert_equal true, @sa.deployed? end def test_get_deploy_info test_info = { :deployed_at => Time.now.to_s, :deployed_as => @sa.shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(@app.checkout_path), :name => @sa.name, :env => @sa.shell_env, :roles => @sa.roles, :path => @app.root_path, :sunshine_version => Sunshine::VERSION }.merge @sa.info deploy_info = @sa.get_deploy_info deploy_info.each do |key, val| next if key == :deployed_at assert_equal test_info[key], val end end def test_has_all_roles assert @sa.has_roles?([:web, :app, :blarg]) assert @sa.has_roles?([:web, :app, :blarg], true) end def test_has_roles @sa.roles = [:web, :app] assert @sa.has_roles?(:web) assert @sa.has_roles?([:web, :app]) assert [email protected]_roles?([:blarg, :web, :app]) assert @sa.has_roles?([:blarg, :web, :app], true) end def test_install_deps nginx_dep = Sunshine.dependencies.get 'nginx', :prefer => @sa.pkg_manager @sa.install_deps "ruby", nginx_dep assert_dep_install 'ruby', Sunshine::Yum assert_dep_install 'nginx', Sunshine::Yum end def test_install_deps_bad_type nginx_dep = Sunshine.dependencies.get 'nginx' @sa.install_deps nginx_dep, :type => Sunshine::Gem raise "Didn't raise missing dependency when it should have." rescue Sunshine::MissingDependency => e assert_equal "No dependency 'nginx' [Sunshine::Gem]", e.message end def test_make_app_directories @sa.make_app_directories assert_server_call "mkdir -p #{@sa.directories.join(" ")}" end def test_make_bash_script app_script = @sa.make_bash_script "blah", [1,2,3,4] assert_bash_script "blah", [1,2,3,4], app_script end def test_make_env_bash_script @sa.shell.env = {"BLAH" => "blarg", "HOME" => "/home/blah"} test_script = "#!/bin/bash\nenv BLAH=blarg HOME=/home/blah \"$@\"" assert_equal test_script, @sa.make_env_bash_script end def test_rake @sa.rake "db:migrate" assert_dep_install 'rake', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && rake db:migrate" end def test_register_as_deployed Sunshine::AddCommand.extend MockObject unless MockObject === Sunshine::AddCommand @sa.register_as_deployed args = [@app.root_path, {'servers' => [@sa.shell]}] assert Sunshine::AddCommand.method_called?(:exec, :args => args) end def test_remove_old_deploys Sunshine.setup 'max_deploy_versions' => 3 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_server_call "rm -rf #{removed.join(" ")}" end def test_remove_old_deploys_unnecessary Sunshine.setup 'max_deploy_versions' => 5 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.mock :call, :args => ["ls -1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_not_called "rm -rf #{removed.join(" ")}" end def test_revert! deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" last_deploy = "#{@app.deploys_path}/ploy5" assert_server_call "ln -sfT #{last_deploy} #{@app.current_path}" end def test_no_previous_revert! @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" end def test_run_bundler @sa.run_bundler assert_dep_install 'bundler', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && gem bundle" end def test_run_geminstaller @sa.run_geminstaller assert_dep_install 'geminstaller', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && geminstaller -e" end + def test_running? + set_mock_response_for @sa, 0, + "#{@sa.root_path}/status" => [:out, "THE SYSTEM OK!"] + + assert_equal true, @sa.running? + end + + + def test_not_running? + set_mock_response_for @sa, 13, + "#{@sa.root_path}/status" => [:err, "THE SYSTEM IS DOWN!"] + + assert_equal false, @sa.running? + end + + + def test_errored_running? + set_mock_response_for @sa, 1, + "#{@sa.root_path}/status" => [:err, "KABLAM!"] + + assert_raises Sunshine::CmdError do + @sa.running? + end + end + + def test_sass sass_files = %w{file1 file2 file3} @sa.sass(*sass_files) assert_dep_install 'haml', @sa.pkg_manager sass_files.each do |file| sass_file = "public/stylesheets/sass/#{file}.sass" css_file = "public/stylesheets/#{file}.css" assert_server_call \ "cd #{@app.checkout_path} && sass #{sass_file} #{css_file}" end end def test_shell_env assert_equal @sa.shell.env, @sa.shell_env end def test_symlink_current_dir @sa.symlink_current_dir assert_server_call "ln -sfT #{@app.checkout_path} #{@app.current_path}" end def test_upload_tasks files = %w{task1 task2} @sa.upload_tasks(*files) assert_server_call "mkdir -p #{@app.checkout_path}/lib/tasks" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{@app.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_with_remote_path files = %w{task1 task2} path = "/path/to/remote/tasks" @sa.upload_tasks files[0], files[1], :remote_path => path assert_server_call "mkdir -p #{path}" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{path}/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_with_local_path files = %w{task1 task2} path = "/path/to/local/tasks" args = files.dup << {:local_path => path} @sa.upload_tasks(*args) assert_server_call "mkdir -p #{@sa.checkout_path}/lib/tasks" files.each do |f| args = ["#{path}/#{f}.rake", "#{@sa.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_all files = Dir.glob("templates/tasks/*").map{|f| File.basename(f, ".rake")} @sa.upload_tasks assert_server_call "mkdir -p #{@app.checkout_path}/lib/tasks" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{@app.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_write_script @sa.shell.mock :file?, :return => false @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert @sa.shell.method_called?(:make_file, :args => args) end def test_symlink_scripts_to_root @sa.shell.mock :call, :args => ["ls -1 #{@sa.scripts_path}"], :return => "script_name\n" args = ["#{@app.scripts_path}/script_name", "#{@app.root_path}/script_name"] @sa.symlink_scripts_to_root assert @sa.shell.method_called?(:symlink, :args => args) end def test_write_script_existing @sa.shell.mock :file?, :return => true @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert [email protected]_called?(:make_file, :args => args) end end
jcasts/sunshine
62d336b800025fca199b7784a2fec25971114c42
changed script generation implementation to return meaningful bash exit codes for start/stop/restart/status
diff --git a/lib/sunshine/daemon.rb b/lib/sunshine/daemon.rb index b27f112..25d0a27 100644 --- a/lib/sunshine/daemon.rb +++ b/lib/sunshine/daemon.rb @@ -1,436 +1,490 @@ module Sunshine ## # An abstract class to wrap simple daemon software setup and start/stop. # # Child classes are expected to at least provide a start and stop bash script # by either overloading the start_cmd and stop_cmd methods, or by setting # @start_cmd and @stop_cmd. A restart_cmd method or @restart_cmd attribute # may also be specified if restart requires more functionality than simply # calling start_cmd && stop_cmd. class Daemon + START_FAILED_CODE = 10 + STOP_FAILED_CODE = 11 + RESTART_FAILED_CODE = 12 + STATUS_FAILED_CODE = 13 ## # Returns an array of method names to assign to the binder # for template rendering. def self.binder_methods [:app, :name, :bin, :pid, :processes, :config_path, :log_file, :timeout] end ## # Returns the short, snake-case version of the class: # Sunshine::Daemon.short_name # #=> "daemon" def self.short_name @short_name ||= self.underscore self.to_s.split("::").last end ## # Turn camelcase into underscore. Used for Daemon#name. def self.underscore str str.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2').downcase end attr_reader :app, :name attr_accessor :bin, :pid, :processes, :timeout, :sudo, :server_apps attr_accessor :config_template, :config_path, :config_file attr_writer :start_cmd, :stop_cmd, :restart_cmd, :status_cmd # Daemon objects need only an App object to be instantiated but many options # are available for customization: # # :bin:: bin_path - Set the daemon app bin path (e.g. usr/local/nginx) # defaults to svr_name. # # :processes:: prcss_num - Number of processes daemon should run; # defaults to 1. # # :config_file:: name - Remote file name the daemon should load; # defaults to svr_name.conf # # :config_path:: path - Remote path daemon configs will be uploaded to; # defaults to app.current_path/daemons/svr_name # # :config_template:: path - Glob path to tempates to render and upload; # defaults to sunshine_path/templates/svr_name/* # # :log_path:: path - Path to where the log files should be output; # defaults to app.log_path. # # :pid:: pid_path - Set the pid; default: app.shared_path/pids/svr_name.pid # defaults to app.shared_path/pids/svr_name.pid. # # :sudo:: bool|str - Define if sudo should be used to run the daemon, # and/or with what user. # # :timeout:: int - Timeout to use for daemon config, defaults to 0. # # The Daemon constructor also supports any App#find options to narrow # the server apps to use. Note: subclasses such as Server already have # a default :role that can be overridden. def initialize app, options={} @options = options @app = app @name = options[:name] || self.class.short_name @pid = options[:pid] || "#{@app.shared_path}/pids/#{@name}.pid" @bin = options[:bin] || self.class.short_name @sudo = options[:sudo] @timeout = options[:timeout] || 0 @dep_name = options[:dep_name] || self.class.short_name @processes = options[:processes] || 1 @sigkill = 'QUIT' @config_template = options[:config_template] || "#{Sunshine::ROOT}/templates/#{self.class.short_name}/*" @config_path = options[:config_path] || "#{@app.current_path}/daemons/#{@name}" @config_file = options[:config_file] || "#{self.class.short_name}.conf" log_path = options[:log_path] || @app.log_path @log_files = { :stderr => "#{log_path}/#{@name}_stderr.log", :stdout => "#{log_path}/#{@name}_stdout.log" } @start_cmd = @stop_cmd = @restart_cmd = @status_cmd = nil @setup_successful = nil register_after_user_script end ## # Do something with each server app used by the daemon. def each_server_app(&block) @app.each(@options, &block) end ## # Setup the daemon, parse and upload config templates. # If a dependency with the daemon name exists in Sunshine.dependencies, # setup will attempt to install the dependency before uploading configs. # If a block is given it will be passed each server_app and binder object # which will be used for the building erb config templates. # See the ConfigBinding class for more information. def setup Sunshine.logger.info @name, "Setting up #{@name} daemon" do each_server_app do |server_app| # Build erb binding binder = config_binding server_app.shell configure_remote_dirs server_app.shell touch_log_files server_app.shell yield(server_app, binder) if block_given? server_app.install_deps @dep_name if Sunshine.dependencies.exist?(@dep_name) upload_config_files(server_app.shell, binder.get_binding) end end @setup_successful = true rescue => e raise DaemonError.new(e, "Could not setup #{@name}") end ## # Check if setup was run successfully. def has_setup? force=false return @setup_successful unless @setup_successful.nil? || force each_server_app do |server_app| unless server_app.shell.file? config_file_path return @setup_successful = false end end @setup_successful = true end ## # Start the daemon app after running setup. def start self.setup unless has_setup? Sunshine.logger.info @name, "Starting #{@name} daemon" do each_server_app do |server_app| begin - server_app.shell.call start_cmd, + server_app.shell.call _start_cmd, :sudo => pick_sudo(server_app.shell) yield(server_app) if block_given? rescue => e raise DaemonError.new(e, "Could not start #{@name}") end end end end ## # Check if the daemon is running on all servers def status each_server_app do |server_app| - server_app.shell.call status_cmd, :sudo => pick_sudo(server_app.shell) + server_app.shell.call _status_cmd, :sudo => pick_sudo(server_app.shell) end true rescue CmdError => e false end ## # Stop the daemon app. def stop Sunshine.logger.info @name, "Stopping #{@name} daemon" do each_server_app do |server_app| begin - server_app.shell.call stop_cmd, + server_app.shell.call _stop_cmd, :sudo => pick_sudo(server_app.shell) yield(server_app) if block_given? rescue => e raise DaemonError.new(e, "Could not stop #{@name}") end end end end ## # Restarts the daemon using the restart_cmd attribute if provided. # If restart_cmd is not provided, calls stop and start. def restart self.setup unless has_setup? Sunshine.logger.info @name, "Restarting #{@name} daemon" do each_server_app do |server_app| begin - server_app.shell.call restart_cmd, + server_app.shell.call _restart_cmd, :sudo => pick_sudo(server_app.shell) yield(server_app) if block_given? rescue => e raise DaemonError.new(e, "Could not restart #{@name}") end end end end + ## + # Wrap a command with a fail-specific exitcode and message. + + def exit_on_failure cmd, exitcode=1, message=nil + "(#{cmd}) || (echo '#{message}' && exit #{exitcode});" + end + + ## # Gets the command that starts the daemon. # Should be overridden by child classes. def start_cmd - raise DaemonError, "@start_cmd undefined for #{@name}" unless @start_cmd - "(#{@start_cmd}) || echo 'Could not start #{@name} for #{@app.name}';" + return @start_cmd if @start_cmd + raise DaemonError, "start_cmd undefined for #{@name}" + end + + + ## + # Start command wrapped with an exit_on_failure handler. + + def _start_cmd + exit_on_failure start_cmd, START_FAILED_CODE, + "Could not start #{@name} for #{@app.name}" end ## # Default daemon stop command. def stop_cmd "test -f #{@pid} && kill -#{@sigkill} $(cat #{@pid}) && sleep 1 && "+ - "rm -f #{@pid} || echo 'Could not kill #{@name} pid for #{@app.name}';" + "rm -f #{@pid}" + end + + + ## + # Stop command wrapped with an exit_on_failure handler. + + def _stop_cmd + exit_on_failure stop_cmd, STOP_FAILED_CODE, + "Could not kill #{@name} pid for #{@app.name}" end ## # Gets the command that restarts the daemon. + # Should be overridden by child classes if different + # from start_cmd && stop_cmd. def restart_cmd - @restart_cmd || [stop_cmd, start_cmd].map{|c| "(#{c})"}.join(" && ") + @restart_cmd end ## - # Get the command to check if the daemon is running. + # Restart command wrapped with an exit_on_failure handler. + + def _restart_cmd + if restart_cmd + exit_on_failure restart_cmd, RESTART_FAILED_CODE, + "Could not restart #{@name} for #{@app.name}" + else + "(#{_stop_cmd}) && (#{_start_cmd});" + end + end + + + ## + # Status command wrapped with an exit_on_failure handler. def status_cmd @status_cmd || "test -f #{@pid} && kill -0 $(cat #{@pid})" end + ## + # Get the command to check if the daemon is running. + + def _status_cmd + exit_on_failure status_cmd, STATUS_FAILED_CODE, + "#{@app.name} #{@name} is not running" + end + + ## # Append or override daemon log file paths: # daemon.log_files :stderr => "/all_logs/stderr.log" def log_files hash @log_files.merge!(hash) end ## # Get the path of a log file: # daemon.log_file(:stderr) # #=> "/all_logs/stderr.log" def log_file key @log_files[key] end ## # Get the file path to the daemon's config file. def config_file_path "#{@config_path}/#{@config_file}" end ## # Upload config files and run them through erb with the provided # binding if necessary. def upload_config_files shell, setup_binding=binding config_template_files.each do |config_file| if File.extname(config_file) == ".erb" filename = File.basename(config_file[0..-5]) parsed_config = @app.build_erb(config_file, setup_binding) shell.make_file "#{@config_path}/#{filename}", parsed_config else filename = File.basename(config_file) shell.upload config_file, "#{@config_path}/#{filename}" end end end ## # Get the array of local config template files needed by the daemon. def config_template_files @config_template_files ||= Dir[@config_template].select{|f| File.file?(f)} end ## # Create and setup a binding for a given shell. def config_binding shell binder = Binder.new self binder.forward(*self.class.binder_methods) binder.set :shell, shell binder_sudo = pick_sudo(shell) binder.set :sudo, binder_sudo binder.set :expand_path do |path| shell.expand_path path end binder end ## # Pick which sudo to use between the daemon sudo and shell sudo. # (Useful when running servers on ports < 1024) def pick_sudo shell self.sudo.nil? ? shell.sudo : self.sudo end ## # Make sure all the remote directories needed by the daemon exist. def configure_remote_dirs shell dirs = @log_files.values.map{|f| File.dirname(f)} dirs << File.dirname(@pid) dirs << @config_path dirs.delete_if{|d| d == "."} dirs = dirs.join(" ") shell.call "mkdir -p #{dirs}" end ## # Make sure log files are owned by the daemon's user. def touch_log_files shell files = @log_files.values.join(" ") sudo = pick_sudo(shell) user = case sudo when true then 'root' when String then sudo else nil end shell.call "touch #{files}", :sudo => true shell.call "chown #{user} #{files}", :sudo => true if user end ## # Setup what should be run after the user block on App#deploy. def register_after_user_script @app.after_user_script do |app| next unless has_setup? each_server_app do |sa| sudo = pick_sudo sa.shell %w{start stop restart status}.each do |script| script_file = "#{@config_path}/#{script}" - cmd = send "#{script}_cmd" + cmd = send "_#{script}_cmd" sa.shell.make_file script_file, cmd, :flags => '--chmod=ugo=rwx' cmd = sa.shell.sudo_cmd "#{@app.root_path}/env #{script_file}", sudo sa.scripts[script.to_sym] << [*cmd].join(" ") end end end end end end diff --git a/test/unit/test_daemon.rb b/test/unit/test_daemon.rb index 4ddf94c..0765772 100644 --- a/test/unit/test_daemon.rb +++ b/test/unit/test_daemon.rb @@ -1,26 +1,26 @@ require 'test/test_helper' class TestDaemon < Test::Unit::TestCase def setup mock_remote_shell_popen4 @app = Sunshine::App.new(TEST_APP_CONFIG_FILE).extend MockObject @server_app = @app.server_apps.first.extend MockObject @app.server_apps.first.shell.extend MockObject use_remote_shell @server_app.shell end def test_missing_start_cmd daemon = Sunshine::Daemon.new @app begin daemon.start_cmd raise "Should have thrown DaemonError but didn't :(" rescue Sunshine::DaemonError => e - assert_equal "@start_cmd undefined for daemon", e.message + assert_equal "start_cmd undefined for daemon", e.message end end end diff --git a/test/unit/test_nginx.rb b/test/unit/test_nginx.rb index b56f5c3..82961a3 100644 --- a/test/unit/test_nginx.rb +++ b/test/unit/test_nginx.rb @@ -1,99 +1,102 @@ require 'test/test_helper' class TestNginx < Test::Unit::TestCase def setup @app = Sunshine::App.new TEST_APP_CONFIG_FILE @app.server_apps.first.extend MockOpen4 @app.server_apps.first.shell.extend MockOpen4 use_remote_shell @app.server_apps.first.shell @passenger = Sunshine::Nginx.new @app @nginx = Sunshine::Nginx.new @app, :port => 5000, :point_to => @passenger @passenger_root = "/Library/Ruby/Gems/1.8/gems/passenger-2.2.11" @nginx_passenger_check = "#{@passenger_root}/ext/nginx" end def test_cmd ds = @nginx.app.server_apps.first.shell ds.set_mock_response 0, "passenger-config --root" => [:out, @passenger_root] @nginx.start @nginx.stop assert_ssh_call start_cmd(@passenger) assert_ssh_call stop_cmd(@passenger) end def test_custom_sudo_cmd ds = @nginx.app.server_apps.first.shell ds.set_mock_response 0, "passenger-config --root" => [:out, @passenger_root] @nginx.sudo = "someuser" @nginx.start @nginx.stop assert_ssh_call start_cmd(@passenger), ds, :sudo => @nginx.sudo assert_ssh_call stop_cmd(@passenger), ds, :sudo => @nginx.sudo end def test_sudo_cmd ds = @passenger.app.server_apps.first.shell ds.set_mock_response 0, "gem list passenger -d" => [:out, @gemout] @passenger.start @passenger.stop assert_equal true, @passenger.sudo assert_ssh_call start_cmd(@passenger), ds, :sudo => true assert_ssh_call stop_cmd(@passenger), ds, :sudo => true end def test_setup_passenger ds = @passenger.app.server_apps.first.shell ds.set_mock_response 0, "passenger-config --root" => [:out, @passenger_root] ds.set_mock_response 0, "nginx -V 2>&1" => [:out, @nginx_passenger_check] @passenger.setup do |ds, binder| assert binder.sudo assert binder.use_passenger? assert_equal "/Library/Ruby/Gems/1.8/gems/passenger-2.2.11", binder.passenger_root end end def test_setup ds = @nginx.app.server_apps.first.shell ds.set_mock_response 0, "passenger-config --root" => [:out, @passenger_root] @nginx.setup do |ds, binder| assert !binder.sudo assert !binder.use_passenger? assert_equal "/Library/Ruby/Gems/1.8/gems/passenger-2.2.11", binder.passenger_root end end ## Helper methods def start_cmd svr - "#{svr.bin} -c #{svr.config_file_path}" + svr.exit_on_failure "#{svr.bin} -c #{svr.config_file_path}", 10, + "Could not start #{svr.name} for #{svr.app.name}" end def stop_cmd svr - "test -f #{svr.pid} && kill -#{svr.sigkill} $(cat #{svr.pid}) && "+ - "sleep 1 && rm -f #{svr.pid} || "+ - "echo 'Could not kill #{svr.name} pid for #{svr.app.name}';" + cmd = "test -f #{svr.pid} && kill -#{svr.sigkill} $(cat #{svr.pid}) && "+ + "sleep 1 && rm -f #{svr.pid}" + + svr.exit_on_failure cmd, 11, + "Could not kill #{svr.name} pid for #{svr.app.name}" end end diff --git a/test/unit/test_server.rb b/test/unit/test_server.rb index 2b0bb88..2209653 100644 --- a/test/unit/test_server.rb +++ b/test/unit/test_server.rb @@ -1,309 +1,309 @@ require 'test/test_helper' class TestServer < Test::Unit::TestCase class Server < Sunshine::Server def start_cmd "test start cmd" end def stop_cmd "test stop cmd" end end def setup mock_remote_shell_popen4 @app = Sunshine::App.new(TEST_APP_CONFIG_FILE).extend MockObject @server_app = @app.server_apps.first.extend MockObject @app.server_apps.first.shell.extend MockObject @server = Server.new @app @rainbows = Sunshine::Rainbows.new(@app).extend MockObject use_remote_shell @server_app.shell end def test_initialize assert_server_init config = { :point_to => @server, :pid => "path/to/pid", :bin => "path/to/bin", :port => 1234, :processes => 10, :server_name => "serv1.com", :server_apps => ["remote_shell_test"], :config_template => "template.erb", :config_path => "path/to/config", :config_file => "conf_filename.conf", :log_path => "path/to/logs", :sudo => "sudouser" } svr = Server.new @app, config config[:target] = config[:point_to] config[:stderr] = "#{config[:log_path]}/server_stderr.log" config[:stdout] = "#{config[:log_path]}/server_stdout.log" assert_server_init svr, config end def test_setup server = @rainbows server.setup do |sa, binder| assert_equal @server_app, sa assert_equal sa.shell, binder.shell assert_equal sa.shell.host, binder.server_name assert_equal @rainbows.send(:pick_sudo, sa.shell), binder.sudo end server.each_server_app do |sa| assert sa.method_called?(:install_deps, :args => ["rainbows"]) assert server.method_called?(:configure_remote_dirs, :args => [sa.shell]) assert server.method_called?(:touch_log_files, :args => [sa.shell]) assert server.method_called?(:upload_config_files, :args => [sa.shell]) end assert_rsync(/rainbows\.conf/, "some_server.com:"+ "/usr/local/my_user/other_app/current/daemons/rainbows/rainbows.conf") assert server.has_setup? end def test_has_setup? server = @rainbows assert_equal nil, server.instance_variable_get("@setup_successful") @server_app.shell.mock :file?, :args => [server.config_file_path], :return => false assert_equal false, server.has_setup? @server_app.shell.mock :file?, :args => [server.config_file_path], :return => true assert_equal false, server.has_setup? assert_equal true, server.has_setup?(true) end def test_new_cluster cluster = Sunshine::Server.new_cluster 3, @app, :port => 5000 assert_equal Sunshine::ServerCluster, cluster.class assert Array === cluster assert_equal 3, cluster.length cluster.each_with_index do |server, index| port = 5000 + index assert_equal Sunshine::Server, server.class assert_equal port, server.port assert_equal "server.#{port}", server.name end end def test_start server = @rainbows @server_app.shell.mock :file?, :args => [server.config_file_path], :return => false server.start do |sa| assert_equal @server_app, sa - assert_ssh_call server.start_cmd, sa.shell, :sudo => true + assert_ssh_call server._start_cmd, sa.shell, :sudo => true end assert server.method_called?(:setup) end def test_start_missing_setup server = @rainbows @server_app.shell.mock :file?, :args => [server.config_file_path], :return => true server.start do |sa| assert_equal @server_app, sa - assert_ssh_call server.start_cmd, sa.shell, :sudo => true + assert_ssh_call server._start_cmd, sa.shell, :sudo => true end assert !server.method_called?(:setup) end def test_stop server = @rainbows server.stop do |sa| assert_equal @server_app, sa - assert_ssh_call server.stop_cmd, sa.shell, :sudo => true + assert_ssh_call server._stop_cmd, sa.shell, :sudo => true end end def test_restart server = @rainbows server.restart do |sa| assert_equal @server_app, sa - assert_ssh_call server.restart_cmd, sa.shell, :sudo => true + assert_ssh_call server._restart_cmd, sa.shell, :sudo => true end end def test_restart_missing_setup server = @rainbows @server_app.shell.mock :file?, :args => [server.config_file_path], :return => true server.restart assert !server.method_called?(:setup) end def test_restart_with_cmd server = @rainbows server.instance_variable_set("@restart_cmd", "RESTART!!1!") @server_app.shell.mock :file?, :args => [server.config_file_path], :return => false server.restart do |sa| assert_equal @server_app, sa - assert_ssh_call server.restart_cmd, sa.shell, :sudo => true + assert_ssh_call server._restart_cmd, sa.shell, :sudo => true end assert server.method_called?(:setup) end def test_log_files @server.log_files :test_log => "/path/test_log.log", :another_test => "/path/another_test.log" assert_equal "/path/test_log.log", @server.log_file(:test_log) assert_equal "/path/another_test.log", @server.log_file(:another_test) end def test_upload_config_files server = @rainbows server.mock :config_template_files, :return => ["rainbows.conf.erb", "test/non_erb.conf"] @app.mock :build_erb, :return => "test_config" server.upload_config_files @server_app.shell args = ["#{server.config_path}/rainbows.conf", "test_config"] assert @server_app.shell.method_called?(:make_file, :args => args) args = ["test/non_erb.conf", "#{server.config_path}/non_erb.conf"] assert @server_app.shell.method_called?(:upload, :args => args) end def test_config_template_files files = Dir["#{Sunshine::ROOT}/templates/rainbows/*"].select{|f| File.file?(f)} assert_equal files, @rainbows.config_template_files end def test_register_after_user_script server = @rainbows assert @app.method_called?(:after_user_script) # called on Server#init @app.run_post_user_lambdas server.each_server_app do |sa| %w{start stop restart status}.each do |script| script_file = "#{@app.root_path}/env #{server.config_path}/#{script}" cmd = sa.shell.sudo_cmd script_file, server.send(:pick_sudo, sa.shell) assert sa.scripts[script.to_sym].include?(cmd.join(" ")) end assert_equal server.port, sa.info[:ports][server.pid] end end def test_pick_sudo ds = @rainbows.app.server_apps.first.shell assert_equal true, @rainbows.send(:pick_sudo, ds) @rainbows.sudo = true assert_equal true, @rainbows.send(:pick_sudo, ds) ds.sudo = true @rainbows.sudo = false assert_equal false, @rainbows.send(:pick_sudo, ds) ds.sudo = "blah" @rainbows.sudo = true assert_equal true, @rainbows.send(:pick_sudo, ds) @rainbows.sudo = "local" assert_equal "local", @rainbows.send(:pick_sudo, ds) end ## # Helper methods def assert_dir_in arr, file assert arr.include?(File.dirname(file)) end def assert_server_init server=@server, user_config={} config = { :app => @app, :target => @app, :name => "server", :pid => "#{@app.shared_path}/pids/server.pid", :bin => "server", :port => 80, :processes => 1, :server_name => nil, :config_file => "server.conf", :config_path => "#{@app.current_path}/daemons/server", :config_template => "#{Sunshine::ROOT}/templates/server/*", :stderr => "#{@app.log_path}/server_stderr.log", :stdout => "#{@app.log_path}/server_stdout.log" }.merge(user_config) assert_equal config[:app], server.app assert_equal config[:bin], server.bin assert_equal config[:pid], server.pid assert_equal config[:port], server.port assert_equal config[:name], server.name assert_equal config[:target], server.target assert_equal config[:processes], server.processes assert_equal config[:server_name], server.server_name assert_equal config[:config_path], server.config_path assert_equal config[:config_file], server.config_file assert_equal config[:config_template], server.config_template assert_equal config[:stderr], server.log_file(:stderr) assert_equal config[:stdout], server.log_file(:stdout) config_file_path = "#{config[:config_path]}/#{config[:config_file]}" assert_equal config_file_path, server.config_file_path end end
jcasts/sunshine
a682f0bf78bf23828f55efaaaaa900219a97277a
restructured and renamed exceptions
diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index 0244b0f..ca3f0f7 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -1,1298 +1,1286 @@ module Sunshine ## # App objects are the core of Sunshine deployment. The Sunshine paradygm # is to construct an app object, and run custom deploy code by passing # a block to its deploy method: # # someserver = Sunshine::RemoteShell.new "[email protected]", # :roles => [:web, :app] # # options = { # :name => 'myapp', # :repo => {:type => :svn, :url => 'svn://blah...'}, # :root_path => '/usr/local/myapp', # :remote_shells => '[email protected]' # } # # app = Sunshine::App.new(options) # # app.deploy do |app| # # app_server = Sunshine::Rainbows.new app, :port => 3000 # web_server = Sunshine::Nginx.new app, :point_to => app_server # # app_server.setup # web_server.setup # end # # Multiple apps can be defined, and deployed from a single deploy script. # The constructor also supports passing a yaml file path: # # Sunshine::App.new("path/to/config.yml") # # Deployment can be expressed more concisely by calling App::deploy: # # App.deploy("path/to/config.yml") do |app| # Sunshine::Rainbows.new(app).setup # end # # # An App holds information about where to deploy an application to and # how to deploy it, as well as many convenience methods to setup and # manipulate the deployment process. Most of these methods support passing # remote shell find options: # # app.rake 'db:migrate', :role => :db # app.deploy :host => 'server1.com' # # See App#find for more information. # # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml # # Yaml files must define settings on a per-environment basis. The default # environment will be used if the deploy_env is not found in the config. # Let's consider the following config: # # #config.yml: # --- # :default: # :repo: # :type: :svn # :url: http://subversion/repo/tags/release-001 # :remote_shells: dev.myserver.com # # :qa: # :remote_shells: # - qa1.myserver.com # - qa2.myserver.com # # :qa_special: # :inherits: :qa # :root_path: /path/to/application # # By default, environment definitions inherit the :default environment. In # this instance, :qa_special also inherits from :qa. # With the given config, I could setup the App instance as so: # # App.new "config.yml", :deploy_env => :development # # Note: by default, App will get the deploy_env value # # from Sunshine.deploy_env # # The above will simply load the default config. The following, however, # will load the :qa_special config which inherits from # both :qa and :default: # # App.new "config.yml", :deploy_env => :qa_special # # # Another way of instantiating an App is to pass it a hash. Unlike the yaml # config file, the hash is not on a per-environment basis and isexpected # to already have the correct values for the given environment. # The following is equivalent to loading the above :default environment: # # App.new :remote_shells => "dev.myserver.com", # :repo => { # :type => :svn, # :url => "http://subversion/repo/tags/release-001" # } # # In theory, the minimum amount of information required to instantiate # an app is the repo and remote_shells. If the repo option is omitted, # the App will attempt to detect if the pwd is a checkout out repo and # use that information. If you would like to deploy an application that # is not under source countrol, you may do so by using Sunshine::RsyncRepo, # or passing :rsync in your hash as your repo type. # # # Options supported by App.new are the following: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. class App ## # Initialize and deploy an application. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] @on_sigint = @on_exception = nil end ## # Call a command on specified server apps. # Supports any App#find and Shell#call options. def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Connect server apps. Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## - # Check if all server apps are connected. Supports any App#find options. + # Check if all server apps are connected and returns a boolean. + # Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## - # Check if any server apps are connected. Supports any App#find options. + # Check if any server apps are connected and returns a boolean. + # Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect server apps. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # If the deploy fails or an exception is raised, it will attempt to # run the Sunshine.failed_deploy_behavior, which is set to :revert by # default. However, this is not true of ssh connection failures. # # If the deploy is interrupted by a SIGINT, it will attempt to run # the Sunshine.sigint_behavior, which is set to :revert by default. # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil state = { :success => false, :stopped => false, :symlinked => false } Sunshine.logger.info :app, "Beginning #{@name} deploy" with_session options do |app| interruptable state do - raise CriticalDeployError, "No servers defined for #{@name}" if + raise DeployError, "No servers defined for #{@name}" if @server_apps.empty? make_app_directories checkout_codebase state[:stopped] = true if stop state[:symlinked] = true if symlink_current_dir yield self if block_given? run_post_user_lambdas health :enable build_control_scripts build_deploy_info_file build_crontab register_as_deployed state[:success] = true if start! :force => true end remove_old_deploys if state[:success] rescue Sunshine.logger.error :app, "Could not remove old deploys" state[:success] &&= deployed? end Sunshine.logger.info :app, "Finished #{@name} deploy" if state[:success] state[:success] end ## # Handles SIGINTs and exceptions according to rules set by # Sunshine.sigint_behavior and Sunshine.exception_behavior # or with the override hooks App#on_sigint and App#on_exception. def interruptable options={} interrupt_trap = TrapStack.add_trap "Interrupted #{@name}" do handle_sigint options end yield if block_given? rescue => e Sunshine.logger.error :app, "#{e.class}: #{e.message}" do Sunshine.logger.error '>>', e.backtrace.join("\n") end handle_exception e, options ensure TrapStack.delete_trap interrupt_trap end ## # Calls the Apps on_sigint hook or the default Sunshine.sigint_behavior. def handle_sigint state={} return @on_sigint.call(state) if @on_sigint handle_interruption Sunshine.sigint_behavior, state end ## # Calls the Apps on_exception hook or the default # Sunshine.exception_behavior. def handle_exception exception, state={} return @on_exception.call(exception, state) if @on_exception handle_interruption Sunshine.exception_behavior, state end ## # Set this to define the behavior of SIGINT during a deploy. # Defines what to do when an INT signal is received when running # a proc through App#interruptable. Used primarily to catch SIGINTs # during deploys. Passes the block a hash with the state of the deploy: # # app.on_sigint do |deploy_state_hash| # deploy_state_hash # #=> {:stopped => true, :symlinked => true, :success => false} # end def on_sigint &block @on_sigint = block end ## # Set this to define the behavior of exceptions during a deploy. # Defines what to do when an exception is received when running # a proc through App#interruptable. Used primarily to catch exceptions # during deploys. Passes the block the exception and a hash with the # state of the deploy: # # app.on_exception do |exception, deploy_state_hash| # # do something... # end def on_exception &block @on_exception = block end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. def handle_interruption behavior, state={} case behavior when :revert revert! if state[:symlinked] start if state[:stopped] when :console self.console! when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" menu.choice(:revert) { handle_interruption :revert, state } menu.choice(:console){ handle_interruption :console, state } menu.choice(:exit) { handle_interruption :exit, state } end else + raise DeployError, "Deploy of #{@name} was interrupted." end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil - copy_option = options && options.has_key?(:copy) && options[:copy] + copy_option = options[:copy] if options if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end - - rescue => e - raise CriticalDeployError, e end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories - - rescue => e - raise FatalDeployError, e end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Run the restart script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def restart! options=nil with_server_apps options, :msg => "Running restart script", :send => :restart! end ## # Runs bundler on deploy servers. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] - - rescue => e - raise CriticalDeployError, e end ## # Runs GemInstaller on deploy servers. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] - - rescue => e - raise CriticalDeployError, e end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run the given script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def run_script! name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script!, name, options] end ## # Run a sass task on any or all deploy servers. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. def shell_env env_hash=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Run the start script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def start! options=nil with_server_apps options, :msg => "Running start script", :send => [:start!, options] end ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. # Post-deploy only. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end ## # Run the stop script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def stop! options=nil with_server_apps options, :msg => "Running stop script", :send => :stop! end ## # Use sudo on deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir - - rescue => e - raise CriticalDeployError, e end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! def threaded_each(options=nil, &block) mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end ## # Upload common rake tasks from the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', :role => :web # #=> upload app and common rake files # # Allows standard DeployServerDispatcher#find options, plus: # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files.last ? files.last.dup : {} options.delete(:remote_path) options = :all if options.empty? with_server_apps options, :msg => "Uploading tasks: #{files.join(" ")}", :send => [:upload_tasks, *files] end ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here # end # # Note: App#with_server_apps calls App#with_session. If you do not need # or want a server connection you can pass :no_session. def with_server_apps search_options, options={} options = search_options.merge options if Hash === search_options message = options[:msg] method = options[:no_threads] ? :each : :threaded_each auto_session = !options[:no_session] block = lambda do send(method, search_options) do |server_app| if block_given? yield(server_app) elsif options[:send] server_app.send(*options[:send]) end end end msg_block = lambda do if message Sunshine.logger.info(:app, message, &block) else block.call end end auto_session ? with_session(&msg_block) : msg_block.call end ## # Runs block ensuring a connection to remote_shells. # Connecting and disconnecting will be ignored if a session # already exists. Supports all App#find options. # # Ensures that servers are disconnected after the block is run # if servers were not previously connected. def with_session options=nil with_filter options do prev_connection = connected? begin connect unless prev_connection yield self ensure disconnect unless prev_connection end end end private ## # Set all the app paths based on the root deploy path. def set_deploy_paths path @root_path = path || File.join(Sunshine.web_directory, @name) @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end ## # Set the app's deploy servers: # server_apps_from_config "some_server" # #=> [<ServerApp @host="some_server"...>] # # server_apps_from_config ["svr1", "svr2", "svr3"] # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] # # remote_shells = [["svr1", {:roles => "web db app"}], "svr2", "svr3"] # server_apps_from_config remote_shells # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] def server_apps_from_config shells shells = [*shells].compact shells.map{|shell| ServerApp.new(*[self,*shell]) } end ## # Set the app's repo: # repo_from_config SvnRepo.new("myurl") # repo_from_config :type => :svn, :url => "myurl" def repo_from_config repo_def case repo_def when Sunshine::Repo repo_def when Hash Sunshine::Repo.new_of_type repo_def[:type], repo_def[:url], repo_def else Sunshine::Repo.detect Sunshine::PATH end end ## # Load a yml config file, parses it with erb and resolves deploy env # inheritance. def config_from_file config_file, erb_binding=binding, env=@deploy_env return {} unless config_file config_data = YAML.load build_erb(config_file, erb_binding) load_config_for config_data, env end ## # Loads an app yml config file, gets the default config # and the current deploy env and returns a merged config hash. def load_config_for config_hash, env return {} unless config_hash deploy_env_config = (config_hash[env] || {}).dup deploy_env_config[:inherits] ||= [] deploy_env_config[:inherits].unshift(:default) if :default != env && config_hash[:default] merge_config_inheritance deploy_env_config, config_hash end ## # Recursively merges config hashes based on the value at :inherits def merge_config_inheritance main_config, all_configs new_config = {} parents = [*main_config[:inherits]].compact parents.each do |config_name| parent = all_configs[config_name] parent = merge_config_inheritance parent, all_configs new_config = new_config.merge parent end new_config.merge main_config # Two merges important for inheritance order end end end diff --git a/lib/sunshine/daemon.rb b/lib/sunshine/daemon.rb index 9763d5e..201a55e 100644 --- a/lib/sunshine/daemon.rb +++ b/lib/sunshine/daemon.rb @@ -1,436 +1,436 @@ module Sunshine ## # An abstract class to wrap simple daemon software setup and start/stop. # # Child classes are expected to at least provide a start and stop bash script # by either overloading the start_cmd and stop_cmd methods, or by setting # @start_cmd and @stop_cmd. A restart_cmd method or @restart_cmd attribute # may also be specified if restart requires more functionality than simply # calling start_cmd && stop_cmd. class Daemon ## # Returns an array of method names to assign to the binder # for template rendering. def self.binder_methods [:app, :name, :bin, :pid, :processes, :config_path, :log_file, :timeout] end ## # Returns the short, snake-case version of the class: # Sunshine::Daemon.short_name # #=> "daemon" def self.short_name @short_name ||= self.underscore self.to_s.split("::").last end ## # Turn camelcase into underscore. Used for Daemon#name. def self.underscore str str.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2').downcase end attr_reader :app, :name attr_accessor :bin, :pid, :processes, :timeout, :sudo, :server_apps attr_accessor :config_template, :config_path, :config_file attr_writer :start_cmd, :stop_cmd, :restart_cmd, :status_cmd # Daemon objects need only an App object to be instantiated but many options # are available for customization: # # :bin:: bin_path - Set the daemon app bin path (e.g. usr/local/nginx) # defaults to svr_name. # # :processes:: prcss_num - Number of processes daemon should run; # defaults to 1. # # :config_file:: name - Remote file name the daemon should load; # defaults to svr_name.conf # # :config_path:: path - Remote path daemon configs will be uploaded to; # defaults to app.current_path/daemons/svr_name # # :config_template:: path - Glob path to tempates to render and upload; # defaults to sunshine_path/templates/svr_name/* # # :log_path:: path - Path to where the log files should be output; # defaults to app.log_path. # # :pid:: pid_path - Set the pid; default: app.shared_path/pids/svr_name.pid # defaults to app.shared_path/pids/svr_name.pid. # # :sudo:: bool|str - Define if sudo should be used to run the daemon, # and/or with what user. # # :timeout:: int - Timeout to use for daemon config, defaults to 0. # # The Daemon constructor also supports any App#find options to narrow # the server apps to use. Note: subclasses such as Server already have # a default :role that can be overridden. def initialize app, options={} @options = options @app = app @name = options[:name] || self.class.short_name @pid = options[:pid] || "#{@app.shared_path}/pids/#{@name}.pid" @bin = options[:bin] || self.class.short_name @sudo = options[:sudo] @timeout = options[:timeout] || 0 @dep_name = options[:dep_name] || self.class.short_name @processes = options[:processes] || 1 @sigkill = 'QUIT' @config_template = options[:config_template] || "#{Sunshine::ROOT}/templates/#{self.class.short_name}/*" @config_path = options[:config_path] || "#{@app.current_path}/daemons/#{@name}" @config_file = options[:config_file] || "#{self.class.short_name}.conf" log_path = options[:log_path] || @app.log_path @log_files = { :stderr => "#{log_path}/#{@name}_stderr.log", :stdout => "#{log_path}/#{@name}_stdout.log" } @start_cmd = @stop_cmd = @restart_cmd = @status_cmd = nil @setup_successful = nil register_after_user_script end ## # Do something with each server app used by the daemon. def each_server_app(&block) @app.each(@options, &block) end ## # Setup the daemon, parse and upload config templates. # If a dependency with the daemon name exists in Sunshine.dependencies, # setup will attempt to install the dependency before uploading configs. # If a block is given it will be passed each server_app and binder object # which will be used for the building erb config templates. # See the ConfigBinding class for more information. def setup Sunshine.logger.info @name, "Setting up #{@name} daemon" do each_server_app do |server_app| # Build erb binding binder = config_binding server_app.shell configure_remote_dirs server_app.shell touch_log_files server_app.shell yield(server_app, binder) if block_given? server_app.install_deps @dep_name if Sunshine.dependencies.exist?(@dep_name) upload_config_files(server_app.shell, binder.get_binding) end end @setup_successful = true rescue => e - raise CriticalDeployError.new(e, "Could not setup #{@name}") + raise DaemonError.new(e, "Could not setup #{@name}") end ## # Check if setup was run successfully. def has_setup? force=false return @setup_successful unless @setup_successful.nil? || force each_server_app do |server_app| unless server_app.shell.file? config_file_path return @setup_successful = false end end @setup_successful = true end ## # Start the daemon app after running setup. def start self.setup unless has_setup? Sunshine.logger.info @name, "Starting #{@name} daemon" do each_server_app do |server_app| begin server_app.shell.call start_cmd, :sudo => pick_sudo(server_app.shell) yield(server_app) if block_given? rescue => e - raise CriticalDeployError.new(e, "Could not start #{@name}") + raise DaemonError.new(e, "Could not start #{@name}") end end end end ## # Check if the daemon is running on all servers def status each_server_app do |server_app| server_app.shell.call status_cmd, :sudo => pick_sudo(server_app.shell) end true rescue CmdError => e false end ## # Stop the daemon app. def stop Sunshine.logger.info @name, "Stopping #{@name} daemon" do each_server_app do |server_app| begin server_app.shell.call stop_cmd, :sudo => pick_sudo(server_app.shell) yield(server_app) if block_given? rescue => e - raise CriticalDeployError.new(e, "Could not stop #{@name}") + raise DaemonError.new(e, "Could not stop #{@name}") end end end end ## # Restarts the daemon using the restart_cmd attribute if provided. # If restart_cmd is not provided, calls stop and start. def restart self.setup unless has_setup? Sunshine.logger.info @name, "Restarting #{@name} daemon" do each_server_app do |server_app| begin server_app.shell.call restart_cmd, :sudo => pick_sudo(server_app.shell) yield(server_app) if block_given? rescue => e - raise CriticalDeployError.new(e, "Could not restart #{@name}") + raise DaemonError.new(e, "Could not restart #{@name}") end end end end ## # Gets the command that starts the daemon. # Should be overridden by child classes. def start_cmd return @start_cmd || - raise(CriticalDeployError, "@start_cmd undefined. Can't start #{@name}") + raise(DaemonError, "@start_cmd undefined. Can't start #{@name}") end ## # Default daemon stop command. def stop_cmd "test -f #{@pid} && kill -#{@sigkill} $(cat #{@pid}) && sleep 1 && "+ "rm -f #{@pid} || echo 'Could not kill #{@name} pid for #{@app.name}';" end ## # Gets the command that restarts the daemon. def restart_cmd @restart_cmd || [stop_cmd, start_cmd].map{|c| "(#{c})"}.join(" && ") end ## # Get the command to check if the daemon is running. def status_cmd @status_cmd || "test -f #{@pid} && kill -0 $(cat #{@pid})" end ## # Append or override daemon log file paths: # daemon.log_files :stderr => "/all_logs/stderr.log" def log_files hash @log_files.merge!(hash) end ## # Get the path of a log file: # daemon.log_file(:stderr) # #=> "/all_logs/stderr.log" def log_file key @log_files[key] end ## # Get the file path to the daemon's config file. def config_file_path "#{@config_path}/#{@config_file}" end ## # Upload config files and run them through erb with the provided # binding if necessary. def upload_config_files shell, setup_binding=binding config_template_files.each do |config_file| if File.extname(config_file) == ".erb" filename = File.basename(config_file[0..-5]) parsed_config = @app.build_erb(config_file, setup_binding) shell.make_file "#{@config_path}/#{filename}", parsed_config else filename = File.basename(config_file) shell.upload config_file, "#{@config_path}/#{filename}" end end end ## # Get the array of local config template files needed by the daemon. def config_template_files @config_template_files ||= Dir[@config_template].select{|f| File.file?(f)} end ## # Create and setup a binding for a given shell. def config_binding shell binder = Binder.new self binder.forward(*self.class.binder_methods) binder.set :shell, shell binder_sudo = pick_sudo(shell) binder.set :sudo, binder_sudo binder.set :expand_path do |path| shell.expand_path path end binder end ## # Pick which sudo to use between the daemon sudo and shell sudo. # (Useful when running servers on ports < 1024) def pick_sudo shell self.sudo.nil? ? shell.sudo : self.sudo end ## # Make sure all the remote directories needed by the daemon exist. def configure_remote_dirs shell dirs = @log_files.values.map{|f| File.dirname(f)} dirs << File.dirname(@pid) dirs << @config_path dirs.delete_if{|d| d == "."} dirs = dirs.join(" ") shell.call "mkdir -p #{dirs}" end ## # Make sure log files are owned by the daemon's user. def touch_log_files shell files = @log_files.values.join(" ") sudo = pick_sudo(shell) user = case sudo when true then 'root' when String then sudo else nil end shell.call "touch #{files}", :sudo => true shell.call "chown #{user} #{files}", :sudo => true if user end ## # Setup what should be run after the user block on App#deploy. def register_after_user_script @app.after_user_script do |app| next unless has_setup? each_server_app do |sa| sudo = pick_sudo sa.shell %w{start stop restart status}.each do |script| script_file = "#{@config_path}/#{script}" cmd = send "#{script}_cmd".to_sym sa.shell.make_file script_file, cmd, :flags => '--chmod=ugo=rwx' cmd = sa.shell.sudo_cmd "#{@app.root_path}/env #{script_file}", sudo sa.scripts[script.to_sym] << [*cmd].join(" ") end end end end end end diff --git a/lib/sunshine/dependency_lib.rb b/lib/sunshine/dependency_lib.rb index 1d34d58..ddc217e 100644 --- a/lib/sunshine/dependency_lib.rb +++ b/lib/sunshine/dependency_lib.rb @@ -1,218 +1,216 @@ module Sunshine ## # DependencyLib is a simple class for building and handling depenedencies. # A dependency tree can be defined by inheriting the DependencyLib class, and # dependencies can be defined through dependency instantiation methods: # # dependency_lib.instance_eval do # # yum 'ruby', :pkg => 'ruby-devel' # # yum 'rubygems', :requires => 'ruby' # # gem 'rdoc', :requires => 'rubygems' # # gem 'ri', :requires => 'rubygems' # # end # # Calling the install for rdoc will then check and install all of its parent # dependencies as well: # # dependency_lib.install 'rdoc', 'ri' # # Dependencies may also be generic and/or have custom bash scripts # for installs, uninstalls, and presence checks: # # dependency 'custom' do # requires 'yum', 'ruby' # install 'sudo yum install custom' # uninstall 'sudo yum remove custom' # check 'yum list installed custom' # end # # See the Dependency class for more information. class DependencyLib - class MissingDependency < Exception; end - ## # Array of all dependency classes. Appended to automatically when # DependencyLib::Dependency is inherited. def self.dependency_types @dependency_types ||= [] end ## # Registers a new dependency class, creates its constructor method # (DependencyLib#[dep_class.short_name]). def self.register_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}(name, options={}, &block) dep = #{dep_class}.new(name, options.merge(:tree => self), &block) self.add dep dep end STR dependency_types << dep_class end ## # Define if sudo should be used def self.sudo= value dependency_types.each do |dep_class| dep_class.sudo = value end end attr_reader :dependencies def initialize @dependencies = Hash.new end ## # Returns a dependency hash by type: # DependencyLib['name'] #=> {:yum => <Yum...>, :apt => <Apt...>, ...} def [](key) @dependencies[key] end ## # Add a dependency to the dependencies hash. def add dep (@dependencies[dep.name] ||= []).unshift dep end ## # Checks for the existance of a dependency by name def exist? key @dependencies.has_key? key end ## # Get a dependency object by name. Supports passing :type => :pkg_manager # if dependencies with the same name but different package managers exist: # dependencies.get 'daemon', :type => Gem # #=> <Gem @name="daemon"...> # # For an 'nginx' dependency defined for both apt and yum, where the yum # dependency object was added to the tree last. Returns nil if # no matching dependency type is found: # dependencies.get 'nginx' # #=> <Yum @name="nginx"...> # # dependencies.get 'nginx', :type => Apt # #=> <Apt @name="nginx"...> # # Use the :prefer option if a certain dependency type is prefered but # will fall back to whatever first dependency is available: # dependencies.yum 'my_dep' # dependencies.get 'my_dep', :prefer => Apt # #=> <Yum @name="my_dep"...> # # Both the :type and the :prefer options support passing arrays to search # from best to least acceptable candidate: # dependencies.yum 'my_dep' # dependencies.apt 'my_dep' # dependencies.get 'my_dep', :type => [Tpkg, Yum] # #=> <Yum @name="my_dep"...> def get name, options={} return unless exist? name deps = @dependencies[name] dep_types = [*(options[:type] || options[:prefer])].compact return deps.first if dep_types.empty? dep_types.each do |dep_type| deps.each do |dep| return dep if dep_type === dep end end return deps.first unless options[:type] end ## # Install one or more dependencies: # # dependencies.install 'dep1', 'dep2', options_hash # # See DependencyLib#get and Dependency#install! for supported options. # # Note: If a Dependency object is passed and the :type option is set, # DependencyLib will attempt to find and install a dependency of class :type # with the same name as the passed Dependency object: # my_dep = dependencies.yum "my_dep_yum_only" # dependencies.install my_dep, :type => Apt # #=> "No dependency 'my_dep' [Sunshine::Apt]" def install(*deps) send_each(:install!, *deps) end ## # Uninstall one or more dependencies: # # dependencies.uninstall 'dep1', 'dep2', options_hash # # See DependencyLib#get and Dependency#uninstall! for supported options. def uninstall(*deps) send_each(:uninstall!, *deps) end ## # Get and call method on each dependency passed def send_each(method, *deps) options = Hash === deps.last ? deps.delete_at(-1).dup : {} #if options[:call].respond_to? :pkg_manager # options[:prefer] ||= options[:call].pkg_manager #end deps.each do |dep_name| dep = if Dependency === dep_name if options[:type] && !(options[:type] === dep_name) get(dep_name.name, options) else dep_name end else get(dep_name, options) end raise MissingDependency, "No dependency '#{dep_name}' [#{options[:type] || "any"}]" if !dep # Remove :type so dependencies of other types than dep can be installed options.delete(:type) dep.send method, options end end end end diff --git a/lib/sunshine/exceptions.rb b/lib/sunshine/exceptions.rb index d1041a8..20c9514 100644 --- a/lib/sunshine/exceptions.rb +++ b/lib/sunshine/exceptions.rb @@ -1,51 +1,72 @@ module Sunshine ## # A standard sunshine exception class Exception < StandardError def initialize input=nil, message=nil if ::Exception === input message = [message, input.message].compact.join(": ") super(message) self.set_backtrace(input.backtrace) else super(input) end end end ## # An error occurred when attempting to run a command on the local system class CmdError < Exception; attr_reader :exit_code def initialize exit_code, cmd=nil message = "Execution failed with status #{exit_code}: #{cmd}" super message @exit_code = exit_code end end + ## + # A shell command timed out. + class TimeoutError < Exception; end + + + ## + # Remote connection to server failed. + class ConnectionError < Exception; end + + ## # Something went wrong with a deploy-specific item. class DeployError < Exception; end ## - # The error is serious enough that deploy cannot proceed. - # Sunshine will attempt to revert to a previous deploy if available. - class CriticalDeployError < DeployError; end + # Something went wrong with a daemon-specific item. + class DaemonError < Exception; end ## - # The error is so serious that no more action can be taken. - # Sunshine will attempt to close any ssh connections and stop the deploy. - class FatalDeployError < DeployError; end + # Something went wrong with a dependency-specific item. + class DependencyError < Exception; end + ## - # A dependency could not be installed. - class DependencyError < FatalDeployError; end + # Dependency requested could not be found. + class MissingDependency < DependencyError; end + + ## + # Dependency failed to install. + class InstallError < DependencyError; end + + ## + # Dependency failed to uninstall. + class UninstallError < DependencyError; end + + ## + # Something went wrong with a scm-specific item. + class RepoError < Exception; end end diff --git a/lib/sunshine/package_managers/dependency.rb b/lib/sunshine/package_managers/dependency.rb index 9c44fef..e1b3d93 100644 --- a/lib/sunshine/package_managers/dependency.rb +++ b/lib/sunshine/package_managers/dependency.rb @@ -1,356 +1,352 @@ module Sunshine ## # Dependency objects let you define how to install, check, and remove # a described package, including parent dependency lookup and installation. # # Dependency.new "ruby", :tree => dependency_lib do # install "sudo yum install ruby" # uninstall "sudo yum remove ruby" # check_test "yum list installed ruby | grep -c ruby", "-ge 1" # end # # Dependencies are more commonly defined through a Settler class' # constructor methods: # # dependency_lib.instance_eval do # dependency 'custom' do # requires 'yum', 'ruby' # install 'sudo yum install custom' # uninstall 'sudo yum remove custom' # check 'yum list installed custom' # end # end # # The Dependency class is simple to inherit and use as a built-in part of # Settler (see the Yum implementation for more info): # # class Yum < Dependency # def initialize(name, options={}, &block) # super(dep_lib, name, options) do # # Define install, check, and uninstall scripts specific to yum # end # end # ... # end # # Once a subclass is defined a constructor method is added automatically # to the Settler class: # # dependency_lib.instance_eval do # yum "ruby", :version => '1.9' # end class Dependency - class InstallError < Exception; end - class UninstallError < Exception; end - - ## # Check if sudo should be used def self.sudo @sudo ||= nil end ## # Assign a sudo value. A value of nil means 'don't assign sudo', # true means sudo, string means sudo -u, false means, explicitely # don't use sudo. Yum and Gem dependency types default to sudo=true. def self.sudo= value @sudo = value end ## # Checks if dependency type is valid for a given shell. # Defaults to false. Override in subclass. def self.system_manager? shell=nil false end attr_reader :name, :pkg, :parents, :children def initialize name, options={}, &block @dependency_lib = options[:tree] @name = name.to_s @pkg = options[:pkg] || @name @options = options.dup @install = nil @uninstall = nil @check = nil @parents = [] @children = [] @shell = Sunshine.shell requires(*options[:requires]) if options[:requires] instance_eval(&block) if block_given? end ## # Append a child dependency def add_child name @children << name end ## # Get direct child dependencies def child_dependencies @children end ## # Define the command that checks if the dependency is installed. # The check command must have an appropriate exitcode: # # dep.check "test -s 'yum list installed depname'" def check cmd_str=nil, &block @check = cmd_str || block end ## # Define checking that the dependency is installed via unix's 'test': # # dep.check_test "yum list installed depname | grep -c depname", "-ge 1" def check_test cmd_str, condition_str check "test \"$(#{cmd_str})\" #{condition_str}" end ## # Define the install command for the dependency: # # dep.install "yum install depname" def install cmd=nil, &block @install = cmd || block end ## # Run the install command for the dependency # Allows options: # :call:: obj - an object that responds to call will be passed the bash cmd # :skip_parents:: true - install regardless of missing parent dependencies # # runner = lambda{|str| system(str)} # dep.install! :call => runner def install! options={} return if installed?(options) if options[:skip_parents] missing = missing_parents? if missing raise(InstallError, "Could not install #{@name}. "+ "Missing dependencies #{missing.join(", ")}") end else install_parents!(options) end run_command(@install, options) raise(InstallError, "Failed installing #{@name}") unless installed?(options) end ## # Call install on direct parent dependencies # Allows options: # :call:: obj - an object that responds to call will be passed the bash cmd # # runner = lambda{|str| system(str)} # dep.install_parents! :call => runner def install_parents! options={} return unless @dependency_lib @parents.each do |dep| @dependency_lib.get(dep, options).install!(options) end end ## # Run the check command to verify that the dependency is installed # Allows options: # :call:: obj - an object that responds to call will be passed the bash cmd # # runner = lambda{|str| system(str)} # dep.installed? :call => runner def installed? options={} run_command @check, options rescue => e false end ## # Checks if any parents dependencies are missing # Allows options: # :call:: obj - an object that responds to call will be passed the bash cmd # # runner = lambda{|str| system(str)} # dep.missing_parents? :call => runner def missing_parents? options={} return unless @dependency_lib missing = [] @parents.each do |dep| parent_dep = @dependency_lib.get dep, options missing << dep unless parent_dep.installed?(options) return missing if options[:limit] && options[:limit] == missing.length end missing.empty? ? nil : missing end ## # Get direct parent dependencies def parent_dependencies @parents end ## # Define which dependencies this dependency relies on: # # dep.requires 'rubygems', 'rdoc' def requires *deps return unless @dependency_lib @parents.concat(deps).uniq! deps.each do |dep| @dependency_lib.dependencies[dep].each{|d| d.add_child(@name) } end end ## # Define the uninstall command for the dependency: # # dep.uninstall "yum remove depname" def uninstall cmd=nil, &block @uninstall = cmd || block end ## # Run the uninstall command for the dependency # Allows options: # :call:: obj - an object that responds to call will be passed the bash cmd # :force:: true - uninstalls regardless of child dependencies # :remove_children:: true - removes direct child dependencies # :remove_children:: :recursive - removes children recursively def uninstall! options={} if !options[:remove_children] && !options[:force] raise UninstallError, "The #{@name} has child dependencies." end uninstall_children!(options) if options[:remove_children] run_command(@uninstall, options) raise(UninstallError, "Failed removing #{@name}") if installed?(options) end ## # Removes child dependencies # Allows options: # :call:: obj - an object that responds to call will be passed the bash cmd # :force:: true - uninstalls regardless of child dependencies # :remove_children:: true - removes direct child dependencies # :remove_children:: :recursive - removes children recursively def uninstall_children! options={} return unless @dependency_lib options = options.dup @children.each do |dep| options.delete(:remove_children) unless options[:remove_children] == :recursive @dependency_lib.get(dep, options).uninstall!(options) end end ## # Alias for name def to_s @name end private def run_command command, options={} shell = options[:call] || @shell if Proc === command command.call shell, self.class.sudo else shell.call command, :sudo => self.class.sudo end end ## # Returns an underscored short version of the class name: # Sunshine::Yum.short_name # #=> "yum" def self.short_name @short_name ||= underscore self.name.to_s.split(":").last end def self.underscore str str.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2').downcase end ## # Auto register the new Dependency class with DependencyLib and ServerApp # when inherited. def self.inherited subclass DependencyLib.register_type subclass ServerApp.register_dependency_type subclass end inherited self end end diff --git a/lib/sunshine/remote_shell.rb b/lib/sunshine/remote_shell.rb index 2c349f0..0efebd2 100644 --- a/lib/sunshine/remote_shell.rb +++ b/lib/sunshine/remote_shell.rb @@ -1,274 +1,272 @@ module Sunshine ## # Keeps an SSH connection open to a server the app will be deployed to. # Deploy servers use the ssh command and support any ssh feature. # By default, deploy servers use the ControlMaster feature to share # socket connections, with the ControlPath = ~/.ssh/sunshine-%r%h:%p # # Setting session-persistant environment variables is supported by # accessing the @env attribute. class RemoteShell < Shell - class ConnectionError < FatalDeployError; end - ## # The loop to keep the ssh connection open. LOGIN_LOOP = "echo ok; echo ready; "+ "for (( ; ; )); do kill -0 $PPID && sleep 10 || exit; done;" LOGIN_TIMEOUT = 30 ## # Closes all remote shell connections. def self.disconnect_all return unless defined?(@remote_shells) @remote_shells.each{|rs| rs.disconnect} end ## # Registers a remote shell for global access from the class. # Handled automatically on initialization. def self.register remote_shell (@remote_shells ||= []) << remote_shell end attr_reader :host, :user, :pid attr_accessor :ssh_flags, :rsync_flags ## # Remote shells essentially need a host and optional user. # Typical instantiation is done through either of these methods: # RemoteShell.new "user@host" # RemoteShell.new "host", :user => "user" # # The constructor also supports the following options: # :env:: hash - hash of environment variables to set for the ssh session # :password:: string - password for ssh login; if missing the deploy server # will attempt to prompt the user for a password. def initialize host, options={} super $stdout, options @host, @user = host.split("@").reverse @user ||= options[:user] @rsync_flags = ["-azP"] @rsync_flags.concat [*options[:rsync_flags]] if options[:rsync_flags] @ssh_flags = [ "-o ControlMaster=auto", "-o ControlPath=~/.ssh/sunshine-%r@%h:%p" ] @ssh_flags.concat ["-l", @user] if @user @ssh_flags.concat [*options[:ssh_flags]] if options[:ssh_flags] @pid, @inn, @out, @err = nil self.class.register self end ## # Runs a command via SSH. Optional block is passed the # stream(stderr, stdout) and string data. def call command_str, options={}, &block Sunshine.logger.info @host, "Running: #{command_str}" do execute build_remote_cmd(command_str, options), &block end end ## # Connect to host via SSH and return process pid def connect return true if connected? cmd = ssh_cmd quote_cmd(LOGIN_LOOP), :sudo => false @pid, @inn, @out, @err = popen4 cmd.join(" ") @inn.sync = true data = "" ready = nil start_time = Time.now.to_i until ready || @out.eof? data << @out.readpartial(1024) ready = data =~ /ready/ raise TimeoutError if timed_out?(start_time, LOGIN_TIMEOUT) end unless connected? disconnect host_info = [@user, @host].compact.join("@") raise ConnectionError, "Can't connect to #{host_info}" end @inn.close @pid end ## # Check if SSH session is open and returns process pid def connected? Process.kill(0, @pid) && @pid rescue false end ## # Disconnect from host def disconnect @inn.close rescue nil @out.close rescue nil @err.close rescue nil kill_process @pid, "HUP" rescue nil @pid = nil end ## # Download a file via rsync def download from_path, to_path, options={}, &block from_path = "#{@host}:#{from_path}" Sunshine.logger.info @host, "Downloading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Expand a path: # shell.expand_path "~user/thing" # #=> "/home/user/thing" def expand_path path dir = File.dirname path full_dir = call "cd #{dir} && pwd" File.join full_dir, File.basename(path) end ## # Checks if the given file exists def file? filepath syscall "test -f #{filepath}" end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " cmd = quote_cmd cmd pid = fork do exec \ ssh_cmd(sudo_cmd(env_cmd(cmd)), :flags => "-t").to_a.join(" ") end Process.waitpid pid end end ## # Create a file remotely def make_file filepath, content, options={} temp_filepath = "#{TMP_DIR}/#{File.basename(filepath)}_#{Time.now.to_i}#{rand(10000)}" File.open(temp_filepath, "w+"){|f| f.write(content)} self.upload temp_filepath, filepath, options File.delete(temp_filepath) end ## # Builds an ssh command with permissions, env, etc. def build_remote_cmd cmd, options={} cmd = sh_cmd cmd cmd = env_cmd cmd cmd = sudo_cmd cmd, options cmd = ssh_cmd cmd, options end ## # Uploads a file via rsync def upload from_path, to_path, options={}, &block to_path = "#{@host}:#{to_path}" Sunshine.logger.info @host, "Uploading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Figure out which rsync flags to use. def build_rsync_flags options flags = @rsync_flags.dup remote_rsync = 'rsync' rsync_sudo = sudo_cmd remote_rsync, options unless rsync_sudo == remote_rsync flags << "--rsync-path='#{ rsync_sudo.join(" ") }'" end flags << "-e \"ssh #{@ssh_flags.join(' ')}\"" if @ssh_flags flags.concat [*options[:flags]] if options[:flags] flags end ## # Creates an rsync command. def rsync_cmd from_path, to_path, options={} cmd = ["rsync", build_rsync_flags(options), from_path, to_path] cmd.flatten.compact.join(" ") end ## # Wraps the command in an ssh call. def ssh_cmd cmd, options=nil options ||= {} flags = [*options[:flags]].concat @ssh_flags ["ssh", flags, @host, cmd].flatten.compact end end end diff --git a/lib/sunshine/repo.rb b/lib/sunshine/repo.rb index 6325efe..25edad6 100644 --- a/lib/sunshine/repo.rb +++ b/lib/sunshine/repo.rb @@ -1,149 +1,147 @@ module Sunshine - class RepoError < Exception; end - ## # An abstract class to wrap simple basic scm features. The primary function # of repo objects is to get information about the scm branch that is being # deployed and to check it out on remote deploy servers: # svn = SvnRepo.new "svn://path/to/repo", :flags => "--ignore-externals" # # The :flags option can be a String or an Array and supports any scm # checkout (or clone for git) options. class Repo ## # Adds subclasses to a repo_types hash for easy def self.inherited subclass @@repo_types ||= {} # Turn Sunshine::ScmNameRepo into :scm_name class_key = subclass.to_s.split("::").last class_key = $1 if class_key =~ /(\w+)Repo$/ class_key.gsub!(/([a-z0-9])([A-Z])/, '\1_\2') class_key = class_key.downcase @@repo_types[class_key] = subclass end ## # Creates a new repo subclass object: # Repo.new_of_type :svn, "https://path/to/repo/tags/releasetag" # Repo.new_of_type :git, "[email protected]:repo/path" def self.new_of_type repo_type, url, options={} repo_class = @@repo_types[repo_type.to_s] raise RepoError, "Invalid type #{repo_type.inspect}" unless repo_class repo_class.new(url, options) end ## # Looks for .git and .svn directories and determines if the passed path # is a recognized repo. Does not check for RsyncRepo since it's a # special case. Returns the appropriate repo object: # Repo.detect "path/to/svn/repo/dir" # #=> <SvnRepo @url="svn://url/of/checked/out/repo"> # Repo.detect "path/to/git/repo/dir" # #=> <GitRepo, @url="git://url/of/git/repo", @branch="master"> # Repo.detect "invalid/repo/path" # #=> nil def self.detect path=".", shell=nil @@repo_types.values.each do |repo| if repo.valid? path info = repo.get_info path, shell return repo.new(info[:url], info) end end nil end ## # Gets repo information for the specified dir - Implemented by subclass def self.get_info path=".", shell=nil raise RepoError, "The 'get_info' method must be implemented by child classes" end ## # Checks if current working directory is a valid repo. # Defaults to false. Subclasses must override this method to enable # auto detecting of a given scm implementation. def self.valid? *args false end attr_reader :url, :scm def initialize url, options={} @scm = self.class.name.split("::").last.sub('Repo', '').downcase @url = url.to_s @flags = [*options[:flags]].compact end ## # Checkout code to a shell and return an info log hash: # repo.chekout_to "some/path", remote_shell # #=> {:revision => 123, :committer => 'someone', :date => time_obj ...} def checkout_to path, shell=nil shell ||= Sunshine.shell shell.call "test -d #{path} && rm -rf #{path} || echo false" shell.call "mkdir -p #{path}" do_checkout path, shell get_repo_info path, shell end ## # Checkout the repo - implemented by subclass def do_checkout path, shell raise RepoError, "The 'do_checkout' method must be implemented by child classes" end ## # Get the project name of the specified repo - implemented by subclass def name raise RepoError, "The 'name' method must be implemented by child classes" end ## # Returns the set scm flags as a string def scm_flags @flags.join(" ") end ## # Returns the repo information as a hash. def get_repo_info path=".", shell=nil defaults = {:type => @scm, :url => @url, :path => path} defaults.merge self.class.get_info(path, shell) end end end diff --git a/lib/sunshine/shell.rb b/lib/sunshine/shell.rb index b2b2137..e242531 100644 --- a/lib/sunshine/shell.rb +++ b/lib/sunshine/shell.rb @@ -1,434 +1,432 @@ module Sunshine ## # The Shell class handles local input, output and execution to the shell. class Shell include Open4 - class TimeoutError < CriticalDeployError; end - LOCAL_USER = `whoami`.chomp LOCAL_HOST = `hostname`.chomp SUDO_FAILED = /^Sorry, try again./ SUDO_PROMPT = /^Password:/ attr_reader :user, :host, :password, :input, :output, :mutex attr_accessor :env, :sudo, :timeout def initialize output = $stdout, options={} @output = output $stdin.sync @input = HighLine.new $stdin @user = LOCAL_USER @host = LOCAL_HOST @sudo = options[:sudo] @env = options[:env] || {} @password = options[:password] @timeout = options[:timeout] || Sunshine.timeout @mutex = nil end ## # Checks for equality def == shell @host == shell.host && @user == shell.user rescue false end ## # Prompt the user for input. def ask(*args, &block) sync{ @input.ask(*args, &block) } end ## # Prompt the user to agree. def agree(*args, &block) sync{ @input.agree(*args, &block) } end ## # Execute a command on the local system and return the output. def call cmd, options={}, &block Sunshine.logger.info @host, "Running: #{cmd}" do execute sudo_cmd(cmd, options), &block end end ## # Prompt the user to make a choice. def choose &block sync{ @input.choose(&block) } end ## # Close the output IO. (Required by the Logger class) def close @output.close end ## # Returns true. Compatibility method with RemoteShell. def connect true end ## # Returns true. Compatibility method with RemoteShell. def connected? true end ## # Returns true. Compatibility method with RemoteShell. def disconnect true end ## # Copies a file. Compatibility method with RemoteShell. def download from_path, to_path, options={}, &block Sunshine.logger.info @host, "Copying #{from_path} -> #{to_path}" do FileUtils.cp_r from_path, to_path end end alias upload download ## # Expands the path. Compatibility method with RemoteShell. def expand_path path File.expand_path path end ## # Checks if file exists. Compatibility method with RemoteShell. def file? filepath File.file? filepath end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " pid = fork do exec sudo_cmd(env_cmd(cmd)).to_a.join(" ") end Process.waitpid pid end end ## # Write a file. Compatibility method with RemoteShell. def make_file filepath, content, options={} File.open(filepath, "w+"){|f| f.write(content)} end ## # Get the name of the OS def os_name @os_name ||= call("uname -s").strip.downcase end ## # Prompt the user for a password def prompt_for_password host_info = [@user, @host].compact.join("@") @password = ask("#{host_info} Password:") do |q| q.echo = false end end ## # Build an env command if an env_hash is passed def env_cmd cmd, env_hash=@env if env_hash && !env_hash.empty? env_vars = env_hash.map{|e| e.join("=")} cmd = ["env", env_vars, cmd].flatten end cmd end ## # Wrap command in quotes and escape as needed. def quote_cmd cmd cmd = [*cmd].join(" ") "'#{cmd.gsub(/'/){|s| "'\\''"}}'" end ## # Build an sh -c command def sh_cmd cmd ["sh", "-c", quote_cmd(cmd)] end ## # Build a command with sudo. # If sudo_val is nil, it is considered to mean "pass-through" # and the default shell sudo will be used. # If sudo_val is false, the cmd will be returned unchanged. # If sudo_val is true, the returned command will be prefaced # with sudo -H # If sudo_val is a String, the command will be prefaced # with sudo -H -u string_value def sudo_cmd cmd, sudo_val=nil sudo_val = sudo_val[:sudo] if Hash === sudo_val sudo_val = @sudo if sudo_val.nil? case sudo_val when true ["sudo", "-H", cmd].flatten when String ["sudo", "-H", "-u", sudo_val, cmd].flatten else cmd end end ## # Force symlinking a directory. def symlink target, symlink_name call "ln -sfT #{target} #{symlink_name}" rescue false end ## # Synchronize a block with the current mutex if it exists. def sync if @mutex @mutex.synchronize{ yield } else yield end end ## # Returns true if command was run successfully, otherwise returns false. def syscall cmd, options=nil call(cmd, options) && true rescue false end ## # Checks if timeout occurred. def timed_out? start_time, max_time=@timeout return unless max_time Time.now.to_i - start_time.to_i > max_time end ## # Execute a block while setting the shell's mutex. # Sets the mutex to its original value on exit. # Executing commands with a mutex is used for user prompts. def with_mutex mutex old_mutex, @mutex = @mutex, mutex yield @mutex = old_mutex end ## # Runs the passed block within a connection session. # If the shell is already connected, connecting and disconnecting # is ignored; otherwise, the session method will ensure that # the shell's connection gets closed after the block has been # executed. def with_session prev_connection = connected? connect unless prev_connection yield disconnect unless prev_connection end ## # Write string to stdout (by default). def write str @output.write str end alias << write ## # Execute a command with open4 and loop until the process exits. # The cmd argument may be a string or an array. If a block is passed, # it will be called when data is received and passed the stream type # and stream string value: # shell.execute "test -s 'blah' && echo 'true'" do |stream, str| # stream #=> :stdout # string #=> 'true' # end # # The method returns the output from the stdout stream by default, and # raises a CmdError if the exit status of the command is not zero. def execute cmd cmd = [cmd] unless Array === cmd pid, inn, out, err = popen4(*cmd) inn.sync = true log_methods = {out => :debug, err => :error} result, status = process_streams(pid, out, err) do |stream, data| stream_name = :out if stream == out stream_name = :err if stream == err stream_name = :inn if stream == inn # User blocks should run with sync threads to avoid badness. sync do Sunshine.logger.send log_methods[stream], "#{@host}:#{stream_name}", data yield(stream_name, data, inn) if block_given? end if password_required?(stream_name, data) then kill_process(pid) unless Sunshine.interactive? send_password_to_stream(inn, data) end end raise_command_failed(status, cmd) unless status.success? result[out].join.chomp ensure inn.close rescue nil out.close rescue nil err.close rescue nil end private def raise_command_failed(status, cmd) err = CmdError.new status.exitstatus, [*cmd].join(" ") raise err end def password_required? stream_name, data stream_name == :err && data =~ SUDO_PROMPT end def send_password_to_stream inn, data prompt_for_password if data =~ SUDO_FAILED inn.puts @password || prompt_for_password end def kill_process pid, kill_type="KILL" begin Process.kill kill_type, pid Process.wait rescue end end def process_streams pid, *streams result = Hash.new{|h,k| h[k] = []} start_time = Time.now # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 raise TimeoutError if timed_out? start_time next if selected.nil? or selected.empty? selected.each do |stream| start_time = Time.now if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) yield(stream, data) result[stream] << data end end return result, status end end end diff --git a/test/unit/test_app.rb b/test/unit/test_app.rb index 7521c34..2330efc 100644 --- a/test/unit/test_app.rb +++ b/test/unit/test_app.rb @@ -1,600 +1,599 @@ require 'test/test_helper' class TestApp < Test::Unit::TestCase def setup mock_remote_shell_popen4 @svn_url = "svn://subversion/path/to/app_name/trunk" @config = { :name => "app_name", :remote_checkout => true, :repo => {:type => "svn", :url => @svn_url}, :remote_shells => ["user@some_server.com", ["server2.com", {:roles => "web db"}]], :root_path => "/usr/local/my_user/app_name"} @app = Sunshine::App.new @config @app.each do |server_app| server_app.extend MockObject server_app.shell.extend MockObject end @tmpdir = File.join Dir.tmpdir, "test_sunshine_#{$$}" mock_svn_response @app.repo.url end def teardown FileUtils.rm_rf @tmpdir end def test_initialize_without_name app = Sunshine::App.new :repo => {:type => "svn", :url => @svn_url}, :remote_shells => ["user@some_server.com"] assert_equal "app_name", app.name end def test_initialize_with_config_file app = Sunshine::App.new TEST_APP_CONFIG_FILE config = YAML.load_file(TEST_APP_CONFIG_FILE)[:default] assert_attributes_equal config, app end def test_initialize_with_file_object file = File.open TEST_APP_CONFIG_FILE app = Sunshine::App.new file config = YAML.load_file(TEST_APP_CONFIG_FILE)[:default] assert_attributes_equal config, app end def test_initialize_with_options assert_attributes_equal @config, @app end def test_initialize_with_options_and_config_file app = Sunshine::App.new TEST_APP_CONFIG_FILE, @config assert_attributes_equal @config, app end def test_app_deploy yield_called = false @app.deploy do |app| assert app.connected? yield_called = true end assert [email protected]? setup_cmd = "test -d #{@app.checkout_path} && rm -rf #{@app.checkout_path}"+ " || echo false" mkdir_cmd = "mkdir -p #{@app.checkout_path}" checkout_cmd = "svn checkout " + "#{@app.repo.scm_flags} #{@app.repo.url} #{@app.checkout_path}" run_results = [ "mkdir -p #{@app.server_apps.first.directories.join(" ")}", setup_cmd, mkdir_cmd, checkout_cmd, "ln -sfT #{@app.checkout_path} #{@app.current_path}" ] @app.each do |server_app| use_remote_shell server_app.shell run_results.each_index do |i| assert_ssh_call run_results[i] end end assert yield_called end TEST_CONFIG = <<-STR :conf1: :common: "conf1" :from_conf1: true :not_conf4: "conf1" :conf2: :inherits: :conf1 :common: "conf2" :from_conf2: true :not_conf4: "conf2" :conf3: :common: "conf3" :from_conf3: true :not_conf4: "conf3" :conf4: :inherits: - :conf2 - :conf3 :common: "conf4" :from_conf4: true STR def test_merge_config_inheritance all_configs = YAML.load TEST_CONFIG main_conf = all_configs[:conf2] main_conf = @app.send(:merge_config_inheritance, main_conf, all_configs) assert main_conf[:from_conf1] assert_equal "conf2", main_conf[:common] end def test_multiple_merge_config_inheritance all_configs = YAML.load TEST_CONFIG main_conf = all_configs[:conf4] main_conf = @app.send(:merge_config_inheritance, main_conf, all_configs) assert main_conf[:from_conf1] assert main_conf[:from_conf2] assert main_conf[:from_conf3] assert_equal "conf4", main_conf[:common] assert_equal "conf3", main_conf[:not_conf4] end class MockError < Exception; end def test_app_deploy_error_handling [ MockError, - Sunshine::CriticalDeployError, - Sunshine::FatalDeployError ].each do |error| + Sunshine::DeployError ].each do |error| begin app = Sunshine::App.deploy @config do |app| raise error, "#{error} was not caught" end rescue MockError => e assert_equal MockError, e.class end end end def test_revert set_mock_response_for @app, 0, "ls -rc1 #{@app.deploys_path}" => [:out, "last_deploy_dir"] @app.revert! @app.each do |sa| use_remote_shell sa.shell assert_ssh_call "rm -rf #{@app.checkout_path}" assert_ssh_call "ls -rc1 #{@app.deploys_path}" last_deploy = "#{@app.deploys_path}/last_deploy_dir" assert_ssh_call "ln -sfT #{last_deploy} #{@app.current_path}" end end def test_build_control_scripts scripts_list = %w{start stop restart custom env} @app.server_apps.each do |sa| sa.shell.mock :file?, :return => false end @app.add_to_script :start, "start script" @app.add_to_script :stop, "stop script" @app.add_to_script :custom, "custom script" @app.build_control_scripts each_remote_shell do |ds| scripts_list.each do |script| assert_rsync(/#{script}/, "#{ds.host}:#{@app.scripts_path}/#{script}") end end end def test_build_deploy_info_file @app.build_deploy_info_file each_remote_shell do |ds| assert_rsync(/info/, "#{ds.host}:#{@app.scripts_path}/info") end end def test_build_erb erb_file = File.join(@tmpdir, "tmp.erb") FileUtils.mkdir_p @tmpdir File.open(erb_file, "w+") do |f| f.write "<%= name %>" end name = "test name" local_name = @app.build_erb(erb_file, binding) app_name = @app.build_erb(erb_file) assert_equal name, local_name assert_equal @app.name, app_name end def test_call calls = 0 @app.call "test call", :sudo => true do |type, data, inn| calls += 1 end assert_equal calls, @app.server_apps.length args = ["test call", {:sudo => true}] @app.each do |server_app| assert server_app.shell.method_called?(:call, :args => args) end end def test_checkout_codebase @app.checkout_codebase each_remote_shell do |ds| path = @app.checkout_path setup_cmd = "test -d #{path} && rm -rf #{path} || echo false" url = @app.repo.url flags = @app.repo.scm_flags checkout_cmd = "svn checkout #{flags} #{url} #{path}" assert_ssh_call setup_cmd assert_ssh_call checkout_cmd end end def test_deployed? set_mock_response_for @app, 0, "cat #{@app.root_path}/info" => [:out, "---\n:deploy_name: '#{@app.deploy_name}'"] deployed = @app.deployed? state = true @app.server_apps.each do |sa| assert sa.method_called?(:deployed?) set_mock_response_for sa.shell, 0, "cat #{@app.current_path}/info" => [:out, "---\n:deploy_name: '#{@app.deploy_name}'"] state = false unless sa.deployed? end assert_equal state, deployed assert deployed end def test_install_deps nginx_dep = Sunshine.dependencies.get 'nginx' ruby_dep = Sunshine.dependencies.get 'ruby' yum_sudo = Sunshine::Yum.sudo check_nginx = "test \"$(yum list installed #{nginx_dep.pkg} | "+ "grep -c #{nginx_dep.pkg})\" -ge 1" check_ruby = "test \"$(yum list installed #{ruby_dep.pkg} | "+ "grep -c #{ruby_dep.pkg})\" -ge 1" set_mock_response_for @app, 1, "apt-get --version" => [:err, ""] set_mock_response_for @app, 0, "yum --version" => [:out, "1.0"] set_mock_response_for @app, 1, {check_nginx => [:err, ""], check_ruby => [:err, ""]}, {:sudo => yum_sudo} @app.install_deps 'ruby', nginx_dep each_remote_shell do |ds| [nginx_dep, ruby_dep].each do |dep| check = "test \"$(yum list installed #{dep.pkg} | grep -c #{dep.pkg})\" -ge 1" install = dep.instance_variable_get "@install" assert_ssh_call check, ds, :sudo => yum_sudo assert_ssh_call install, ds, :sudo => yum_sudo end end end def test_install_gem_deps rake_dep = Sunshine.dependencies.get 'rake' bundler_dep = Sunshine.dependencies.get 'bundler' gem_sudo = Sunshine::Gem.sudo checks = { rake_dep => "gem list #{rake_dep.pkg} -i --version '>=0.8'", bundler_dep => "gem list #{bundler_dep.pkg} -i --version '>=0.9'" } checks.values.each do |check| set_mock_response_for @app, 1, {check => [:err, ""]}, {:sudo => gem_sudo} end @app.install_deps 'rake', bundler_dep each_remote_shell do |ds| [rake_dep, bundler_dep].each do |dep| install = dep.instance_variable_get "@install" assert_ssh_call checks[dep], ds, :sudo => gem_sudo assert_ssh_call install, ds, :sudo => gem_sudo end end end def test_find_all app = Sunshine::App.new :repo => {:type => "svn", :url => @svn_url}, :remote_shells => [ "user@some_server.com", ["server2.com", {:roles => "web db"}] ] server_apps = app.server_apps assert_equal server_apps, app.find assert_equal server_apps, app.find({}) assert_equal server_apps, app.find(:all) assert_equal server_apps, app.find(nil) end def test_find app = Sunshine::App.new :repo => {:type => "svn", :url => @svn_url}, :remote_shells => [ "user@some_server.com", ["server2.com", {:roles => "web db"}] ] server_apps = app.server_apps assert_equal server_apps, app.find(:role => :web) assert_equal server_apps, app.find(:role => :db) assert_equal [server_apps[0]], app.find(:role => :all) assert_equal [server_apps[0]], app.find(:role => :blarg) assert_equal [server_apps[0]], app.find(:user => 'user') assert_equal [server_apps[0]], app.find(:host => 'some_server.com') assert_equal [server_apps[1]], app.find(:host => 'server2.com') end def test_make_app_directories @app.make_app_directories each_remote_shell do |ds| assert_ssh_call "mkdir -p #{@app.server_apps.first.directories.join(" ")}" end end def test_rake @app.rake("test:task") each_remote_shell do |ds| assert_ssh_call "cd #{@app.checkout_path} && rake test:task" end end def test_register_as_deployed @app.register_as_deployed each_remote_shell do |ds| assert_ssh_call "test -d #{@app.root_path}" yml_list = {@app.name => @app.root_path}.to_yaml path = ds.expand_path(Sunshine::APP_LIST_PATH) assert ds.method_called?(:make_file, :args => [path, yml_list]) end end def test_remove_old_deploys returned_dirs = %w{old_deploy1 old_deploy2 old_deploy3 main_deploy} old_deploys = returned_dirs[0..-2].map{|d| "#{@app.deploys_path}/#{d}"} list_cmd = "ls -rc1 #{@app.deploys_path}" rm_cmd = "rm -rf #{old_deploys.join(" ")}" set_mock_response_for @app, 0, list_cmd => [:out, returned_dirs.join("\n")] Sunshine.setup 'max_deploy_versions' => 1 @app.remove_old_deploys each_remote_shell do |ds| assert_ssh_call list_cmd assert_ssh_call rm_cmd end end def test_run_post_user_lambdas lambdas_ran = 0 count = 5 count.times do @app.after_user_script do |app| lambdas_ran = lambdas_ran.next end end assert_equal 0, lambdas_ran @app.run_post_user_lambdas assert_equal count, lambdas_ran end def test_shell_env new_env = { "PATH" => "/etc/lib:$PATH", "RACK_ENV" => "test", "RAILS_ENV" => "test" } @app.shell_env new_env assert_equal new_env, @app.shell_env end def test_symlink_current_dir @app.symlink_current_dir each_remote_shell do |ds| assert_ssh_call "ln -sfT #{@app.checkout_path} #{@app.current_path}" end end def test_threaded_each_errors err_host = "some_server.com" finished = 0 @app.threaded_each do |server_app| if server_app.shell.host == err_host - raise Sunshine::CriticalDeployError, server_app.shell.host + raise Sunshine::DeployError, server_app.shell.host else finished = finished.next end end raise "Didn't raise threaded error when it should have" - rescue Sunshine::CriticalDeployError => e + rescue Sunshine::DeployError => e host = @app.server_apps.first.shell.host assert_equal host, e.message assert_equal (@app.server_apps.length - 1), finished end def test_upload_tasks path = "/path/to/tasks" @app.upload_tasks 'common', 'tpkg', :host => 'some_server.com', :remote_path => path shell = @app.find(:host => 'some_server.com').first.shell use_remote_shell shell assert_ssh_call "mkdir -p /path/to/tasks" %w{common tpkg}.each do |task| from = "#{Sunshine::ROOT}/templates/tasks/#{task}.rake" to = "#{shell.host}:#{path}/#{task}.rake" assert_rsync from, to end end def test_upload_tasks_simple @app.upload_tasks path = "#{@app.checkout_path}/lib/tasks" tasks = Dir.glob("#{Sunshine::ROOT}/templates/tasks/*").map{|t| File.basename t} each_remote_shell do |ds| assert_ssh_call "mkdir -p #{path}" tasks.each do |task| from = "#{Sunshine::ROOT}/templates/tasks/#{task}" to = "#{ds.host}:#{path}/#{task}" assert_rsync from, to end end end def test_with_filter app = Sunshine::App.new :repo => {:type => "svn", :url => @svn_url}, :remote_shells => ["[email protected]", "[email protected]"] assert_equal 2, app.server_apps.length app.with_filter :host => 'server1.com' do |app| assert_equal 1, app.server_apps.length assert_equal 'server1.com', app.server_apps.first.shell.host end assert_equal 2, app.server_apps.length end def test_sudo_assignment @app.sudo = "someuser" @app.each do |server_app| assert_equal "someuser", server_app.shell.sudo end end private def assert_attributes_equal(attr_hash, app) assert_equal attr_hash[:name], app.name assert_equal attr_hash[:repo][:url], app.repo.url assert_equal attr_hash[:root_path], app.root_path attr_hash[:remote_shells].each_with_index do |server_def, i| shell = Sunshine::RemoteShell.new(*server_def) assert_equal shell, app.server_apps[i].shell end end end diff --git a/test/unit/test_daemon.rb b/test/unit/test_daemon.rb index 03d7923..9fdbd78 100644 --- a/test/unit/test_daemon.rb +++ b/test/unit/test_daemon.rb @@ -1,26 +1,26 @@ require 'test/test_helper' class TestDaemon < Test::Unit::TestCase def setup mock_remote_shell_popen4 @app = Sunshine::App.new(TEST_APP_CONFIG_FILE).extend MockObject @server_app = @app.server_apps.first.extend MockObject @app.server_apps.first.shell.extend MockObject use_remote_shell @server_app.shell end def test_missing_start_cmd daemon = Sunshine::Daemon.new @app begin daemon.start_cmd - raise "Should have thrown CriticalDeployError but didn't :(" - rescue Sunshine::CriticalDeployError => e + raise "Should have thrown DaemonError but didn't :(" + rescue Sunshine::DaemonError => e assert_equal "@start_cmd undefined. Can't start daemon", e.message end end end diff --git a/test/unit/test_server_app.rb b/test/unit/test_server_app.rb index 30a041f..03eeff0 100644 --- a/test/unit/test_server_app.rb +++ b/test/unit/test_server_app.rb @@ -1,489 +1,489 @@ require 'test_helper' class TestServerApp < Test::Unit::TestCase def setup mock_svn_response @app = mock_app @app.repo.extend MockObject @sa = Sunshine::ServerApp.new @app, mock_remote_shell @sa.extend MockObject use_remote_shell @sa.shell end def test_from_info_file info_data = @sa.get_deploy_info.to_yaml @sa.shell.mock :call, :args => "cat info/path", :return => info_data server_app = Sunshine::ServerApp.from_info_file "info/path", @sa.shell assert_equal @sa.root_path, server_app.root_path assert_equal @sa.checkout_path, server_app.checkout_path assert_equal @sa.current_path, server_app.current_path assert_equal @sa.deploys_path, server_app.deploys_path assert_equal @sa.log_path, server_app.log_path assert_equal @sa.shared_path, server_app.shared_path assert_equal @sa.scripts_path, server_app.scripts_path assert_equal @sa.roles, server_app.roles assert_equal @sa.shell.env, server_app.shell_env assert_equal @sa.name, server_app.name assert_equal @sa.deploy_name, server_app.deploy_name end def test_init default_info = {:ports => {}} assert_equal default_info, @sa.info assert_equal @app, @sa.app assert_equal Hash.new, @sa.scripts assert_equal [:all], @sa.roles end def test_init_roles sa = Sunshine::ServerApp.new @app, "host", :roles => "role1 role2" assert_equal [:role1, :role2], sa.roles sa = Sunshine::ServerApp.new @app, "host", :roles => %w{role3 role4} assert_equal [:role3, :role4], sa.roles end def test_add_shell_paths @sa.add_shell_paths "test/path1", "test/path2" assert_equal "test/path1:test/path2:$PATH", @sa.shell_env['PATH'] @sa.add_shell_paths "test/path3", "test/path4" assert_equal "test/path3:test/path4:test/path1:test/path2:$PATH", @sa.shell_env['PATH'] end def test_app_attr sa_root_path = "local/server_app/path" sa_deploy_name = "local_deploy_name" @sa = Sunshine::ServerApp.new "test", "host", :root_path => sa_root_path, :deploy_name => sa_deploy_name assert_equal sa_root_path, @sa.root_path assert_equal sa_deploy_name, @sa.deploy_name assert_equal "test", @sa.name @sa.app = @app assert_not_equal sa_root_path, @sa.root_path assert_not_equal sa_deploy_name, @sa.deploy_name assert_not_equal "test", @sa.name assert_equal @app.root_path, @sa.root_path assert_equal @app.deploy_name, @sa.deploy_name assert_equal @app.name, @sa.name end def test_build_control_scripts @sa.scripts[:start] << "start" @sa.scripts[:stop] << "stop" @sa.scripts[:custom] << "custom" @sa.build_control_scripts [:start, :stop, :custom].each do |script| content = @sa.make_bash_script script, @sa.scripts[script] assert @sa.method_called?(:write_script, :args => [script, content]) end content = @sa.make_env_bash_script assert @sa.method_called?(:write_script, :args => ["env", content]) content = @sa.make_bash_script :restart, ["#{@sa.app.root_path}/stop", "#{@sa.app.root_path}/start"] assert @sa.method_called?(:write_script, :args => [:restart, content]) end def test_build_deploy_info_file @sa.shell.mock :file?, :return => false args = ["#{@app.scripts_path}/info", @sa.get_deploy_info.to_yaml] @sa.build_deploy_info_file assert @sa.shell.method_called?(:make_file, :args => args) args = ["#{@app.scripts_path}/info", "#{@app.root_path}/info"] assert @sa.shell.method_called?(:symlink, :args => args) end def test_checkout_repo @sa.checkout_repo @app.repo repo = @sa.app.repo args = [@app.checkout_path, @sa.shell] assert repo.method_called?(:checkout_to, :args => args) info = @app.repo.checkout_to @app.checkout_path, @sa.shell assert_equal info, @sa.info[:scm] end def test_deploy_details deploy_details = {:item => "thing"} other_details = {:key => "value"} @sa.shell.mock :call, :args => ["cat #{@sa.root_path}/info"], :return => other_details.to_yaml @sa.instance_variable_set "@deploy_details", deploy_details assert_equal deploy_details, @sa.deploy_details assert_equal other_details, @sa.deploy_details(true) end def test_not_deployed? @sa.mock :deploy_details, :args => [true], :return => nil assert_equal false, @sa.deployed? end def test_server_checked_deployed? @sa.mock :deploy_details, :args => [true], :return => {:deploy_name => @sa.deploy_name} assert_equal true, @sa.deployed? end def test_cached_details_deployed? @sa.instance_variable_set "@deploy_details", :deploy_name => @sa.deploy_name assert_equal true, @sa.deployed? end def test_get_deploy_info test_info = { :deployed_at => Time.now.to_s, :deployed_as => @sa.shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(@app.checkout_path), :name => @sa.name, :env => @sa.shell_env, :roles => @sa.roles, :path => @app.root_path, :sunshine_version => Sunshine::VERSION }.merge @sa.info deploy_info = @sa.get_deploy_info deploy_info.each do |key, val| next if key == :deployed_at assert_equal test_info[key], val end end def test_has_all_roles assert @sa.has_roles?([:web, :app, :blarg]) assert @sa.has_roles?([:web, :app, :blarg], true) end def test_has_roles @sa.roles = [:web, :app] assert @sa.has_roles?(:web) assert @sa.has_roles?([:web, :app]) assert [email protected]_roles?([:blarg, :web, :app]) assert @sa.has_roles?([:blarg, :web, :app], true) end def test_install_deps nginx_dep = Sunshine.dependencies.get 'nginx', :prefer => @sa.pkg_manager @sa.install_deps "ruby", nginx_dep assert_dep_install 'ruby', Sunshine::Yum assert_dep_install 'nginx', Sunshine::Yum end def test_install_deps_bad_type nginx_dep = Sunshine.dependencies.get 'nginx' @sa.install_deps nginx_dep, :type => Sunshine::Gem raise "Didn't raise missing dependency when it should have." - rescue Sunshine::DependencyLib::MissingDependency => e + rescue Sunshine::MissingDependency => e assert_equal "No dependency 'nginx' [Sunshine::Gem]", e.message end def test_make_app_directories @sa.make_app_directories assert_server_call "mkdir -p #{@sa.directories.join(" ")}" end def test_make_bash_script app_script = @sa.make_bash_script "blah", [1,2,3,4] assert_bash_script "blah", [1,2,3,4], app_script end def test_make_env_bash_script @sa.shell.env = {"BLAH" => "blarg", "HOME" => "/home/blah"} test_script = "#!/bin/bash\nenv BLAH=blarg HOME=/home/blah \"$@\"" assert_equal test_script, @sa.make_env_bash_script end def test_rake @sa.rake "db:migrate" assert_dep_install 'rake', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && rake db:migrate" end def test_register_as_deployed Sunshine::AddCommand.extend MockObject unless MockObject === Sunshine::AddCommand @sa.register_as_deployed args = [@app.root_path, {'servers' => [@sa.shell]}] assert Sunshine::AddCommand.method_called?(:exec, :args => args) end def test_remove_old_deploys Sunshine.setup 'max_deploy_versions' => 3 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_server_call "rm -rf #{removed.join(" ")}" end def test_remove_old_deploys_unnecessary Sunshine.setup 'max_deploy_versions' => 5 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.mock :call, :args => ["ls -1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_not_called "rm -rf #{removed.join(" ")}" end def test_revert! deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" last_deploy = "#{@app.deploys_path}/ploy5" assert_server_call "ln -sfT #{last_deploy} #{@app.current_path}" end def test_no_previous_revert! @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" end def test_run_bundler @sa.run_bundler assert_dep_install 'bundler', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && gem bundle" end def test_run_geminstaller @sa.run_geminstaller assert_dep_install 'geminstaller', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && geminstaller -e" end def test_sass sass_files = %w{file1 file2 file3} @sa.sass(*sass_files) assert_dep_install 'haml', @sa.pkg_manager sass_files.each do |file| sass_file = "public/stylesheets/sass/#{file}.sass" css_file = "public/stylesheets/#{file}.css" assert_server_call \ "cd #{@app.checkout_path} && sass #{sass_file} #{css_file}" end end def test_shell_env assert_equal @sa.shell.env, @sa.shell_env end def test_symlink_current_dir @sa.symlink_current_dir assert_server_call "ln -sfT #{@app.checkout_path} #{@app.current_path}" end def test_upload_tasks files = %w{task1 task2} @sa.upload_tasks(*files) assert_server_call "mkdir -p #{@app.checkout_path}/lib/tasks" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{@app.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_with_remote_path files = %w{task1 task2} path = "/path/to/remote/tasks" @sa.upload_tasks files[0], files[1], :remote_path => path assert_server_call "mkdir -p #{path}" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{path}/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_with_local_path files = %w{task1 task2} path = "/path/to/local/tasks" args = files.dup << {:local_path => path} @sa.upload_tasks(*args) assert_server_call "mkdir -p #{@sa.checkout_path}/lib/tasks" files.each do |f| args = ["#{path}/#{f}.rake", "#{@sa.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_all files = Dir.glob("templates/tasks/*").map{|f| File.basename(f, ".rake")} @sa.upload_tasks assert_server_call "mkdir -p #{@app.checkout_path}/lib/tasks" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{@app.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_write_script @sa.shell.mock :file?, :return => false @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert @sa.shell.method_called?(:make_file, :args => args) end def test_symlink_scripts_to_root @sa.shell.mock :call, :args => ["ls -1 #{@sa.scripts_path}"], :return => "script_name\n" args = ["#{@app.scripts_path}/script_name", "#{@app.root_path}/script_name"] @sa.symlink_scripts_to_root assert @sa.shell.method_called?(:symlink, :args => args) end def test_write_script_existing @sa.shell.mock :file?, :return => true @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert [email protected]_called?(:make_file, :args => args) end end
jcasts/sunshine
9317625022a49c12d075077d1be2d28995309a46
started refactoring exception classes
diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index a3e4b64..024c258 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -1,1240 +1,1239 @@ module Sunshine ## # App objects are the core of Sunshine deployment. The Sunshine paradygm # is to construct an app object, and run custom deploy code by passing # a block to its deploy method: # # someserver = Sunshine::RemoteShell.new "[email protected]", # :roles => [:web, :app] # # options = { # :name => 'myapp', # :repo => {:type => :svn, :url => 'svn://blah...'}, # :root_path => '/usr/local/myapp', # :remote_shells => '[email protected]' # } # # app = Sunshine::App.new(options) # # app.deploy do |app| # # app_server = Sunshine::Rainbows.new app, :port => 3000 # web_server = Sunshine::Nginx.new app, :point_to => app_server # # app_server.setup # web_server.setup # end # # Multiple apps can be defined, and deployed from a single deploy script. # The constructor also supports passing a yaml file path: # # Sunshine::App.new("path/to/config.yml") # # Deployment can be expressed more concisely by calling App::deploy: # # App.deploy("path/to/config.yml") do |app| # Sunshine::Rainbows.new(app).setup # end # # # An App holds information about where to deploy an application to and # how to deploy it, as well as many convenience methods to setup and # manipulate the deployment process. Most of these methods support passing # remote shell find options: # # app.rake 'db:migrate', :role => :db # app.deploy :host => 'server1.com' # # See App#find for more information. # # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml # # Yaml files must define settings on a per-environment basis. The default # environment will be used if the deploy_env is not found in the config. # Let's consider the following config: # # #config.yml: # --- # :default: # :repo: # :type: :svn # :url: http://subversion/repo/tags/release-001 # :remote_shells: dev.myserver.com # # :qa: # :remote_shells: # - qa1.myserver.com # - qa2.myserver.com # # :qa_special: # :inherits: :qa # :root_path: /path/to/application # # By default, environment definitions inherit the :default environment. In # this instance, :qa_special also inherits from :qa. # With the given config, I could setup the App instance as so: # # App.new "config.yml", :deploy_env => :development # # Note: by default, App will get the deploy_env value # # from Sunshine.deploy_env # # The above will simply load the default config. The following, however, # will load the :qa_special config which inherits from # both :qa and :default: # # App.new "config.yml", :deploy_env => :qa_special # # # Another way of instantiating an App is to pass it a hash. Unlike the yaml # config file, the hash is not on a per-environment basis and isexpected # to already have the correct values for the given environment. # The following is equivalent to loading the above :default environment: # # App.new :remote_shells => "dev.myserver.com", # :repo => { # :type => :svn, # :url => "http://subversion/repo/tags/release-001" # } # # In theory, the minimum amount of information required to instantiate # an app is the repo and remote_shells. If the repo option is omitted, # the App will attempt to detect if the pwd is a checkout out repo and # use that information. If you would like to deploy an application that # is not under source countrol, you may do so by using Sunshine::RsyncRepo, # or passing :rsync in your hash as your repo type. # # # Options supported by App.new are the following: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. class App ## # Initialize and deploy an application. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] @on_sigint = @on_exception = nil end ## # Call a command on specified server apps. # Supports any App#find and Shell#call options. def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Connect server apps. Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected. Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected. Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect server apps. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # If the deploy fails or an exception is raised, it will attempt to # run the Sunshine.failed_deploy_behavior, which is set to :revert by # default. # # If the deploy is interrupted by a SIGINT, it will attempt to run # the Sunshine.sigint_behavior, which is set to :revert by default. # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil state = { :success => false, :stopped => false, :symlinked => false } Sunshine.logger.info :app, "Beginning deploy of #{@name}" with_session options do |app| interruptable state do raise CriticalDeployError, "No servers defined for #{@name}" if @server_apps.empty? make_app_directories checkout_codebase state[:stopped] = stop state[:symlinked] = symlink_current_dir yield self if block_given? run_post_user_lambdas health :enable build_control_scripts build_deploy_info_file build_crontab register_as_deployed state[:success] = start! :force => true end remove_old_deploys if state[:success] rescue Sunshine.logger.error :app, "Could not remove old deploys" state[:success] &&= deployed? end Sunshine.logger.info :app, "Finished deploy of #{@name}" state[:success] end ## # Handles SIGINTs and exceptions according to rules set by # Sunshine.sigint_behavior and Sunshine.exception_behavior # or with the override hooks App#on_sigint and App#on_exception. def interruptable options={} interrupt_trap = TrapStack.add_trap "Interrupted #{@name}" do handle_sigint options end yield if block_given? rescue => e Sunshine.logger.error :app, "#{e.class}: #{e.message}" do Sunshine.logger.error '>>', e.backtrace.join("\n") end handle_exception options ensure TrapStack.delete_trap interrupt_trap end ## # Calls the Apps on_sigint hook or the default Sunshine.sigint_behavior. def handle_sigint state={} return @on_sigint.call(self, state) if @on_sigint handle_interruption Sunshine.sigint_behavior, state end ## # Calls the Apps on_exception hook or the default # Sunshine.exception_behavior. def handle_exception state={} return @on_exception.call(self, state) if @on_exception handle_interruption Sunshine.exception_behavior, state end ## # Set this to define the behavior of SIGINT during a deploy. # Defines what to do when an INT signal is received when running # a proc through App#interruptable. Used primarily to catch SIGINTs # during deploys. def on_sigint &block @on_sigint = block end - ## # Set this to define the behavior of exceptions during a deploy. # Defines what to do when an exception is received when running # a proc through App#interruptable. Used primarily to catch exceptions # during deploys. def on_exception &block @on_exception = block end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. def handle_interruption behavior, state={} case behavior when :revert revert! if state[:symlinked] start if state[:stopped] when :console self.console! when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" menu.choice(:revert) { handle_interrupted_deploy :revert, state } menu.choice(:console){ handle_interrupted_deploy :console, state } menu.choice(:exit) { handle_interrupted_deploy :exit, state } end else end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil - copy_option = options && options.has_key?(:copy) && options[:copy] + copy_option = options[:copy] if options if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end rescue => e raise CriticalDeployError, e end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories rescue => e - raise FatalDeployError, e + raise CriticalDeployError, e end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Runs bundler on deploy servers. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] rescue => e raise CriticalDeployError, e end ## # Runs GemInstaller on deploy servers. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] rescue => e raise CriticalDeployError, e end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run a sass task on any or all deploy servers. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. def shell_env env_hash=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. # Post-deploy only. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end ## # Use sudo on deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir rescue => e raise CriticalDeployError, e end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! def threaded_each(options=nil, &block) mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end ## # Upload common rake tasks from the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', :role => :web # #=> upload app and common rake files # # Allows standard DeployServerDispatcher#find options, plus: # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files.last ? files.last.dup : {} options.delete(:remote_path) options = :all if options.empty? with_server_apps options, :msg => "Uploading tasks: #{files.join(" ")}", :send => [:upload_tasks, *files] end ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here # end # # Note: App#with_server_apps calls App#with_session. If you do not need # or want a server connection you can pass :no_session. def with_server_apps search_options, options={} options = search_options.merge options if Hash === search_options message = options[:msg] method = options[:no_threads] ? :each : :threaded_each auto_session = !options[:no_session] block = lambda do send(method, search_options) do |server_app| if block_given? yield(server_app) elsif options[:send] server_app.send(*options[:send]) end end end msg_block = lambda do if message Sunshine.logger.info(:app, message, &block) else block.call end end auto_session ? with_session(&msg_block) : msg_block.call end ## # Runs block ensuring a connection to remote_shells. # Connecting and disconnecting will be ignored if a session # already exists. Supports all App#find options. # # Ensures that servers are disconnected after the block is run # if servers were not previously connected. def with_session options=nil with_filter options do prev_connection = connected? begin connect unless prev_connection yield self ensure disconnect unless prev_connection end end end private ## # Set all the app paths based on the root deploy path. def set_deploy_paths path @root_path = path || File.join(Sunshine.web_directory, @name) @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end ## # Set the app's deploy servers: # server_apps_from_config "some_server" # #=> [<ServerApp @host="some_server"...>] # # server_apps_from_config ["svr1", "svr2", "svr3"] # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] # # remote_shells = [["svr1", {:roles => "web db app"}], "svr2", "svr3"] # server_apps_from_config remote_shells # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] def server_apps_from_config shells shells = [*shells].compact shells.map{|shell| ServerApp.new(*[self,*shell]) } end ## # Set the app's repo: # repo_from_config SvnRepo.new("myurl") # repo_from_config :type => :svn, :url => "myurl" def repo_from_config repo_def case repo_def when Sunshine::Repo repo_def when Hash Sunshine::Repo.new_of_type repo_def[:type], repo_def[:url], repo_def else Sunshine::Repo.detect Sunshine::PATH end end ## # Load a yml config file, parses it with erb and resolves deploy env # inheritance. def config_from_file config_file, erb_binding=binding, env=@deploy_env return {} unless config_file config_data = YAML.load build_erb(config_file, erb_binding) load_config_for config_data, env end ## # Loads an app yml config file, gets the default config # and the current deploy env and returns a merged config hash. def load_config_for config_hash, env return {} unless config_hash deploy_env_config = (config_hash[env] || {}).dup deploy_env_config[:inherits] ||= [] deploy_env_config[:inherits].unshift(:default) if :default != env && config_hash[:default] merge_config_inheritance deploy_env_config, config_hash end ## # Recursively merges config hashes based on the value at :inherits def merge_config_inheritance main_config, all_configs new_config = {} parents = [*main_config[:inherits]].compact parents.each do |config_name| parent = all_configs[config_name] parent = merge_config_inheritance parent, all_configs new_config = new_config.merge parent end new_config.merge main_config # Two merges important for inheritance order end end end diff --git a/lib/sunshine/exceptions.rb b/lib/sunshine/exceptions.rb index 38b83a7..7126a10 100644 --- a/lib/sunshine/exceptions.rb +++ b/lib/sunshine/exceptions.rb @@ -1,54 +1,55 @@ module Sunshine ## # A standard sunshine exception class Exception < StandardError def initialize input=nil, message=nil if ::Exception === input message = [message, input.message].compact.join(": ") super(message) self.set_backtrace(input.backtrace) else super(input) end end end ## # An error occurred when attempting to run a command on the local system class CmdError < Exception; end ## # An ssh call returned a non-zero exit code class SSHCmdError < CmdError attr_reader :shell def initialize message=nil, shell=nil @shell = shell super(message) end end ## # Something went wrong with a deploy-specific item. class DeployError < Exception; end ## # The error is serious enough that deploy cannot proceed. # Sunshine will attempt to revert to a previous deploy if available. class CriticalDeployError < DeployError; end ## - # The error is so serious that all no more action can be taken. + # The error is so serious that no more action can be taken. The app deploy + # may be in a critical or unusable state. # Sunshine will attempt to close any ssh connections and stop the deploy. class FatalDeployError < DeployError; end + ## # A dependency could not be installed. - class DependencyError < FatalDeployError; end - + class DependencyError < CriticalDeployError; end end
jcasts/sunshine
e8dd8629b2c3780db8fb7adb6e740624ad960383
cleanup
diff --git a/lib/sunshine.rb b/lib/sunshine.rb index e4f0447..fdf7b65 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,427 +1,427 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'yaml' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' require 'irb' ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. VERSION = '1.2.1' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { - 'auto' => false, - 'auto_dependencies' => true, - 'deploy_env' => :development, - 'exception_behavior' => :revert, - 'level' => 'info', - 'max_deploy_versions' => 5, - 'remote_checkouts' => false, - 'timeout' => 300, - 'sigint_behavior' => :revert, - 'web_directory' => '/srv/http' + 'auto' => false, + 'auto_dependencies' => true, + 'deploy_env' => :development, + 'exception_behavior' => :revert, + 'level' => 'info', + 'max_deploy_versions' => 5, + 'remote_checkouts' => false, + 'timeout' => 300, + 'sigint_behavior' => :revert, + 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end ## # Defines what to do when deploy raises an exception. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.exception_behavior @config['exception_behavior'] || :revert end ## # Should sunshine ever ask for user input? True by default; overridden with # the -a option. def self.interactive? !@config['auto'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end ## # Defines what to do when sigint is sent during deploys. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.sigint_behavior @config['sigint_behavior'] || :revert end ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config unless File.file? USER_CONFIG_FILE File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" msg << DEFAULT_CONFIG.to_yaml self.exit 1, msg end load_config_file USER_CONFIG_FILE @config['deploy_env'] = ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] || @config['deploy_env'] @config end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset TrapStack.trap_signal :INT do |msg| $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" logger.info :INT, msg end TrapStack.add_trap "Disconnecting all remote shells." do RemoteShell.disconnect_all end require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' require 'sunshine/trap_stack' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' require 'sunshine/healthcheck' require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies' diff --git a/lib/sunshine/remote_shell.rb b/lib/sunshine/remote_shell.rb index 2c349f0..7231a11 100644 --- a/lib/sunshine/remote_shell.rb +++ b/lib/sunshine/remote_shell.rb @@ -1,274 +1,274 @@ module Sunshine ## # Keeps an SSH connection open to a server the app will be deployed to. # Deploy servers use the ssh command and support any ssh feature. # By default, deploy servers use the ControlMaster feature to share # socket connections, with the ControlPath = ~/.ssh/sunshine-%r%h:%p # # Setting session-persistant environment variables is supported by # accessing the @env attribute. class RemoteShell < Shell - class ConnectionError < FatalDeployError; end + class ConnectionError < Exception; end ## # The loop to keep the ssh connection open. LOGIN_LOOP = "echo ok; echo ready; "+ "for (( ; ; )); do kill -0 $PPID && sleep 10 || exit; done;" LOGIN_TIMEOUT = 30 ## # Closes all remote shell connections. def self.disconnect_all return unless defined?(@remote_shells) @remote_shells.each{|rs| rs.disconnect} end ## # Registers a remote shell for global access from the class. # Handled automatically on initialization. def self.register remote_shell (@remote_shells ||= []) << remote_shell end attr_reader :host, :user, :pid attr_accessor :ssh_flags, :rsync_flags ## # Remote shells essentially need a host and optional user. # Typical instantiation is done through either of these methods: # RemoteShell.new "user@host" # RemoteShell.new "host", :user => "user" # # The constructor also supports the following options: # :env:: hash - hash of environment variables to set for the ssh session # :password:: string - password for ssh login; if missing the deploy server # will attempt to prompt the user for a password. def initialize host, options={} super $stdout, options @host, @user = host.split("@").reverse @user ||= options[:user] @rsync_flags = ["-azP"] @rsync_flags.concat [*options[:rsync_flags]] if options[:rsync_flags] @ssh_flags = [ "-o ControlMaster=auto", "-o ControlPath=~/.ssh/sunshine-%r@%h:%p" ] @ssh_flags.concat ["-l", @user] if @user @ssh_flags.concat [*options[:ssh_flags]] if options[:ssh_flags] @pid, @inn, @out, @err = nil self.class.register self end ## # Runs a command via SSH. Optional block is passed the # stream(stderr, stdout) and string data. def call command_str, options={}, &block Sunshine.logger.info @host, "Running: #{command_str}" do execute build_remote_cmd(command_str, options), &block end end ## # Connect to host via SSH and return process pid def connect return true if connected? cmd = ssh_cmd quote_cmd(LOGIN_LOOP), :sudo => false @pid, @inn, @out, @err = popen4 cmd.join(" ") @inn.sync = true data = "" ready = nil start_time = Time.now.to_i until ready || @out.eof? data << @out.readpartial(1024) ready = data =~ /ready/ raise TimeoutError if timed_out?(start_time, LOGIN_TIMEOUT) end unless connected? disconnect host_info = [@user, @host].compact.join("@") raise ConnectionError, "Can't connect to #{host_info}" end @inn.close @pid end ## # Check if SSH session is open and returns process pid def connected? Process.kill(0, @pid) && @pid rescue false end ## # Disconnect from host def disconnect @inn.close rescue nil @out.close rescue nil @err.close rescue nil kill_process @pid, "HUP" rescue nil @pid = nil end ## # Download a file via rsync def download from_path, to_path, options={}, &block from_path = "#{@host}:#{from_path}" Sunshine.logger.info @host, "Downloading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Expand a path: # shell.expand_path "~user/thing" # #=> "/home/user/thing" def expand_path path dir = File.dirname path full_dir = call "cd #{dir} && pwd" File.join full_dir, File.basename(path) end ## # Checks if the given file exists def file? filepath syscall "test -f #{filepath}" end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " cmd = quote_cmd cmd pid = fork do exec \ ssh_cmd(sudo_cmd(env_cmd(cmd)), :flags => "-t").to_a.join(" ") end Process.waitpid pid end end ## # Create a file remotely def make_file filepath, content, options={} temp_filepath = "#{TMP_DIR}/#{File.basename(filepath)}_#{Time.now.to_i}#{rand(10000)}" File.open(temp_filepath, "w+"){|f| f.write(content)} self.upload temp_filepath, filepath, options File.delete(temp_filepath) end ## # Builds an ssh command with permissions, env, etc. def build_remote_cmd cmd, options={} cmd = sh_cmd cmd cmd = env_cmd cmd cmd = sudo_cmd cmd, options cmd = ssh_cmd cmd, options end ## # Uploads a file via rsync def upload from_path, to_path, options={}, &block to_path = "#{@host}:#{to_path}" Sunshine.logger.info @host, "Uploading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Figure out which rsync flags to use. def build_rsync_flags options flags = @rsync_flags.dup remote_rsync = 'rsync' rsync_sudo = sudo_cmd remote_rsync, options unless rsync_sudo == remote_rsync flags << "--rsync-path='#{ rsync_sudo.join(" ") }'" end flags << "-e \"ssh #{@ssh_flags.join(' ')}\"" if @ssh_flags flags.concat [*options[:flags]] if options[:flags] flags end ## # Creates an rsync command. def rsync_cmd from_path, to_path, options={} cmd = ["rsync", build_rsync_flags(options), from_path, to_path] cmd.flatten.compact.join(" ") end ## # Wraps the command in an ssh call. def ssh_cmd cmd, options=nil options ||= {} flags = [*options[:flags]].concat @ssh_flags ["ssh", flags, @host, cmd].flatten.compact end end end diff --git a/lib/sunshine/shell.rb b/lib/sunshine/shell.rb index 0f91b3d..ec0ac8d 100644 --- a/lib/sunshine/shell.rb +++ b/lib/sunshine/shell.rb @@ -1,444 +1,444 @@ module Sunshine ## # The Shell class handles local input, output and execution to the shell. class Shell include Open4 - class TimeoutError < CriticalDeployError; end + class TimeoutError < Exception; end LOCAL_USER = `whoami`.chomp LOCAL_HOST = `hostname`.chomp SUDO_FAILED = /^Sorry, try again./ SUDO_PROMPT = /^Password:/ attr_reader :user, :host, :password, :input, :output, :mutex attr_accessor :env, :sudo, :timeout def initialize output = $stdout, options={} @output = output $stdin.sync @input = HighLine.new $stdin @user = LOCAL_USER @host = LOCAL_HOST @sudo = options[:sudo] @env = options[:env] || {} @password = options[:password] @timeout = options[:timeout] || Sunshine.timeout @cmd_activity = nil @mutex = nil end ## # Checks for equality def == shell @host == shell.host && @user == shell.user rescue false end ## # Prompt the user for input. def ask(*args, &block) sync{ @input.ask(*args, &block) } end ## # Prompt the user to agree. def agree(*args, &block) sync{ @input.agree(*args, &block) } end ## # Execute a command on the local system and return the output. def call cmd, options={}, &block Sunshine.logger.info @host, "Running: #{cmd}" do execute sudo_cmd(cmd, options), &block end end ## # Prompt the user to make a choice. def choose(&block) sync{ @input.choose(&block) } end ## # Close the output IO. (Required by the Logger class) def close @output.close end ## # Returns true. Compatibility method with RemoteShell. def connect true end ## # Returns true. Compatibility method with RemoteShell. def connected? true end ## # Returns true. Compatibility method with RemoteShell. def disconnect true end ## # Copies a file. Compatibility method with RemoteShell. def download from_path, to_path, options={}, &block Sunshine.logger.info @host, "Copying #{from_path} -> #{to_path}" do FileUtils.cp_r from_path, to_path end end alias upload download ## # Expands the path. Compatibility method with RemoteShell. def expand_path path File.expand_path path end ## # Checks if file exists. Compatibility method with RemoteShell. def file? filepath File.file? filepath end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " pid = fork do exec sudo_cmd(env_cmd(cmd)).to_a.join(" ") end Process.waitpid pid end end ## # Write a file. Compatibility method with RemoteShell. def make_file filepath, content, options={} File.open(filepath, "w+"){|f| f.write(content)} end ## # Get the name of the OS def os_name @os_name ||= call("uname -s").strip.downcase end ## # Prompt the user for a password def prompt_for_password host_info = [@user, @host].compact.join("@") @password = ask("#{host_info} Password:") do |q| q.echo = false end end ## # Build an env command if an env_hash is passed def env_cmd cmd, env_hash=@env if env_hash && !env_hash.empty? env_vars = env_hash.map{|e| e.join("=")} cmd = ["env", env_vars, cmd].flatten end cmd end ## # Wrap command in quotes and escape as needed. def quote_cmd cmd cmd = [*cmd].join(" ") "'#{cmd.gsub(/'/){|s| "'\\''"}}'" end ## # Build an sh -c command def sh_cmd cmd ["sh", "-c", quote_cmd(cmd)] end ## # Build a command with sudo. # If sudo_val is nil, it is considered to mean "pass-through" # and the default shell sudo will be used. # If sudo_val is false, the cmd will be returned unchanged. # If sudo_val is true, the returned command will be prefaced # with sudo -H # If sudo_val is a String, the command will be prefaced # with sudo -H -u string_value def sudo_cmd cmd, sudo_val=nil sudo_val = sudo_val[:sudo] if Hash === sudo_val sudo_val = @sudo if sudo_val.nil? case sudo_val when true ["sudo", "-H", cmd].flatten when String ["sudo", "-H", "-u", sudo_val, cmd].flatten else cmd end end ## # Force symlinking a directory. def symlink target, symlink_name call "ln -sfT #{target} #{symlink_name}" rescue false end ## # Synchronize a block with the current mutex if it exists. def sync if @mutex @mutex.synchronize{ yield } else yield end end ## # Returns true if command was run successfully, otherwise returns false. def syscall cmd, options=nil call(cmd, options) && true rescue false end ## # Checks if timeout occurred. def timed_out? start_time=@cmd_activity, max_time=@timeout return unless max_time Time.now.to_i - start_time.to_i > max_time end ## # Update the time of the last command activity def update_timeout @cmd_activity = Time.now end ## # Execute a block while setting the shell's mutex. # Sets the mutex to its original value on exit. # Executing commands with a mutex is used for user prompts. def with_mutex mutex old_mutex, @mutex = @mutex, mutex yield @mutex = old_mutex end ## # Runs the passed block within a connection session. # If the shell is already connected, connecting and disconnecting # is ignored; otherwise, the session method will ensure that # the shell's connection gets closed after the block has been # executed. def with_session prev_connection = connected? connect unless prev_connection yield disconnect unless prev_connection end ## # Write string to stdout (by default). def write str @output.write str end alias << write ## # Execute a command with open4 and loop until the process exits. # The cmd argument may be a string or an array. If a block is passed, # it will be called when data is received and passed the stream type # and stream string value: # shell.execute "test -s 'blah' && echo 'true'" do |stream, str| # stream #=> :stdout # string #=> 'true' # end # # The method returns the output from the stdout stream by default, and # raises a CmdError if the exit status of the command is not zero. def execute cmd cmd = [cmd] unless Array === cmd pid, inn, out, err = popen4(*cmd) inn.sync = true log_methods = {out => :debug, err => :error} result, status = process_streams(pid, out, err) do |stream, data| stream_name = :out if stream == out stream_name = :err if stream == err stream_name = :inn if stream == inn # User blocks should run with sync threads to avoid badness. sync do Sunshine.logger.send log_methods[stream], "#{@host}:#{stream_name}", data yield(stream_name, data, inn) if block_given? end if password_required?(stream_name, data) then kill_process(pid) unless Sunshine.interactive? send_password_to_stream(inn, data) end end raise_command_failed(status, cmd) unless status.success? result[out].join.chomp ensure inn.close rescue nil out.close rescue nil err.close rescue nil end private def raise_command_failed(status, cmd) raise CmdError, "Execution failed with status #{status.exitstatus}: #{[*cmd].join ' '}" end def password_required? stream_name, data stream_name == :err && data =~ SUDO_PROMPT end def send_password_to_stream inn, data prompt_for_password if data =~ SUDO_FAILED inn.puts @password || prompt_for_password end def kill_process pid, kill_type="KILL" begin Process.kill kill_type, pid Process.wait rescue end end def process_streams pid, *streams result = Hash.new{|h,k| h[k] = []} update_timeout # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 raise TimeoutError if timed_out? next if selected.nil? or selected.empty? selected.each do |stream| update_timeout if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) yield(stream, data) result[stream] << data end end return result, status end end end
jcasts/sunshine
4f7d8e9455e0fe46839ab4e5b256de9c59cbc112
removed extraneous CmdError from dependency class
diff --git a/lib/sunshine/package_managers/dependency.rb b/lib/sunshine/package_managers/dependency.rb index 4ff6fbc..9c44fef 100644 --- a/lib/sunshine/package_managers/dependency.rb +++ b/lib/sunshine/package_managers/dependency.rb @@ -1,357 +1,356 @@ module Sunshine ## # Dependency objects let you define how to install, check, and remove # a described package, including parent dependency lookup and installation. # # Dependency.new "ruby", :tree => dependency_lib do # install "sudo yum install ruby" # uninstall "sudo yum remove ruby" # check_test "yum list installed ruby | grep -c ruby", "-ge 1" # end # # Dependencies are more commonly defined through a Settler class' # constructor methods: # # dependency_lib.instance_eval do # dependency 'custom' do # requires 'yum', 'ruby' # install 'sudo yum install custom' # uninstall 'sudo yum remove custom' # check 'yum list installed custom' # end # end # # The Dependency class is simple to inherit and use as a built-in part of # Settler (see the Yum implementation for more info): # # class Yum < Dependency # def initialize(name, options={}, &block) # super(dep_lib, name, options) do # # Define install, check, and uninstall scripts specific to yum # end # end # ... # end # # Once a subclass is defined a constructor method is added automatically # to the Settler class: # # dependency_lib.instance_eval do # yum "ruby", :version => '1.9' # end class Dependency - class CmdError < Exception; end class InstallError < Exception; end class UninstallError < Exception; end ## # Check if sudo should be used def self.sudo @sudo ||= nil end ## # Assign a sudo value. A value of nil means 'don't assign sudo', # true means sudo, string means sudo -u, false means, explicitely # don't use sudo. Yum and Gem dependency types default to sudo=true. def self.sudo= value @sudo = value end ## # Checks if dependency type is valid for a given shell. # Defaults to false. Override in subclass. def self.system_manager? shell=nil false end attr_reader :name, :pkg, :parents, :children def initialize name, options={}, &block @dependency_lib = options[:tree] @name = name.to_s @pkg = options[:pkg] || @name @options = options.dup @install = nil @uninstall = nil @check = nil @parents = [] @children = [] @shell = Sunshine.shell requires(*options[:requires]) if options[:requires] instance_eval(&block) if block_given? end ## # Append a child dependency def add_child name @children << name end ## # Get direct child dependencies def child_dependencies @children end ## # Define the command that checks if the dependency is installed. # The check command must have an appropriate exitcode: # # dep.check "test -s 'yum list installed depname'" def check cmd_str=nil, &block @check = cmd_str || block end ## # Define checking that the dependency is installed via unix's 'test': # # dep.check_test "yum list installed depname | grep -c depname", "-ge 1" def check_test cmd_str, condition_str check "test \"$(#{cmd_str})\" #{condition_str}" end ## # Define the install command for the dependency: # # dep.install "yum install depname" def install cmd=nil, &block @install = cmd || block end ## # Run the install command for the dependency # Allows options: # :call:: obj - an object that responds to call will be passed the bash cmd # :skip_parents:: true - install regardless of missing parent dependencies # # runner = lambda{|str| system(str)} # dep.install! :call => runner def install! options={} return if installed?(options) if options[:skip_parents] missing = missing_parents? if missing raise(InstallError, "Could not install #{@name}. "+ "Missing dependencies #{missing.join(", ")}") end else install_parents!(options) end run_command(@install, options) raise(InstallError, "Failed installing #{@name}") unless installed?(options) end ## # Call install on direct parent dependencies # Allows options: # :call:: obj - an object that responds to call will be passed the bash cmd # # runner = lambda{|str| system(str)} # dep.install_parents! :call => runner def install_parents! options={} return unless @dependency_lib @parents.each do |dep| @dependency_lib.get(dep, options).install!(options) end end ## # Run the check command to verify that the dependency is installed # Allows options: # :call:: obj - an object that responds to call will be passed the bash cmd # # runner = lambda{|str| system(str)} # dep.installed? :call => runner def installed? options={} run_command @check, options rescue => e false end ## # Checks if any parents dependencies are missing # Allows options: # :call:: obj - an object that responds to call will be passed the bash cmd # # runner = lambda{|str| system(str)} # dep.missing_parents? :call => runner def missing_parents? options={} return unless @dependency_lib missing = [] @parents.each do |dep| parent_dep = @dependency_lib.get dep, options missing << dep unless parent_dep.installed?(options) return missing if options[:limit] && options[:limit] == missing.length end missing.empty? ? nil : missing end ## # Get direct parent dependencies def parent_dependencies @parents end ## # Define which dependencies this dependency relies on: # # dep.requires 'rubygems', 'rdoc' def requires *deps return unless @dependency_lib @parents.concat(deps).uniq! deps.each do |dep| @dependency_lib.dependencies[dep].each{|d| d.add_child(@name) } end end ## # Define the uninstall command for the dependency: # # dep.uninstall "yum remove depname" def uninstall cmd=nil, &block @uninstall = cmd || block end ## # Run the uninstall command for the dependency # Allows options: # :call:: obj - an object that responds to call will be passed the bash cmd # :force:: true - uninstalls regardless of child dependencies # :remove_children:: true - removes direct child dependencies # :remove_children:: :recursive - removes children recursively def uninstall! options={} if !options[:remove_children] && !options[:force] raise UninstallError, "The #{@name} has child dependencies." end uninstall_children!(options) if options[:remove_children] run_command(@uninstall, options) raise(UninstallError, "Failed removing #{@name}") if installed?(options) end ## # Removes child dependencies # Allows options: # :call:: obj - an object that responds to call will be passed the bash cmd # :force:: true - uninstalls regardless of child dependencies # :remove_children:: true - removes direct child dependencies # :remove_children:: :recursive - removes children recursively def uninstall_children! options={} return unless @dependency_lib options = options.dup @children.each do |dep| options.delete(:remove_children) unless options[:remove_children] == :recursive @dependency_lib.get(dep, options).uninstall!(options) end end ## # Alias for name def to_s @name end private def run_command command, options={} shell = options[:call] || @shell if Proc === command command.call shell, self.class.sudo else shell.call command, :sudo => self.class.sudo end end ## # Returns an underscored short version of the class name: # Sunshine::Yum.short_name # #=> "yum" def self.short_name @short_name ||= underscore self.name.to_s.split(":").last end def self.underscore str str.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2').downcase end ## # Auto register the new Dependency class with DependencyLib and ServerApp # when inherited. def self.inherited subclass DependencyLib.register_type subclass ServerApp.register_dependency_type subclass end inherited self end end
jcasts/sunshine
27d6e127db6a89a4aacb1a2fd0dc1145b037db02
added exit code to CmdError
diff --git a/History.txt b/History.txt index 5f207cd..8261f21 100644 --- a/History.txt +++ b/History.txt @@ -1,359 +1,363 @@ === 1.2.1 / 2010-10-05 * Improvements: * Added customizable behaviors for sigint and failures during deploys. * Added Sunshine irb shell to work directly with deploying apps. * Added ability to launch a pseudo terminal from a RemoteShell. + * Added exit code to CmdError. + * Bugfixes: * Fixed custom scripts. * Fixed deploy env defaults. + * Removed Shell#update_timeout as it was unnecessary. + === 1.2.0 / 2010-09-08 * Improvements: * Added better support for custom env/start/stop/restart scripts. * Added scripts sunshine command to call custom scripts remotely. * Deploy env defaults to ENV 'DEPLOY_ENV', 'env', 'RACK_ENV', or 'RAILS_ENV'. * Bugfixes: * ServerApp#run_geminstaller no longer defaults to using sudo. * Added better extensible package manager checking to ServerApp. * Fixed Cronjob functionality and added array support. === 1.1.2 / 2010-04-15 * Improvements: * Added array support to App#find. * Added auto registration of Dependency subclasses for scalability. * Added call to App#start in App#deploy. * Bugfixes: * Fixed bug where env wouldn't be applied correctly in control scripts. * Changed App#with_filter to actually change the App#server_apps attribute. * Shell#env_cmd now returns a flattened array. * Added actual check of running process to Daemon#status_cmd. === 1.1.1 / 2010-04-05 * Improvements: * Added Repo subclass registration for greater expandability. * Added support for checking out codebases locally then rsync-ing them. * Bugfixes: * Fixed RemoteShell login script lingering after disconnect. === 1.1.0 / 2010-04-02 * Improvements: * Support for server clustering with the ServerCluster class. * Added Daemon#status method. * Added the -R option for loading external libraries and gems. * Added support for Thin and MongrelRails. * Added Server support for max connections configuration. * Bugfixes: * Daemons no longer create control scripts if they aren't used. * Fixed Rsync repo to auto append "/" to urls for correct rsyncing. === 1.0.3 / 2010-03-26 * Improvements: * Added App#call method. * Added App#with_session and Shell#with_session to reduce login prompts. * Bugfixes: * Geminstaller now always installs with sudo. * Fixed permissions issues with running servers on ports < 1024. * Fixed healthcheck middleware. === 1.0.2 / 2010-03-25 * Bugfixes: * Fixed apache passenger dependency to run as sudo. * Fixed a bug in Repo::detect === 1.0.1 / 2010-03-25 * Bugfixes: * Added json dependency === 1.0.0 / 2010-03-25 * Improvements: * Added auto_dependencies config to turn on/off auto installing things. * Added healthcheck middleware support. * Added support for Apache2 and its passenger implementation. * Removed all Atti-specific code for public release. * Bugfixes: * Fixed Nginx passenger implementation. === 0.0.6 / 2010-03-19 * Major: * Removed DeployServerDispatcher. Dispatching now happens at the App level. * Moved Settler into Sunshine and renamed it to DependencyLib. * Improvements: * Added INT signal handling to exit deploys and close connections gracefully. * Added dependency installation methods apt_install, gem_install, tpkg_install and yum_install to App and ServerApp. * Extended functionality of ServerApp#upload_tasks. * ServerApp now support being instatiated with an App instance (for coordinated deploys) or just with an app name (for post-deploy usage). * Added a Sunshine rakefile template for task-based deploys. Available through: sunshine --rakefile [COPY_TO] * App#name gets auto-assigned by repo info if not provided. * Sunshine::web_directory used to determine App#deploy_path when missing. * Repo#detect now returns a Repo object instead of an array. * Added start/stop/restart/status methods to DeployServerApp. * ServerApp instances with unspecified roles get all roles by default. * App config files now use erb parsing. Any key/value passed the App constructor as a hash should be passed to the erb binding along with the deploy_env. * Added support to bundler for defining multiple dependencies with the same name, and different package managers. * Bugfixes: * Added setup checking to Daemon to only run setup when needed. * Moved healthcheck from App to ServerApp and improved the api. * Renamed DeployServerApp to ServerApp. * Renamed App#deploy_path and App#deploys_dir to App#root_path and App#deploys_path. * Renamed the 'deploy' command to 'run' to more accurately express it's use. * RsyncRepo#do_checkout fixed to match standard Repo#do_checkout methods. * Sunshine::DATA and Sunshine::PATH are now set when running standalone ruby deploy files. === 0.0.5 / 2010-02-26 * Sunshine::App: * Use of DeployServerDispatcher threading * Fixed control script creation to be deploy_server specific (takes roles into account) * Added AttiApp class for ATTi app deployment. * Constuctor supports :deploy_name option for nameable deploys. Defaults to the timestamp. * Auto-detects if the script's directory is a checked out repo and uses it if no repo information was given. * Support for running sass. * Sunshine::DeployServerDispatcher: * Added threading support * Sunshine::Repo: * Added support for detecting a repo type based on a path: Repo.detect [path [, console_or_deploy_server]] #=> [:git, "git://url/of/git/repo", {:tree => "master", ...}] * Moved info instance methods to the class * Support for git-svn: SvnRepo.git_svn? path * Changed the checkout_to method signature * Sunshine::Server: * Added support for ar_sendmail server. === 0.0.4 / 2010-02-12 * Added sudo functionality: * Support for :sudo option on Sunshine::App, Sunshine::Server, and Sunshine::DeployServer constructors, and attr_accessor :sudo * Settler Dependency classes support a default sudo value: Sunshine::Dependencies::Gem.sudo = true # use sudo Sunshine::Dependencies::Gem.sudo = "usr" # use sudo -u usr Sunshine::Dependencies::Gem.sudo = false # ensure sudo is off Sunshine::Dependencies::Gem.sudo = nil # use :call obj precedence * App supports passing a (yml) file object to the constructor. Useful for passing file DATA if desired: app = Sunshine::App.new Sunshine::DATA app.deploy!{|app| Sunshine::Rainbows.new(app).restart } __END__ #yaml for app goes here... * App class changes: * Changed the format of the App#checkout_path directory * Logrotate setup now has to be called explicitely * Commands functionality expanded: * Support for --sudo and --sudo=user on all Sunshine commands * Added --format option for control commands. Supports txt, yml, json. * Control scripts generated on the remote server now keep deploy-time shell_env variables: * Run commands with the --no-env option to run without deploy shell_env variables. * Run any script with the app's env variables using: /path/to/app/env some_command /path/to/app/env EXTRA_VAR=some_value some_command Supports all options the env command supports. * Dependency handling now supports apt. * DeployServers now support passing custom flags for ssh and rsync: deploy_server = DeployServer.new "svr.com", :rsync_flags => [...] deploy_server.call "some_command", :sudo => "user", :flags => '-C' deploy_server.upload "from", "to", :sudo => "user", :flags => ['--chmod=ugo=rwX', '-b'] deploy_server.download "from", "to", :flags => '--ignore-existing' * Repo implementation has significantly changed: * Added support for git repo. * Info about a repo is now retrieved with Repo#get_repo_info: repo.get_repo_info deploy_server, checkout_path * Repo constructor supports options hash with :flags option. === 0.0.3 / 2010-01-29 * Many small bugfixes * Tests, tests, and more tests * Changed DeployServer api * DeployServer#run is not longer supported, use DeployServer#call * Constructor supports a spaced delimited list for roles: DeployServer.new "myhost.com", :roles => "web db other" * Changed how deploy server yaml is parsed. Should parse to be valid on: DeployServer.new *parsed_yaml Example Given: :deploy_servers : - server1.com - - server2.com - - server3.com - :roles : web db other :ssh_flags : '-o ControlMaster=auto' === 0.0.2 / 2010-01-15 * Added Control Commands * add, deploy, list, restart, rm, start, stop * Application support * Changed VERSION file to info and its format to yaml * Deployed apps now have a start, stop and restart script * Added Crontab and log rotation support * Functional changes * Ditched net/ssh and net/scp for ssh and rsync through Open4 * Fixed and updated dependencies to use Yum * Support for sunshine user configuration in ~/.sunshine * Rake tasks * Support to run the app's rake tasks * Built in default ATTi rake tasks === 0.0.1 / 2009-11-18 * 1 major enhancement * First release! diff --git a/lib/sunshine/exceptions.rb b/lib/sunshine/exceptions.rb index b80958e..d1041a8 100644 --- a/lib/sunshine/exceptions.rb +++ b/lib/sunshine/exceptions.rb @@ -1,54 +1,51 @@ module Sunshine ## # A standard sunshine exception class Exception < StandardError def initialize input=nil, message=nil if ::Exception === input message = [message, input.message].compact.join(": ") super(message) self.set_backtrace(input.backtrace) else super(input) end end end ## # An error occurred when attempting to run a command on the local system - class CmdError < Exception; end + class CmdError < Exception; + attr_reader :exit_code - - ## - # An ssh call returned a non-zero exit code - class SSHCmdError < CmdError - attr_reader :shell - def initialize message=nil, shell=nil - @shell = shell - super(message) + def initialize exit_code, cmd=nil + message = "Execution failed with status #{exit_code}: #{cmd}" + super message + @exit_code = exit_code end end ## # Something went wrong with a deploy-specific item. class DeployError < Exception; end ## # The error is serious enough that deploy cannot proceed. # Sunshine will attempt to revert to a previous deploy if available. class CriticalDeployError < DeployError; end ## # The error is so serious that no more action can be taken. # Sunshine will attempt to close any ssh connections and stop the deploy. class FatalDeployError < DeployError; end ## # A dependency could not be installed. class DependencyError < FatalDeployError; end end diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index 9dee76c..13843bf 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -1,548 +1,548 @@ module Sunshine ## # Handles App deployment functionality for a single deploy server. # # Server apps can be assigned any number of roles for classification. # :roles:: sym|array - roles assigned (web, db, app, etc...) # By default server apps get the special :all role which will # always return true when calling: # server_app.has_roles? :some_role # # ServerApp objects can be instantiated several ways: # ServerApp.new app_instance, shell_instance, options_hash # # When passing an App instance, the new ServerApp will keep an active link # to the app's properties. Name, deploy, and path attributes will be # actively linked. # # Rely on ServerApp to create a RemoteShell instance to use: # ServerApp.new app_instance, "host.com", options_hash # # Instantiate with app name and rely on Sunshine defaults for app paths: # ServerApp.new "app_name", shell_instance, options_hash # # Explicitely assign the app's root path: # ServerApp.new "app_name", ..., :root_path => "/path/to/app_root" # # Assigning a specific deploy name to use can be done with the # :deploy_name option: # ServerApp.new "app_name", ..., :deploy_name => "deploy" class ServerApp ## - # Define an attribue that will get a value from app, or locally if + # Define an attribute that will get a value from app, or locally if # @app isn't set. def self.app_attr *attribs attribs.each do |attrib| class_eval <<-STR, __FILE__, __LINE__ + 1 def #{attrib} @app ? @app.send(:#{attrib}) : @#{attrib} end STR end end ## # Creates dependency instance methods such as gem_install, yum_install, etc # on both App and ServerApp classes. def self.register_dependency_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = Hash === names.last ? names.delete_at(-1) : Hash.new names.each do |name| dep = #{dep_class}.new(name, options) dep.install! :call => @shell end end STR App.class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = names.last if Hash === names.last with_server_apps options, :msg => "Installing #{dep_class.short_name} packages", :send => [:#{dep_class.short_name}_install, *names] end STR end ## # Creates a ServerApp instance from a deploy info file. def self.from_info_file path, shell=nil shell ||= Sunshine.shell opts = YAML.load shell.call("cat #{path}") opts[:root_path] = opts.delete :path sa_shell = shell.dup sa_shell.env = opts[:env] || Hash.new sa_shell.connect if shell.connected? new opts[:name], sa_shell, opts end app_attr :name, :deploy_name app_attr :root_path, :checkout_path, :current_path app_attr :deploys_path, :log_path, :shared_path, :scripts_path attr_accessor :app, :roles, :scripts, :info, :shell, :crontab, :health attr_writer :pkg_manager ## # Create a server app instance. Supports the following # argument configurations: # # ServerApp.new app_inst, "myserver.com", :roles => :web # ServerApp.new "app_name", shell_inst, options_hash def initialize app, host, options={} @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell @health = Healthcheck.new shared_path, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No daemons for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path, :sunshine_version => Sunshine::VERSION }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec self.root_path, 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's restart script. Raises an exception on failure. # Post-deploy only. def restart! # Permissions are handled by the script, use: :sudo => false run_script! :restart, :sudo => false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the root_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} run_script! name, options, &block rescue false end ## # Runs a script from the root_path. Raises an exception if the status # code is not 0. # Post-deploy only. def run_script! name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script :status, :sudo => false end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" diff --git a/lib/sunshine/shell.rb b/lib/sunshine/shell.rb index 99d1e0e..b2b2137 100644 --- a/lib/sunshine/shell.rb +++ b/lib/sunshine/shell.rb @@ -1,444 +1,434 @@ module Sunshine ## # The Shell class handles local input, output and execution to the shell. class Shell include Open4 class TimeoutError < CriticalDeployError; end LOCAL_USER = `whoami`.chomp LOCAL_HOST = `hostname`.chomp SUDO_FAILED = /^Sorry, try again./ SUDO_PROMPT = /^Password:/ attr_reader :user, :host, :password, :input, :output, :mutex attr_accessor :env, :sudo, :timeout def initialize output = $stdout, options={} @output = output $stdin.sync @input = HighLine.new $stdin @user = LOCAL_USER @host = LOCAL_HOST @sudo = options[:sudo] @env = options[:env] || {} @password = options[:password] @timeout = options[:timeout] || Sunshine.timeout - @cmd_activity = nil - @mutex = nil end ## # Checks for equality def == shell @host == shell.host && @user == shell.user rescue false end ## # Prompt the user for input. def ask(*args, &block) sync{ @input.ask(*args, &block) } end ## # Prompt the user to agree. def agree(*args, &block) sync{ @input.agree(*args, &block) } end ## # Execute a command on the local system and return the output. def call cmd, options={}, &block Sunshine.logger.info @host, "Running: #{cmd}" do execute sudo_cmd(cmd, options), &block end end ## # Prompt the user to make a choice. def choose &block sync{ @input.choose(&block) } end ## # Close the output IO. (Required by the Logger class) def close @output.close end ## # Returns true. Compatibility method with RemoteShell. def connect true end ## # Returns true. Compatibility method with RemoteShell. def connected? true end ## # Returns true. Compatibility method with RemoteShell. def disconnect true end ## # Copies a file. Compatibility method with RemoteShell. def download from_path, to_path, options={}, &block Sunshine.logger.info @host, "Copying #{from_path} -> #{to_path}" do FileUtils.cp_r from_path, to_path end end alias upload download ## # Expands the path. Compatibility method with RemoteShell. def expand_path path File.expand_path path end ## # Checks if file exists. Compatibility method with RemoteShell. def file? filepath File.file? filepath end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " pid = fork do exec sudo_cmd(env_cmd(cmd)).to_a.join(" ") end Process.waitpid pid end end ## # Write a file. Compatibility method with RemoteShell. def make_file filepath, content, options={} File.open(filepath, "w+"){|f| f.write(content)} end ## # Get the name of the OS def os_name @os_name ||= call("uname -s").strip.downcase end ## # Prompt the user for a password def prompt_for_password host_info = [@user, @host].compact.join("@") @password = ask("#{host_info} Password:") do |q| q.echo = false end end ## # Build an env command if an env_hash is passed def env_cmd cmd, env_hash=@env if env_hash && !env_hash.empty? env_vars = env_hash.map{|e| e.join("=")} cmd = ["env", env_vars, cmd].flatten end cmd end ## # Wrap command in quotes and escape as needed. def quote_cmd cmd cmd = [*cmd].join(" ") "'#{cmd.gsub(/'/){|s| "'\\''"}}'" end ## # Build an sh -c command def sh_cmd cmd ["sh", "-c", quote_cmd(cmd)] end ## # Build a command with sudo. # If sudo_val is nil, it is considered to mean "pass-through" # and the default shell sudo will be used. # If sudo_val is false, the cmd will be returned unchanged. # If sudo_val is true, the returned command will be prefaced # with sudo -H # If sudo_val is a String, the command will be prefaced # with sudo -H -u string_value def sudo_cmd cmd, sudo_val=nil sudo_val = sudo_val[:sudo] if Hash === sudo_val sudo_val = @sudo if sudo_val.nil? case sudo_val when true ["sudo", "-H", cmd].flatten when String ["sudo", "-H", "-u", sudo_val, cmd].flatten else cmd end end ## # Force symlinking a directory. def symlink target, symlink_name call "ln -sfT #{target} #{symlink_name}" rescue false end ## # Synchronize a block with the current mutex if it exists. def sync if @mutex @mutex.synchronize{ yield } else yield end end ## # Returns true if command was run successfully, otherwise returns false. def syscall cmd, options=nil call(cmd, options) && true rescue false end ## # Checks if timeout occurred. - def timed_out? start_time=@cmd_activity, max_time=@timeout + def timed_out? start_time, max_time=@timeout return unless max_time Time.now.to_i - start_time.to_i > max_time end - ## - # Update the time of the last command activity - - def update_timeout - @cmd_activity = Time.now - end - - ## # Execute a block while setting the shell's mutex. # Sets the mutex to its original value on exit. # Executing commands with a mutex is used for user prompts. def with_mutex mutex old_mutex, @mutex = @mutex, mutex yield @mutex = old_mutex end ## # Runs the passed block within a connection session. # If the shell is already connected, connecting and disconnecting # is ignored; otherwise, the session method will ensure that # the shell's connection gets closed after the block has been # executed. def with_session prev_connection = connected? connect unless prev_connection yield disconnect unless prev_connection end ## # Write string to stdout (by default). def write str @output.write str end alias << write ## # Execute a command with open4 and loop until the process exits. # The cmd argument may be a string or an array. If a block is passed, # it will be called when data is received and passed the stream type # and stream string value: # shell.execute "test -s 'blah' && echo 'true'" do |stream, str| # stream #=> :stdout # string #=> 'true' # end # # The method returns the output from the stdout stream by default, and # raises a CmdError if the exit status of the command is not zero. def execute cmd cmd = [cmd] unless Array === cmd pid, inn, out, err = popen4(*cmd) inn.sync = true log_methods = {out => :debug, err => :error} result, status = process_streams(pid, out, err) do |stream, data| stream_name = :out if stream == out stream_name = :err if stream == err stream_name = :inn if stream == inn # User blocks should run with sync threads to avoid badness. sync do Sunshine.logger.send log_methods[stream], "#{@host}:#{stream_name}", data yield(stream_name, data, inn) if block_given? end if password_required?(stream_name, data) then kill_process(pid) unless Sunshine.interactive? send_password_to_stream(inn, data) end end raise_command_failed(status, cmd) unless status.success? result[out].join.chomp ensure inn.close rescue nil out.close rescue nil err.close rescue nil end private def raise_command_failed(status, cmd) - raise CmdError, - "Execution failed with status #{status.exitstatus}: #{[*cmd].join ' '}" + err = CmdError.new status.exitstatus, [*cmd].join(" ") + raise err end def password_required? stream_name, data stream_name == :err && data =~ SUDO_PROMPT end def send_password_to_stream inn, data prompt_for_password if data =~ SUDO_FAILED inn.puts @password || prompt_for_password end def kill_process pid, kill_type="KILL" begin Process.kill kill_type, pid Process.wait rescue end end def process_streams pid, *streams result = Hash.new{|h,k| h[k] = []} - update_timeout + start_time = Time.now # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 - raise TimeoutError if timed_out? + raise TimeoutError if timed_out? start_time next if selected.nil? or selected.empty? selected.each do |stream| - update_timeout + start_time = Time.now if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) yield(stream, data) result[stream] << data end end return result, status end end end
jcasts/sunshine
e613ce557369ee9e70fc2ca059f48ab7468169db
fixed ServerApp#run_script to pass options correctly
diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index 419fcdf..0244b0f 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -1,832 +1,832 @@ module Sunshine ## # App objects are the core of Sunshine deployment. The Sunshine paradygm # is to construct an app object, and run custom deploy code by passing # a block to its deploy method: # # someserver = Sunshine::RemoteShell.new "[email protected]", # :roles => [:web, :app] # # options = { # :name => 'myapp', # :repo => {:type => :svn, :url => 'svn://blah...'}, # :root_path => '/usr/local/myapp', # :remote_shells => '[email protected]' # } # # app = Sunshine::App.new(options) # # app.deploy do |app| # # app_server = Sunshine::Rainbows.new app, :port => 3000 # web_server = Sunshine::Nginx.new app, :point_to => app_server # # app_server.setup # web_server.setup # end # # Multiple apps can be defined, and deployed from a single deploy script. # The constructor also supports passing a yaml file path: # # Sunshine::App.new("path/to/config.yml") # # Deployment can be expressed more concisely by calling App::deploy: # # App.deploy("path/to/config.yml") do |app| # Sunshine::Rainbows.new(app).setup # end # # # An App holds information about where to deploy an application to and # how to deploy it, as well as many convenience methods to setup and # manipulate the deployment process. Most of these methods support passing # remote shell find options: # # app.rake 'db:migrate', :role => :db # app.deploy :host => 'server1.com' # # See App#find for more information. # # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml # # Yaml files must define settings on a per-environment basis. The default # environment will be used if the deploy_env is not found in the config. # Let's consider the following config: # # #config.yml: # --- # :default: # :repo: # :type: :svn # :url: http://subversion/repo/tags/release-001 # :remote_shells: dev.myserver.com # # :qa: # :remote_shells: # - qa1.myserver.com # - qa2.myserver.com # # :qa_special: # :inherits: :qa # :root_path: /path/to/application # # By default, environment definitions inherit the :default environment. In # this instance, :qa_special also inherits from :qa. # With the given config, I could setup the App instance as so: # # App.new "config.yml", :deploy_env => :development # # Note: by default, App will get the deploy_env value # # from Sunshine.deploy_env # # The above will simply load the default config. The following, however, # will load the :qa_special config which inherits from # both :qa and :default: # # App.new "config.yml", :deploy_env => :qa_special # # # Another way of instantiating an App is to pass it a hash. Unlike the yaml # config file, the hash is not on a per-environment basis and isexpected # to already have the correct values for the given environment. # The following is equivalent to loading the above :default environment: # # App.new :remote_shells => "dev.myserver.com", # :repo => { # :type => :svn, # :url => "http://subversion/repo/tags/release-001" # } # # In theory, the minimum amount of information required to instantiate # an app is the repo and remote_shells. If the repo option is omitted, # the App will attempt to detect if the pwd is a checkout out repo and # use that information. If you would like to deploy an application that # is not under source countrol, you may do so by using Sunshine::RsyncRepo, # or passing :rsync in your hash as your repo type. # # # Options supported by App.new are the following: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. class App ## # Initialize and deploy an application. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] @on_sigint = @on_exception = nil end ## # Call a command on specified server apps. # Supports any App#find and Shell#call options. def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Connect server apps. Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected. Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected. Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect server apps. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # If the deploy fails or an exception is raised, it will attempt to # run the Sunshine.failed_deploy_behavior, which is set to :revert by # default. However, this is not true of ssh connection failures. # # If the deploy is interrupted by a SIGINT, it will attempt to run # the Sunshine.sigint_behavior, which is set to :revert by default. # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil state = { :success => false, :stopped => false, :symlinked => false } - Sunshine.logger.info :app, "Beginning deploy of #{@name}" + Sunshine.logger.info :app, "Beginning #{@name} deploy" with_session options do |app| interruptable state do raise CriticalDeployError, "No servers defined for #{@name}" if @server_apps.empty? make_app_directories checkout_codebase state[:stopped] = true if stop state[:symlinked] = true if symlink_current_dir yield self if block_given? run_post_user_lambdas health :enable build_control_scripts build_deploy_info_file build_crontab register_as_deployed state[:success] = true if start! :force => true end remove_old_deploys if state[:success] rescue Sunshine.logger.error :app, "Could not remove old deploys" state[:success] &&= deployed? end - Sunshine.logger.info :app, "Finished deploy of #{@name}" + Sunshine.logger.info :app, "Finished #{@name} deploy" if state[:success] state[:success] end ## # Handles SIGINTs and exceptions according to rules set by # Sunshine.sigint_behavior and Sunshine.exception_behavior # or with the override hooks App#on_sigint and App#on_exception. def interruptable options={} interrupt_trap = TrapStack.add_trap "Interrupted #{@name}" do handle_sigint options end yield if block_given? rescue => e Sunshine.logger.error :app, "#{e.class}: #{e.message}" do Sunshine.logger.error '>>', e.backtrace.join("\n") end handle_exception e, options ensure TrapStack.delete_trap interrupt_trap end ## # Calls the Apps on_sigint hook or the default Sunshine.sigint_behavior. def handle_sigint state={} return @on_sigint.call(state) if @on_sigint handle_interruption Sunshine.sigint_behavior, state end ## # Calls the Apps on_exception hook or the default # Sunshine.exception_behavior. def handle_exception exception, state={} return @on_exception.call(exception, state) if @on_exception handle_interruption Sunshine.exception_behavior, state end ## # Set this to define the behavior of SIGINT during a deploy. # Defines what to do when an INT signal is received when running # a proc through App#interruptable. Used primarily to catch SIGINTs # during deploys. Passes the block a hash with the state of the deploy: # # app.on_sigint do |deploy_state_hash| # deploy_state_hash # #=> {:stopped => true, :symlinked => true, :success => false} # end def on_sigint &block @on_sigint = block end ## # Set this to define the behavior of exceptions during a deploy. # Defines what to do when an exception is received when running # a proc through App#interruptable. Used primarily to catch exceptions # during deploys. Passes the block the exception and a hash with the # state of the deploy: # # app.on_exception do |exception, deploy_state_hash| # # do something... # end def on_exception &block @on_exception = block end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. def handle_interruption behavior, state={} case behavior when :revert revert! if state[:symlinked] start if state[:stopped] when :console self.console! when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" menu.choice(:revert) { handle_interruption :revert, state } menu.choice(:console){ handle_interruption :console, state } menu.choice(:exit) { handle_interruption :exit, state } end else end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil copy_option = options && options.has_key?(:copy) && options[:copy] if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end rescue => e raise CriticalDeployError, e end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories rescue => e raise FatalDeployError, e end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index e7eb031..9dee76c 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -2,733 +2,733 @@ module Sunshine ## # Handles App deployment functionality for a single deploy server. # # Server apps can be assigned any number of roles for classification. # :roles:: sym|array - roles assigned (web, db, app, etc...) # By default server apps get the special :all role which will # always return true when calling: # server_app.has_roles? :some_role # # ServerApp objects can be instantiated several ways: # ServerApp.new app_instance, shell_instance, options_hash # # When passing an App instance, the new ServerApp will keep an active link # to the app's properties. Name, deploy, and path attributes will be # actively linked. # # Rely on ServerApp to create a RemoteShell instance to use: # ServerApp.new app_instance, "host.com", options_hash # # Instantiate with app name and rely on Sunshine defaults for app paths: # ServerApp.new "app_name", shell_instance, options_hash # # Explicitely assign the app's root path: # ServerApp.new "app_name", ..., :root_path => "/path/to/app_root" # # Assigning a specific deploy name to use can be done with the # :deploy_name option: # ServerApp.new "app_name", ..., :deploy_name => "deploy" class ServerApp ## # Define an attribue that will get a value from app, or locally if # @app isn't set. def self.app_attr *attribs attribs.each do |attrib| class_eval <<-STR, __FILE__, __LINE__ + 1 def #{attrib} @app ? @app.send(:#{attrib}) : @#{attrib} end STR end end ## # Creates dependency instance methods such as gem_install, yum_install, etc # on both App and ServerApp classes. def self.register_dependency_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = Hash === names.last ? names.delete_at(-1) : Hash.new names.each do |name| dep = #{dep_class}.new(name, options) dep.install! :call => @shell end end STR App.class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = names.last if Hash === names.last with_server_apps options, :msg => "Installing #{dep_class.short_name} packages", :send => [:#{dep_class.short_name}_install, *names] end STR end ## # Creates a ServerApp instance from a deploy info file. def self.from_info_file path, shell=nil shell ||= Sunshine.shell opts = YAML.load shell.call("cat #{path}") opts[:root_path] = opts.delete :path sa_shell = shell.dup sa_shell.env = opts[:env] || Hash.new sa_shell.connect if shell.connected? new opts[:name], sa_shell, opts end app_attr :name, :deploy_name app_attr :root_path, :checkout_path, :current_path app_attr :deploys_path, :log_path, :shared_path, :scripts_path attr_accessor :app, :roles, :scripts, :info, :shell, :crontab, :health attr_writer :pkg_manager ## # Create a server app instance. Supports the following # argument configurations: # # ServerApp.new app_inst, "myserver.com", :roles => :web # ServerApp.new "app_name", shell_inst, options_hash def initialize app, host, options={} @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell @health = Healthcheck.new shared_path, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No daemons for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path, :sunshine_version => Sunshine::VERSION }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec self.root_path, 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's restart script. Raises an exception on failure. # Post-deploy only. def restart! # Permissions are handled by the script, use: :sudo => false run_script! :restart, :sudo => false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the root_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} - run_script! name, options=nil, &block rescue false + run_script! name, options, &block rescue false end ## # Runs a script from the root_path. Raises an exception if the status # code is not 0. # Post-deploy only. def run_script! name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script :status, :sudo => false end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Run the app's start script. Raises an exception on failure. # Post-deploy only. def start! options=nil options ||= {} if running? return unless options[:force] stop! end # Permissions are handled by the script, use: :sudo => false run_script! :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's stop script. Raises an exception on failure. # Post-deploy only. def stop! # Permissions are handled by the script, use: :sudo => false run_script! :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} RsyncRepo.new(code_dir).checkout_to self.checkout_path, @shell @info[:scm] = scm_info end ## # Upload common rake tasks from a local path or the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', ... # #=> upload app and common rake files # # File paths may also be used instead of the file's base name but # directory structures will not be followed: # app.upload_tasks 'lib/common/app.rake', 'lib/do_thing.rake' # # Allows options: # :local_path:: str - the path to get rake tasks from # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files[-1] ? files.delete_at(-1) : {} remote_path = options[:remote_path] || "#{self.checkout_path}/lib/tasks" local_path = options[:local_path] || "#{Sunshine::ROOT}/templates/tasks" @shell.call "mkdir -p #{remote_path}" files.map! do |file| if File.basename(file) == file File.join(local_path, "#{file}.rake") else file end end files = Dir.glob("#{Sunshine::ROOT}/templates/tasks/*") if files.empty? files.each do |file| remote_file = File.join remote_path, File.basename(file) @shell.upload file, remote_file end end ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end end end
jcasts/sunshine
929db23cfeebd2e3b0711912fdf5ac5c0b398d48
added better deploy exception handling - updated history file
diff --git a/History.txt b/History.txt index 7d2116e..5f207cd 100644 --- a/History.txt +++ b/History.txt @@ -1,343 +1,359 @@ +=== 1.2.1 / 2010-10-05 + +* Improvements: + + * Added customizable behaviors for sigint and failures during deploys. + + * Added Sunshine irb shell to work directly with deploying apps. + + * Added ability to launch a pseudo terminal from a RemoteShell. + +* Bugfixes: + + * Fixed custom scripts. + + * Fixed deploy env defaults. + === 1.2.0 / 2010-09-08 * Improvements: * Added better support for custom env/start/stop/restart scripts. * Added scripts sunshine command to call custom scripts remotely. * Deploy env defaults to ENV 'DEPLOY_ENV', 'env', 'RACK_ENV', or 'RAILS_ENV'. * Bugfixes: * ServerApp#run_geminstaller no longer defaults to using sudo. * Added better extensible package manager checking to ServerApp. * Fixed Cronjob functionality and added array support. === 1.1.2 / 2010-04-15 * Improvements: * Added array support to App#find. * Added auto registration of Dependency subclasses for scalability. * Added call to App#start in App#deploy. * Bugfixes: * Fixed bug where env wouldn't be applied correctly in control scripts. * Changed App#with_filter to actually change the App#server_apps attribute. * Shell#env_cmd now returns a flattened array. * Added actual check of running process to Daemon#status_cmd. === 1.1.1 / 2010-04-05 * Improvements: * Added Repo subclass registration for greater expandability. * Added support for checking out codebases locally then rsync-ing them. * Bugfixes: * Fixed RemoteShell login script lingering after disconnect. === 1.1.0 / 2010-04-02 * Improvements: * Support for server clustering with the ServerCluster class. * Added Daemon#status method. * Added the -R option for loading external libraries and gems. * Added support for Thin and MongrelRails. * Added Server support for max connections configuration. * Bugfixes: * Daemons no longer create control scripts if they aren't used. * Fixed Rsync repo to auto append "/" to urls for correct rsyncing. === 1.0.3 / 2010-03-26 * Improvements: * Added App#call method. * Added App#with_session and Shell#with_session to reduce login prompts. * Bugfixes: * Geminstaller now always installs with sudo. * Fixed permissions issues with running servers on ports < 1024. * Fixed healthcheck middleware. === 1.0.2 / 2010-03-25 * Bugfixes: * Fixed apache passenger dependency to run as sudo. * Fixed a bug in Repo::detect === 1.0.1 / 2010-03-25 * Bugfixes: * Added json dependency === 1.0.0 / 2010-03-25 * Improvements: * Added auto_dependencies config to turn on/off auto installing things. * Added healthcheck middleware support. * Added support for Apache2 and its passenger implementation. * Removed all Atti-specific code for public release. * Bugfixes: * Fixed Nginx passenger implementation. === 0.0.6 / 2010-03-19 * Major: * Removed DeployServerDispatcher. Dispatching now happens at the App level. * Moved Settler into Sunshine and renamed it to DependencyLib. * Improvements: * Added INT signal handling to exit deploys and close connections gracefully. * Added dependency installation methods apt_install, gem_install, tpkg_install and yum_install to App and ServerApp. * Extended functionality of ServerApp#upload_tasks. * ServerApp now support being instatiated with an App instance (for coordinated deploys) or just with an app name (for post-deploy usage). * Added a Sunshine rakefile template for task-based deploys. Available through: sunshine --rakefile [COPY_TO] * App#name gets auto-assigned by repo info if not provided. * Sunshine::web_directory used to determine App#deploy_path when missing. * Repo#detect now returns a Repo object instead of an array. * Added start/stop/restart/status methods to DeployServerApp. * ServerApp instances with unspecified roles get all roles by default. * App config files now use erb parsing. Any key/value passed the App constructor as a hash should be passed to the erb binding along with the deploy_env. * Added support to bundler for defining multiple dependencies with the same name, and different package managers. * Bugfixes: * Added setup checking to Daemon to only run setup when needed. * Moved healthcheck from App to ServerApp and improved the api. * Renamed DeployServerApp to ServerApp. * Renamed App#deploy_path and App#deploys_dir to App#root_path and App#deploys_path. * Renamed the 'deploy' command to 'run' to more accurately express it's use. * RsyncRepo#do_checkout fixed to match standard Repo#do_checkout methods. * Sunshine::DATA and Sunshine::PATH are now set when running standalone ruby deploy files. === 0.0.5 / 2010-02-26 * Sunshine::App: * Use of DeployServerDispatcher threading * Fixed control script creation to be deploy_server specific (takes roles into account) * Added AttiApp class for ATTi app deployment. * Constuctor supports :deploy_name option for nameable deploys. Defaults to the timestamp. * Auto-detects if the script's directory is a checked out repo and uses it if no repo information was given. * Support for running sass. * Sunshine::DeployServerDispatcher: * Added threading support * Sunshine::Repo: * Added support for detecting a repo type based on a path: Repo.detect [path [, console_or_deploy_server]] #=> [:git, "git://url/of/git/repo", {:tree => "master", ...}] * Moved info instance methods to the class * Support for git-svn: SvnRepo.git_svn? path * Changed the checkout_to method signature * Sunshine::Server: * Added support for ar_sendmail server. === 0.0.4 / 2010-02-12 * Added sudo functionality: * Support for :sudo option on Sunshine::App, Sunshine::Server, and Sunshine::DeployServer constructors, and attr_accessor :sudo * Settler Dependency classes support a default sudo value: Sunshine::Dependencies::Gem.sudo = true # use sudo Sunshine::Dependencies::Gem.sudo = "usr" # use sudo -u usr Sunshine::Dependencies::Gem.sudo = false # ensure sudo is off Sunshine::Dependencies::Gem.sudo = nil # use :call obj precedence * App supports passing a (yml) file object to the constructor. Useful for passing file DATA if desired: app = Sunshine::App.new Sunshine::DATA app.deploy!{|app| Sunshine::Rainbows.new(app).restart } __END__ #yaml for app goes here... * App class changes: * Changed the format of the App#checkout_path directory * Logrotate setup now has to be called explicitely * Commands functionality expanded: * Support for --sudo and --sudo=user on all Sunshine commands * Added --format option for control commands. Supports txt, yml, json. * Control scripts generated on the remote server now keep deploy-time shell_env variables: * Run commands with the --no-env option to run without deploy shell_env variables. * Run any script with the app's env variables using: /path/to/app/env some_command /path/to/app/env EXTRA_VAR=some_value some_command Supports all options the env command supports. * Dependency handling now supports apt. * DeployServers now support passing custom flags for ssh and rsync: deploy_server = DeployServer.new "svr.com", :rsync_flags => [...] deploy_server.call "some_command", :sudo => "user", :flags => '-C' deploy_server.upload "from", "to", :sudo => "user", :flags => ['--chmod=ugo=rwX', '-b'] deploy_server.download "from", "to", :flags => '--ignore-existing' * Repo implementation has significantly changed: * Added support for git repo. * Info about a repo is now retrieved with Repo#get_repo_info: repo.get_repo_info deploy_server, checkout_path * Repo constructor supports options hash with :flags option. === 0.0.3 / 2010-01-29 * Many small bugfixes * Tests, tests, and more tests * Changed DeployServer api * DeployServer#run is not longer supported, use DeployServer#call * Constructor supports a spaced delimited list for roles: DeployServer.new "myhost.com", :roles => "web db other" * Changed how deploy server yaml is parsed. Should parse to be valid on: DeployServer.new *parsed_yaml Example Given: :deploy_servers : - server1.com - - server2.com - - server3.com - :roles : web db other :ssh_flags : '-o ControlMaster=auto' === 0.0.2 / 2010-01-15 * Added Control Commands * add, deploy, list, restart, rm, start, stop * Application support * Changed VERSION file to info and its format to yaml * Deployed apps now have a start, stop and restart script * Added Crontab and log rotation support * Functional changes * Ditched net/ssh and net/scp for ssh and rsync through Open4 * Fixed and updated dependencies to use Yum * Support for sunshine user configuration in ~/.sunshine * Rake tasks * Support to run the app's rake tasks * Built in default ATTi rake tasks === 0.0.1 / 2009-11-18 * 1 major enhancement * First release! diff --git a/lib/sunshine.rb b/lib/sunshine.rb index e4f0447..1765a58 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,427 +1,431 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'yaml' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' require 'irb' +# Turn off EOF tracking to be able to prompt on deploy exceptions. +HighLine.track_eof = false + + ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. VERSION = '1.2.1' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { 'auto' => false, 'auto_dependencies' => true, 'deploy_env' => :development, 'exception_behavior' => :revert, 'level' => 'info', 'max_deploy_versions' => 5, 'remote_checkouts' => false, 'timeout' => 300, 'sigint_behavior' => :revert, 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end ## # Defines what to do when deploy raises an exception. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.exception_behavior @config['exception_behavior'] || :revert end ## # Should sunshine ever ask for user input? True by default; overridden with # the -a option. def self.interactive? !@config['auto'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end ## # Defines what to do when sigint is sent during deploys. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.sigint_behavior @config['sigint_behavior'] || :revert end ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config unless File.file? USER_CONFIG_FILE File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" msg << DEFAULT_CONFIG.to_yaml self.exit 1, msg end load_config_file USER_CONFIG_FILE @config['deploy_env'] = ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] || @config['deploy_env'] @config end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset TrapStack.trap_signal :INT do |msg| $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" logger.info :INT, msg end TrapStack.add_trap "Disconnecting all remote shells." do RemoteShell.disconnect_all end require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' require 'sunshine/trap_stack' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' require 'sunshine/healthcheck' require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies' diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index 283b006..419fcdf 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -1,938 +1,948 @@ module Sunshine ## # App objects are the core of Sunshine deployment. The Sunshine paradygm # is to construct an app object, and run custom deploy code by passing # a block to its deploy method: # # someserver = Sunshine::RemoteShell.new "[email protected]", # :roles => [:web, :app] # # options = { # :name => 'myapp', # :repo => {:type => :svn, :url => 'svn://blah...'}, # :root_path => '/usr/local/myapp', # :remote_shells => '[email protected]' # } # # app = Sunshine::App.new(options) # # app.deploy do |app| # # app_server = Sunshine::Rainbows.new app, :port => 3000 # web_server = Sunshine::Nginx.new app, :point_to => app_server # # app_server.setup # web_server.setup # end # # Multiple apps can be defined, and deployed from a single deploy script. # The constructor also supports passing a yaml file path: # # Sunshine::App.new("path/to/config.yml") # # Deployment can be expressed more concisely by calling App::deploy: # # App.deploy("path/to/config.yml") do |app| # Sunshine::Rainbows.new(app).setup # end # # # An App holds information about where to deploy an application to and # how to deploy it, as well as many convenience methods to setup and # manipulate the deployment process. Most of these methods support passing # remote shell find options: # # app.rake 'db:migrate', :role => :db # app.deploy :host => 'server1.com' # # See App#find for more information. # # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml # # Yaml files must define settings on a per-environment basis. The default # environment will be used if the deploy_env is not found in the config. # Let's consider the following config: # # #config.yml: # --- # :default: # :repo: # :type: :svn # :url: http://subversion/repo/tags/release-001 # :remote_shells: dev.myserver.com # # :qa: # :remote_shells: # - qa1.myserver.com # - qa2.myserver.com # # :qa_special: # :inherits: :qa # :root_path: /path/to/application # # By default, environment definitions inherit the :default environment. In # this instance, :qa_special also inherits from :qa. # With the given config, I could setup the App instance as so: # # App.new "config.yml", :deploy_env => :development # # Note: by default, App will get the deploy_env value # # from Sunshine.deploy_env # # The above will simply load the default config. The following, however, # will load the :qa_special config which inherits from # both :qa and :default: # # App.new "config.yml", :deploy_env => :qa_special # # # Another way of instantiating an App is to pass it a hash. Unlike the yaml # config file, the hash is not on a per-environment basis and isexpected # to already have the correct values for the given environment. # The following is equivalent to loading the above :default environment: # # App.new :remote_shells => "dev.myserver.com", # :repo => { # :type => :svn, # :url => "http://subversion/repo/tags/release-001" # } # # In theory, the minimum amount of information required to instantiate # an app is the repo and remote_shells. If the repo option is omitted, # the App will attempt to detect if the pwd is a checkout out repo and # use that information. If you would like to deploy an application that # is not under source countrol, you may do so by using Sunshine::RsyncRepo, # or passing :rsync in your hash as your repo type. # # # Options supported by App.new are the following: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. class App ## # Initialize and deploy an application. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] @on_sigint = @on_exception = nil end ## # Call a command on specified server apps. # Supports any App#find and Shell#call options. def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Connect server apps. Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected. Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected. Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect server apps. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # If the deploy fails or an exception is raised, it will attempt to # run the Sunshine.failed_deploy_behavior, which is set to :revert by - # default. + # default. However, this is not true of ssh connection failures. # # If the deploy is interrupted by a SIGINT, it will attempt to run # the Sunshine.sigint_behavior, which is set to :revert by default. # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil state = { :success => false, :stopped => false, :symlinked => false } Sunshine.logger.info :app, "Beginning deploy of #{@name}" with_session options do |app| interruptable state do raise CriticalDeployError, "No servers defined for #{@name}" if @server_apps.empty? make_app_directories checkout_codebase - state[:stopped] = stop - state[:symlinked] = symlink_current_dir + state[:stopped] = true if stop + state[:symlinked] = true if symlink_current_dir yield self if block_given? run_post_user_lambdas health :enable build_control_scripts build_deploy_info_file build_crontab register_as_deployed - state[:success] = start! :force => true + state[:success] = true if start! :force => true end remove_old_deploys if state[:success] rescue Sunshine.logger.error :app, "Could not remove old deploys" state[:success] &&= deployed? end Sunshine.logger.info :app, "Finished deploy of #{@name}" state[:success] end ## # Handles SIGINTs and exceptions according to rules set by # Sunshine.sigint_behavior and Sunshine.exception_behavior # or with the override hooks App#on_sigint and App#on_exception. def interruptable options={} interrupt_trap = TrapStack.add_trap "Interrupted #{@name}" do handle_sigint options end yield if block_given? rescue => e Sunshine.logger.error :app, "#{e.class}: #{e.message}" do Sunshine.logger.error '>>', e.backtrace.join("\n") end - handle_exception options + handle_exception e, options ensure TrapStack.delete_trap interrupt_trap end ## # Calls the Apps on_sigint hook or the default Sunshine.sigint_behavior. def handle_sigint state={} - return @on_sigint.call(self, state) if @on_sigint + return @on_sigint.call(state) if @on_sigint handle_interruption Sunshine.sigint_behavior, state end ## # Calls the Apps on_exception hook or the default # Sunshine.exception_behavior. - def handle_exception state={} - return @on_exception.call(self, state) if @on_exception + def handle_exception exception, state={} + return @on_exception.call(exception, state) if @on_exception handle_interruption Sunshine.exception_behavior, state end ## # Set this to define the behavior of SIGINT during a deploy. # Defines what to do when an INT signal is received when running # a proc through App#interruptable. Used primarily to catch SIGINTs - # during deploys. + # during deploys. Passes the block a hash with the state of the deploy: + # + # app.on_sigint do |deploy_state_hash| + # deploy_state_hash + # #=> {:stopped => true, :symlinked => true, :success => false} + # end def on_sigint &block @on_sigint = block end ## # Set this to define the behavior of exceptions during a deploy. # Defines what to do when an exception is received when running # a proc through App#interruptable. Used primarily to catch exceptions - # during deploys. + # during deploys. Passes the block the exception and a hash with the + # state of the deploy: + # + # app.on_exception do |exception, deploy_state_hash| + # # do something... + # end def on_exception &block @on_exception = block end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. def handle_interruption behavior, state={} case behavior when :revert revert! if state[:symlinked] start if state[:stopped] when :console self.console! when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" - menu.choice(:revert) { handle_interrupted_deploy :revert, state } - menu.choice(:console){ handle_interrupted_deploy :console, state } - menu.choice(:exit) { handle_interrupted_deploy :exit, state } + menu.choice(:revert) { handle_interruption :revert, state } + menu.choice(:console){ handle_interruption :console, state } + menu.choice(:exit) { handle_interruption :exit, state } end else end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil copy_option = options && options.has_key?(:copy) && options[:copy] if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end rescue => e raise CriticalDeployError, e end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories rescue => e raise FatalDeployError, e end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Run the restart script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def restart! options=nil with_server_apps options, :msg => "Running restart script", :send => :restart! end ## # Runs bundler on deploy servers. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] rescue => e raise CriticalDeployError, e end ## # Runs GemInstaller on deploy servers. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] rescue => e raise CriticalDeployError, e end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run the given script of a deployed app on the specified # deploy servers. Raises an exception on failure. # Post-deploy only. def run_script! name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script!, name, options] end ## # Run a sass task on any or all deploy servers. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. def shell_env env_hash=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps :all, :no_threads => true, diff --git a/lib/sunshine/exceptions.rb b/lib/sunshine/exceptions.rb index 38b83a7..b80958e 100644 --- a/lib/sunshine/exceptions.rb +++ b/lib/sunshine/exceptions.rb @@ -1,54 +1,54 @@ module Sunshine ## # A standard sunshine exception class Exception < StandardError def initialize input=nil, message=nil if ::Exception === input message = [message, input.message].compact.join(": ") super(message) self.set_backtrace(input.backtrace) else super(input) end end end ## # An error occurred when attempting to run a command on the local system class CmdError < Exception; end ## # An ssh call returned a non-zero exit code class SSHCmdError < CmdError attr_reader :shell def initialize message=nil, shell=nil @shell = shell super(message) end end ## # Something went wrong with a deploy-specific item. class DeployError < Exception; end ## # The error is serious enough that deploy cannot proceed. # Sunshine will attempt to revert to a previous deploy if available. class CriticalDeployError < DeployError; end ## - # The error is so serious that all no more action can be taken. + # The error is so serious that no more action can be taken. # Sunshine will attempt to close any ssh connections and stop the deploy. class FatalDeployError < DeployError; end ## # A dependency could not be installed. class DependencyError < FatalDeployError; end end diff --git a/lib/sunshine/shell.rb b/lib/sunshine/shell.rb index 0f91b3d..99d1e0e 100644 --- a/lib/sunshine/shell.rb +++ b/lib/sunshine/shell.rb @@ -1,444 +1,444 @@ module Sunshine ## # The Shell class handles local input, output and execution to the shell. class Shell include Open4 class TimeoutError < CriticalDeployError; end LOCAL_USER = `whoami`.chomp LOCAL_HOST = `hostname`.chomp SUDO_FAILED = /^Sorry, try again./ SUDO_PROMPT = /^Password:/ attr_reader :user, :host, :password, :input, :output, :mutex attr_accessor :env, :sudo, :timeout def initialize output = $stdout, options={} @output = output $stdin.sync @input = HighLine.new $stdin @user = LOCAL_USER @host = LOCAL_HOST @sudo = options[:sudo] @env = options[:env] || {} @password = options[:password] @timeout = options[:timeout] || Sunshine.timeout @cmd_activity = nil @mutex = nil end ## # Checks for equality def == shell @host == shell.host && @user == shell.user rescue false end ## # Prompt the user for input. def ask(*args, &block) sync{ @input.ask(*args, &block) } end ## # Prompt the user to agree. def agree(*args, &block) sync{ @input.agree(*args, &block) } end ## # Execute a command on the local system and return the output. def call cmd, options={}, &block Sunshine.logger.info @host, "Running: #{cmd}" do execute sudo_cmd(cmd, options), &block end end ## # Prompt the user to make a choice. - def choose(&block) + def choose &block sync{ @input.choose(&block) } end ## # Close the output IO. (Required by the Logger class) def close @output.close end ## # Returns true. Compatibility method with RemoteShell. def connect true end ## # Returns true. Compatibility method with RemoteShell. def connected? true end ## # Returns true. Compatibility method with RemoteShell. def disconnect true end ## # Copies a file. Compatibility method with RemoteShell. def download from_path, to_path, options={}, &block Sunshine.logger.info @host, "Copying #{from_path} -> #{to_path}" do FileUtils.cp_r from_path, to_path end end alias upload download ## # Expands the path. Compatibility method with RemoteShell. def expand_path path File.expand_path path end ## # Checks if file exists. Compatibility method with RemoteShell. def file? filepath File.file? filepath end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " pid = fork do exec sudo_cmd(env_cmd(cmd)).to_a.join(" ") end Process.waitpid pid end end ## # Write a file. Compatibility method with RemoteShell. def make_file filepath, content, options={} File.open(filepath, "w+"){|f| f.write(content)} end ## # Get the name of the OS def os_name @os_name ||= call("uname -s").strip.downcase end ## # Prompt the user for a password def prompt_for_password host_info = [@user, @host].compact.join("@") @password = ask("#{host_info} Password:") do |q| q.echo = false end end ## # Build an env command if an env_hash is passed def env_cmd cmd, env_hash=@env if env_hash && !env_hash.empty? env_vars = env_hash.map{|e| e.join("=")} cmd = ["env", env_vars, cmd].flatten end cmd end ## # Wrap command in quotes and escape as needed. def quote_cmd cmd cmd = [*cmd].join(" ") "'#{cmd.gsub(/'/){|s| "'\\''"}}'" end ## # Build an sh -c command def sh_cmd cmd ["sh", "-c", quote_cmd(cmd)] end ## # Build a command with sudo. # If sudo_val is nil, it is considered to mean "pass-through" # and the default shell sudo will be used. # If sudo_val is false, the cmd will be returned unchanged. # If sudo_val is true, the returned command will be prefaced # with sudo -H # If sudo_val is a String, the command will be prefaced # with sudo -H -u string_value def sudo_cmd cmd, sudo_val=nil sudo_val = sudo_val[:sudo] if Hash === sudo_val sudo_val = @sudo if sudo_val.nil? case sudo_val when true ["sudo", "-H", cmd].flatten when String ["sudo", "-H", "-u", sudo_val, cmd].flatten else cmd end end ## # Force symlinking a directory. def symlink target, symlink_name call "ln -sfT #{target} #{symlink_name}" rescue false end ## # Synchronize a block with the current mutex if it exists. def sync if @mutex @mutex.synchronize{ yield } else yield end end ## # Returns true if command was run successfully, otherwise returns false. def syscall cmd, options=nil call(cmd, options) && true rescue false end ## # Checks if timeout occurred. def timed_out? start_time=@cmd_activity, max_time=@timeout return unless max_time Time.now.to_i - start_time.to_i > max_time end ## # Update the time of the last command activity def update_timeout @cmd_activity = Time.now end ## # Execute a block while setting the shell's mutex. # Sets the mutex to its original value on exit. # Executing commands with a mutex is used for user prompts. def with_mutex mutex old_mutex, @mutex = @mutex, mutex yield @mutex = old_mutex end ## # Runs the passed block within a connection session. # If the shell is already connected, connecting and disconnecting # is ignored; otherwise, the session method will ensure that # the shell's connection gets closed after the block has been # executed. def with_session prev_connection = connected? connect unless prev_connection yield disconnect unless prev_connection end ## # Write string to stdout (by default). def write str @output.write str end alias << write ## # Execute a command with open4 and loop until the process exits. # The cmd argument may be a string or an array. If a block is passed, # it will be called when data is received and passed the stream type # and stream string value: # shell.execute "test -s 'blah' && echo 'true'" do |stream, str| # stream #=> :stdout # string #=> 'true' # end # # The method returns the output from the stdout stream by default, and # raises a CmdError if the exit status of the command is not zero. def execute cmd cmd = [cmd] unless Array === cmd pid, inn, out, err = popen4(*cmd) inn.sync = true log_methods = {out => :debug, err => :error} result, status = process_streams(pid, out, err) do |stream, data| stream_name = :out if stream == out stream_name = :err if stream == err stream_name = :inn if stream == inn # User blocks should run with sync threads to avoid badness. sync do Sunshine.logger.send log_methods[stream], "#{@host}:#{stream_name}", data yield(stream_name, data, inn) if block_given? end if password_required?(stream_name, data) then kill_process(pid) unless Sunshine.interactive? send_password_to_stream(inn, data) end end raise_command_failed(status, cmd) unless status.success? result[out].join.chomp ensure inn.close rescue nil out.close rescue nil err.close rescue nil end private def raise_command_failed(status, cmd) raise CmdError, "Execution failed with status #{status.exitstatus}: #{[*cmd].join ' '}" end def password_required? stream_name, data stream_name == :err && data =~ SUDO_PROMPT end def send_password_to_stream inn, data prompt_for_password if data =~ SUDO_FAILED inn.puts @password || prompt_for_password end def kill_process pid, kill_type="KILL" begin Process.kill kill_type, pid Process.wait rescue end end def process_streams pid, *streams result = Hash.new{|h,k| h[k] = []} update_timeout # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 raise TimeoutError if timed_out? next if selected.nil? or selected.empty? selected.each do |stream| update_timeout if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) yield(stream, data) result[stream] << data end end return result, status end end end
jcasts/sunshine
59eedb124b3dce6fd6faac1a448fe3264a1c11a5
fix for ServerApp#stop and added exception raising start stop and restart methods to App
diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index a3e4b64..283b006 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -331,910 +331,958 @@ module Sunshine interrupt_trap = TrapStack.add_trap "Interrupted #{@name}" do handle_sigint options end yield if block_given? rescue => e Sunshine.logger.error :app, "#{e.class}: #{e.message}" do Sunshine.logger.error '>>', e.backtrace.join("\n") end handle_exception options ensure TrapStack.delete_trap interrupt_trap end ## # Calls the Apps on_sigint hook or the default Sunshine.sigint_behavior. def handle_sigint state={} return @on_sigint.call(self, state) if @on_sigint handle_interruption Sunshine.sigint_behavior, state end ## # Calls the Apps on_exception hook or the default # Sunshine.exception_behavior. def handle_exception state={} return @on_exception.call(self, state) if @on_exception handle_interruption Sunshine.exception_behavior, state end ## # Set this to define the behavior of SIGINT during a deploy. # Defines what to do when an INT signal is received when running # a proc through App#interruptable. Used primarily to catch SIGINTs # during deploys. def on_sigint &block @on_sigint = block end ## # Set this to define the behavior of exceptions during a deploy. # Defines what to do when an exception is received when running # a proc through App#interruptable. Used primarily to catch exceptions # during deploys. def on_exception &block @on_exception = block end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. def handle_interruption behavior, state={} case behavior when :revert revert! if state[:symlinked] start if state[:stopped] when :console self.console! when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" menu.choice(:revert) { handle_interrupted_deploy :revert, state } menu.choice(:console){ handle_interrupted_deploy :console, state } menu.choice(:exit) { handle_interrupted_deploy :exit, state } end else end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil copy_option = options && options.has_key?(:copy) && options[:copy] if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end rescue => e raise CriticalDeployError, e end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories rescue => e raise FatalDeployError, e end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end + ## + # Run the restart script of a deployed app on the specified + # deploy servers. Raises an exception on failure. + # Post-deploy only. + + def restart! options=nil + with_server_apps options, + :msg => "Running restart script", + :send => :restart! + end + + ## # Runs bundler on deploy servers. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] rescue => e raise CriticalDeployError, e end ## # Runs GemInstaller on deploy servers. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] rescue => e raise CriticalDeployError, e end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end + ## + # Run the given script of a deployed app on the specified + # deploy servers. Raises an exception on failure. + # Post-deploy only. + + def run_script! name, options=nil + with_server_apps options, + :msg => "Running #{name} script", + :send => [:run_script!, name, options] + end + + ## # Run a sass task on any or all deploy servers. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. def shell_env env_hash=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end + ## + # Run the start script of a deployed app on the specified + # deploy servers. Raises an exception on failure. + # Post-deploy only. + + def start! options=nil + with_server_apps options, + :msg => "Running start script", + :send => [:start!, options] + end + + ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. # Post-deploy only. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end + ## + # Run the stop script of a deployed app on the specified + # deploy servers. Raises an exception on failure. + # Post-deploy only. + + def stop! options=nil + with_server_apps options, + :msg => "Running stop script", + :send => :stop! + end + + ## # Use sudo on deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir rescue => e raise CriticalDeployError, e end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! def threaded_each(options=nil, &block) mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end ## # Upload common rake tasks from the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', :role => :web # #=> upload app and common rake files # # Allows standard DeployServerDispatcher#find options, plus: # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files.last ? files.last.dup : {} options.delete(:remote_path) options = :all if options.empty? with_server_apps options, :msg => "Uploading tasks: #{files.join(" ")}", :send => [:upload_tasks, *files] end ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here # end # # Note: App#with_server_apps calls App#with_session. If you do not need # or want a server connection you can pass :no_session. def with_server_apps search_options, options={} options = search_options.merge options if Hash === search_options message = options[:msg] method = options[:no_threads] ? :each : :threaded_each auto_session = !options[:no_session] block = lambda do send(method, search_options) do |server_app| if block_given? yield(server_app) elsif options[:send] server_app.send(*options[:send]) end end end msg_block = lambda do if message Sunshine.logger.info(:app, message, &block) else block.call end end auto_session ? with_session(&msg_block) : msg_block.call end ## # Runs block ensuring a connection to remote_shells. # Connecting and disconnecting will be ignored if a session # already exists. Supports all App#find options. # # Ensures that servers are disconnected after the block is run # if servers were not previously connected. def with_session options=nil with_filter options do prev_connection = connected? begin connect unless prev_connection yield self ensure disconnect unless prev_connection end end end private ## # Set all the app paths based on the root deploy path. def set_deploy_paths path @root_path = path || File.join(Sunshine.web_directory, @name) @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end ## # Set the app's deploy servers: # server_apps_from_config "some_server" # #=> [<ServerApp @host="some_server"...>] # # server_apps_from_config ["svr1", "svr2", "svr3"] # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] # # remote_shells = [["svr1", {:roles => "web db app"}], "svr2", "svr3"] # server_apps_from_config remote_shells # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] def server_apps_from_config shells shells = [*shells].compact shells.map{|shell| ServerApp.new(*[self,*shell]) } end ## # Set the app's repo: # repo_from_config SvnRepo.new("myurl") # repo_from_config :type => :svn, :url => "myurl" def repo_from_config repo_def case repo_def when Sunshine::Repo repo_def when Hash Sunshine::Repo.new_of_type repo_def[:type], repo_def[:url], repo_def else Sunshine::Repo.detect Sunshine::PATH end end ## # Load a yml config file, parses it with erb and resolves deploy env # inheritance. def config_from_file config_file, erb_binding=binding, env=@deploy_env return {} unless config_file config_data = YAML.load build_erb(config_file, erb_binding) load_config_for config_data, env end ## # Loads an app yml config file, gets the default config # and the current deploy env and returns a merged config hash. def load_config_for config_hash, env return {} unless config_hash deploy_env_config = (config_hash[env] || {}).dup deploy_env_config[:inherits] ||= [] deploy_env_config[:inherits].unshift(:default) if :default != env && config_hash[:default] merge_config_inheritance deploy_env_config, config_hash end ## # Recursively merges config hashes based on the value at :inherits def merge_config_inheritance main_config, all_configs new_config = {} parents = [*main_config[:inherits]].compact parents.each do |config_name| parent = all_configs[config_name] parent = merge_config_inheritance parent, all_configs new_config = new_config.merge parent end new_config.merge main_config # Two merges important for inheritance order end end end diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index cab5fad..e7eb031 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -109,626 +109,626 @@ module Sunshine @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell @health = Healthcheck.new shared_path, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No daemons for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path, :sunshine_version => Sunshine::VERSION }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec self.root_path, 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's restart script. Raises an exception on failure. # Post-deploy only. def restart! # Permissions are handled by the script, use: :sudo => false run_script! :restart, :sudo => false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the root_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} run_script! name, options=nil, &block rescue false end ## # Runs a script from the root_path. Raises an exception if the status # code is not 0. # Post-deploy only. def run_script! name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script :status, :sudo => false end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Run the app's start script. Raises an exception on failure. # Post-deploy only. def start! options=nil options ||= {} if running? return unless options[:force] stop! end # Permissions are handled by the script, use: :sudo => false run_script! :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Run the app's stop script. Raises an exception on failure. # Post-deploy only. - def stop + def stop! # Permissions are handled by the script, use: :sudo => false run_script! :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} RsyncRepo.new(code_dir).checkout_to self.checkout_path, @shell @info[:scm] = scm_info end ## # Upload common rake tasks from a local path or the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', ... # #=> upload app and common rake files # # File paths may also be used instead of the file's base name but # directory structures will not be followed: # app.upload_tasks 'lib/common/app.rake', 'lib/do_thing.rake' # # Allows options: # :local_path:: str - the path to get rake tasks from # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files[-1] ? files.delete_at(-1) : {} remote_path = options[:remote_path] || "#{self.checkout_path}/lib/tasks" local_path = options[:local_path] || "#{Sunshine::ROOT}/templates/tasks" @shell.call "mkdir -p #{remote_path}" files.map! do |file| if File.basename(file) == file File.join(local_path, "#{file}.rake") else file end end files = Dir.glob("#{Sunshine::ROOT}/templates/tasks/*") if files.empty? files.each do |file| remote_file = File.join remote_path, File.basename(file) @shell.upload file, remote_file end end ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end end end
jcasts/sunshine
b89fa6e9ade3c5b5c30af8e02dd4ee17a7cbbc7a
added App#interruptable method to handle exceptions and sigints during deploys
diff --git a/lib/sunshine.rb b/lib/sunshine.rb index b71288d..e4f0447 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,427 +1,427 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'yaml' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' require 'irb' ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. VERSION = '1.2.1' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { 'auto' => false, 'auto_dependencies' => true, 'deploy_env' => :development, - 'failed_deploy_behavior' => :revert, + 'exception_behavior' => :revert, 'level' => 'info', 'max_deploy_versions' => 5, 'remote_checkouts' => false, 'timeout' => 300, 'sigint_behavior' => :revert, 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end ## # Defines what to do when deploy raises an exception. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. - def self.failed_deploy_behavior - @config['failed_deploy_behavior'] || :revert + def self.exception_behavior + @config['exception_behavior'] || :revert end ## # Should sunshine ever ask for user input? True by default; overridden with # the -a option. def self.interactive? !@config['auto'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end ## # Defines what to do when sigint is sent during deploys. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.sigint_behavior @config['sigint_behavior'] || :revert end ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config unless File.file? USER_CONFIG_FILE File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" msg << DEFAULT_CONFIG.to_yaml self.exit 1, msg end load_config_file USER_CONFIG_FILE @config['deploy_env'] = ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] || @config['deploy_env'] @config end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset TrapStack.trap_signal :INT do |msg| $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" logger.info :INT, msg end TrapStack.add_trap "Disconnecting all remote shells." do RemoteShell.disconnect_all end require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' require 'sunshine/trap_stack' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' require 'sunshine/healthcheck' require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies' diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index d748034..a3e4b64 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -1,872 +1,925 @@ module Sunshine ## # App objects are the core of Sunshine deployment. The Sunshine paradygm # is to construct an app object, and run custom deploy code by passing # a block to its deploy method: # # someserver = Sunshine::RemoteShell.new "[email protected]", # :roles => [:web, :app] # # options = { # :name => 'myapp', # :repo => {:type => :svn, :url => 'svn://blah...'}, # :root_path => '/usr/local/myapp', # :remote_shells => '[email protected]' # } # # app = Sunshine::App.new(options) # # app.deploy do |app| # # app_server = Sunshine::Rainbows.new app, :port => 3000 # web_server = Sunshine::Nginx.new app, :point_to => app_server # # app_server.setup # web_server.setup # end # # Multiple apps can be defined, and deployed from a single deploy script. # The constructor also supports passing a yaml file path: # # Sunshine::App.new("path/to/config.yml") # # Deployment can be expressed more concisely by calling App::deploy: # # App.deploy("path/to/config.yml") do |app| # Sunshine::Rainbows.new(app).setup # end # # # An App holds information about where to deploy an application to and # how to deploy it, as well as many convenience methods to setup and # manipulate the deployment process. Most of these methods support passing # remote shell find options: # # app.rake 'db:migrate', :role => :db # app.deploy :host => 'server1.com' # # See App#find for more information. # # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml # # Yaml files must define settings on a per-environment basis. The default # environment will be used if the deploy_env is not found in the config. # Let's consider the following config: # # #config.yml: # --- # :default: # :repo: # :type: :svn # :url: http://subversion/repo/tags/release-001 # :remote_shells: dev.myserver.com # # :qa: # :remote_shells: # - qa1.myserver.com # - qa2.myserver.com # # :qa_special: # :inherits: :qa # :root_path: /path/to/application # # By default, environment definitions inherit the :default environment. In # this instance, :qa_special also inherits from :qa. # With the given config, I could setup the App instance as so: # # App.new "config.yml", :deploy_env => :development # # Note: by default, App will get the deploy_env value # # from Sunshine.deploy_env # # The above will simply load the default config. The following, however, # will load the :qa_special config which inherits from # both :qa and :default: # # App.new "config.yml", :deploy_env => :qa_special # # # Another way of instantiating an App is to pass it a hash. Unlike the yaml # config file, the hash is not on a per-environment basis and isexpected # to already have the correct values for the given environment. # The following is equivalent to loading the above :default environment: # # App.new :remote_shells => "dev.myserver.com", # :repo => { # :type => :svn, # :url => "http://subversion/repo/tags/release-001" # } # # In theory, the minimum amount of information required to instantiate # an app is the repo and remote_shells. If the repo option is omitted, # the App will attempt to detect if the pwd is a checkout out repo and # use that information. If you would like to deploy an application that # is not under source countrol, you may do so by using Sunshine::RsyncRepo, # or passing :rsync in your hash as your repo type. # # # Options supported by App.new are the following: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. class App ## # Initialize and deploy an application. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] + + @on_sigint = @on_exception = nil end ## # Call a command on specified server apps. # Supports any App#find and Shell#call options. def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Connect server apps. Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected. Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected. Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect server apps. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # If the deploy fails or an exception is raised, it will attempt to # run the Sunshine.failed_deploy_behavior, which is set to :revert by # default. # # If the deploy is interrupted by a SIGINT, it will attempt to run # the Sunshine.sigint_behavior, which is set to :revert by default. # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil state = { :success => false, :stopped => false, :symlinked => false } - deploy_trap = - TrapStack.add_trap "Interrupted deploy of #{@name}" do - handle_interrupted_deploy Sunshine.sigint_behavior, state - end - Sunshine.logger.info :app, "Beginning deploy of #{@name}" with_session options do |app| - begin + interruptable state do raise CriticalDeployError, "No servers defined for #{@name}" if @server_apps.empty? make_app_directories checkout_codebase - state[:stopped] = stop - + state[:stopped] = stop state[:symlinked] = symlink_current_dir - yield(self) if block_given? + yield self if block_given? run_post_user_lambdas health :enable build_control_scripts build_deploy_info_file build_crontab register_as_deployed state[:success] = start! :force => true - - rescue => e - Sunshine.logger.error :app, "#{e.class}: #{e.message}" do - Sunshine.logger.error '>>', e.backtrace.join("\n") - end - - handle_interrupted_deploy Sunshine.failed_deploy_behavior, state end remove_old_deploys if state[:success] rescue Sunshine.logger.error :app, "Could not remove old deploys" state[:success] &&= deployed? end Sunshine.logger.info :app, "Finished deploy of #{@name}" + state[:success] + end + + + ## + # Handles SIGINTs and exceptions according to rules set by + # Sunshine.sigint_behavior and Sunshine.exception_behavior + # or with the override hooks App#on_sigint and App#on_exception. + + def interruptable options={} + interrupt_trap = + TrapStack.add_trap "Interrupted #{@name}" do + handle_sigint options + end + + yield if block_given? + + rescue => e + Sunshine.logger.error :app, "#{e.class}: #{e.message}" do + Sunshine.logger.error '>>', e.backtrace.join("\n") + end + + handle_exception options ensure - TrapStack.delete_trap deploy_trap - state[:success] + TrapStack.delete_trap interrupt_trap + end + + + ## + # Calls the Apps on_sigint hook or the default Sunshine.sigint_behavior. + + def handle_sigint state={} + return @on_sigint.call(self, state) if @on_sigint + handle_interruption Sunshine.sigint_behavior, state + end + + + ## + # Calls the Apps on_exception hook or the default + # Sunshine.exception_behavior. + + def handle_exception state={} + return @on_exception.call(self, state) if @on_exception + handle_interruption Sunshine.exception_behavior, state + end + + + ## + # Set this to define the behavior of SIGINT during a deploy. + # Defines what to do when an INT signal is received when running + # a proc through App#interruptable. Used primarily to catch SIGINTs + # during deploys. + + def on_sigint &block + @on_sigint = block + end + + + + ## + # Set this to define the behavior of exceptions during a deploy. + # Defines what to do when an exception is received when running + # a proc through App#interruptable. Used primarily to catch exceptions + # during deploys. + + def on_exception &block + @on_exception = block end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. - def handle_interrupted_deploy behavior, state={} + def handle_interruption behavior, state={} case behavior when :revert - revert! if state[:symlinked] - start if state[:stopped] + revert! if state[:symlinked] + start if state[:stopped] when :console self.console! when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" menu.choice(:revert) { handle_interrupted_deploy :revert, state } menu.choice(:console){ handle_interrupted_deploy :console, state } menu.choice(:exit) { handle_interrupted_deploy :exit, state } end else end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil copy_option = options && options.has_key?(:copy) && options[:copy] if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end rescue => e raise CriticalDeployError, e end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories rescue => e raise FatalDeployError, e end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Runs bundler on deploy servers. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] rescue => e raise CriticalDeployError, e end ## # Runs GemInstaller on deploy servers. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] rescue => e raise CriticalDeployError, e end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run a sass task on any or all deploy servers. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. def shell_env env_hash=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified
jcasts/sunshine
685849e9ff3bb02591eda1e94009057269ee2737
added non-rescued script running to server app
diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index 4e85a4c..d748034 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -1,828 +1,827 @@ module Sunshine ## # App objects are the core of Sunshine deployment. The Sunshine paradygm # is to construct an app object, and run custom deploy code by passing # a block to its deploy method: # # someserver = Sunshine::RemoteShell.new "[email protected]", # :roles => [:web, :app] # # options = { # :name => 'myapp', # :repo => {:type => :svn, :url => 'svn://blah...'}, # :root_path => '/usr/local/myapp', # :remote_shells => '[email protected]' # } # # app = Sunshine::App.new(options) # # app.deploy do |app| # # app_server = Sunshine::Rainbows.new app, :port => 3000 # web_server = Sunshine::Nginx.new app, :point_to => app_server # # app_server.setup # web_server.setup # end # # Multiple apps can be defined, and deployed from a single deploy script. # The constructor also supports passing a yaml file path: # # Sunshine::App.new("path/to/config.yml") # # Deployment can be expressed more concisely by calling App::deploy: # # App.deploy("path/to/config.yml") do |app| # Sunshine::Rainbows.new(app).setup # end # # # An App holds information about where to deploy an application to and # how to deploy it, as well as many convenience methods to setup and # manipulate the deployment process. Most of these methods support passing # remote shell find options: # # app.rake 'db:migrate', :role => :db # app.deploy :host => 'server1.com' # # See App#find for more information. # # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml # # Yaml files must define settings on a per-environment basis. The default # environment will be used if the deploy_env is not found in the config. # Let's consider the following config: # # #config.yml: # --- # :default: # :repo: # :type: :svn # :url: http://subversion/repo/tags/release-001 # :remote_shells: dev.myserver.com # # :qa: # :remote_shells: # - qa1.myserver.com # - qa2.myserver.com # # :qa_special: # :inherits: :qa # :root_path: /path/to/application # # By default, environment definitions inherit the :default environment. In # this instance, :qa_special also inherits from :qa. # With the given config, I could setup the App instance as so: # # App.new "config.yml", :deploy_env => :development # # Note: by default, App will get the deploy_env value # # from Sunshine.deploy_env # # The above will simply load the default config. The following, however, # will load the :qa_special config which inherits from # both :qa and :default: # # App.new "config.yml", :deploy_env => :qa_special # # # Another way of instantiating an App is to pass it a hash. Unlike the yaml # config file, the hash is not on a per-environment basis and isexpected # to already have the correct values for the given environment. # The following is equivalent to loading the above :default environment: # # App.new :remote_shells => "dev.myserver.com", # :repo => { # :type => :svn, # :url => "http://subversion/repo/tags/release-001" # } # # In theory, the minimum amount of information required to instantiate # an app is the repo and remote_shells. If the repo option is omitted, # the App will attempt to detect if the pwd is a checkout out repo and # use that information. If you would like to deploy an application that # is not under source countrol, you may do so by using Sunshine::RsyncRepo, # or passing :rsync in your hash as your repo type. # # # Options supported by App.new are the following: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. class App ## # Initialize and deploy an application. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] end ## # Call a command on specified server apps. # Supports any App#find and Shell#call options. def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Connect server apps. Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected. Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected. Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect server apps. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # If the deploy fails or an exception is raised, it will attempt to # run the Sunshine.failed_deploy_behavior, which is set to :revert by # default. # # If the deploy is interrupted by a SIGINT, it will attempt to run # the Sunshine.sigint_behavior, which is set to :revert by default. # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil state = { :success => false, :stopped => false, :symlinked => false } deploy_trap = TrapStack.add_trap "Interrupted deploy of #{@name}" do handle_interrupted_deploy Sunshine.sigint_behavior, state end Sunshine.logger.info :app, "Beginning deploy of #{@name}" with_session options do |app| begin raise CriticalDeployError, "No servers defined for #{@name}" if @server_apps.empty? make_app_directories checkout_codebase state[:stopped] = stop state[:symlinked] = symlink_current_dir yield(self) if block_given? run_post_user_lambdas health :enable build_control_scripts build_deploy_info_file build_crontab register_as_deployed - state[:success] = start(:force => true) || - raise(CriticalDeployError, "Could not start #{@name}") + state[:success] = start! :force => true rescue => e Sunshine.logger.error :app, "#{e.class}: #{e.message}" do Sunshine.logger.error '>>', e.backtrace.join("\n") end handle_interrupted_deploy Sunshine.failed_deploy_behavior, state end remove_old_deploys if state[:success] rescue Sunshine.logger.error :app, "Could not remove old deploys" state[:success] &&= deployed? end Sunshine.logger.info :app, "Finished deploy of #{@name}" ensure TrapStack.delete_trap deploy_trap state[:success] end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. def handle_interrupted_deploy behavior, state={} case behavior when :revert revert! if state[:symlinked] start if state[:stopped] when :console self.console! when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" menu.choice(:revert) { handle_interrupted_deploy :revert, state } menu.choice(:console){ handle_interrupted_deploy :console, state } menu.choice(:exit) { handle_interrupted_deploy :exit, state } end else end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil copy_option = options && options.has_key?(:copy) && options[:copy] if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end rescue => e raise CriticalDeployError, e end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories rescue => e raise FatalDeployError, e end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Runs bundler on deploy servers. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] rescue => e raise CriticalDeployError, e end ## # Runs GemInstaller on deploy servers. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] rescue => e raise CriticalDeployError, e end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index c5e94e1..cab5fad 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -1,685 +1,734 @@ module Sunshine ## # Handles App deployment functionality for a single deploy server. # # Server apps can be assigned any number of roles for classification. # :roles:: sym|array - roles assigned (web, db, app, etc...) # By default server apps get the special :all role which will # always return true when calling: # server_app.has_roles? :some_role # # ServerApp objects can be instantiated several ways: # ServerApp.new app_instance, shell_instance, options_hash # # When passing an App instance, the new ServerApp will keep an active link # to the app's properties. Name, deploy, and path attributes will be # actively linked. # # Rely on ServerApp to create a RemoteShell instance to use: # ServerApp.new app_instance, "host.com", options_hash # # Instantiate with app name and rely on Sunshine defaults for app paths: # ServerApp.new "app_name", shell_instance, options_hash # # Explicitely assign the app's root path: # ServerApp.new "app_name", ..., :root_path => "/path/to/app_root" # # Assigning a specific deploy name to use can be done with the # :deploy_name option: # ServerApp.new "app_name", ..., :deploy_name => "deploy" class ServerApp ## # Define an attribue that will get a value from app, or locally if # @app isn't set. def self.app_attr *attribs attribs.each do |attrib| class_eval <<-STR, __FILE__, __LINE__ + 1 def #{attrib} @app ? @app.send(:#{attrib}) : @#{attrib} end STR end end ## # Creates dependency instance methods such as gem_install, yum_install, etc # on both App and ServerApp classes. def self.register_dependency_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = Hash === names.last ? names.delete_at(-1) : Hash.new names.each do |name| dep = #{dep_class}.new(name, options) dep.install! :call => @shell end end STR App.class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = names.last if Hash === names.last with_server_apps options, :msg => "Installing #{dep_class.short_name} packages", :send => [:#{dep_class.short_name}_install, *names] end STR end ## # Creates a ServerApp instance from a deploy info file. def self.from_info_file path, shell=nil shell ||= Sunshine.shell opts = YAML.load shell.call("cat #{path}") opts[:root_path] = opts.delete :path sa_shell = shell.dup sa_shell.env = opts[:env] || Hash.new sa_shell.connect if shell.connected? new opts[:name], sa_shell, opts end app_attr :name, :deploy_name app_attr :root_path, :checkout_path, :current_path app_attr :deploys_path, :log_path, :shared_path, :scripts_path attr_accessor :app, :roles, :scripts, :info, :shell, :crontab, :health attr_writer :pkg_manager ## # Create a server app instance. Supports the following # argument configurations: # # ServerApp.new app_inst, "myserver.com", :roles => :web # ServerApp.new "app_name", shell_inst, options_hash def initialize app, host, options={} @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell @health = Healthcheck.new shared_path, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No daemons for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path, :sunshine_version => Sunshine::VERSION }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec self.root_path, 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart - @shell.call "#{self.root_path}/restart" rescue false + # Permissions are handled by the script, use: :sudo => false + run_script :stop, :sudo => false + end + + + ## + # Run the app's restart script. Raises an exception on failure. + # Post-deploy only. + + def restart! + # Permissions are handled by the script, use: :sudo => false + run_script! :restart, :sudo => false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## - # Runs a script from the script_path. + # Runs a script from the root_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} + run_script! name, options=nil, &block rescue false + end + + + ## + # Runs a script from the root_path. Raises an exception if the status + # code is not 0. + # Post-deploy only. + + def run_script! name, options=nil, &block + options ||= {} script_path = File.join self.root_path, name.to_s - @shell.call script_path, options, &block rescue false + @shell.call script_path, options, &block end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script :status, :sudo => false end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end + ## + # Run the app's start script. Raises an exception on failure. + # Post-deploy only. + + def start! options=nil + options ||= {} + + if running? + return unless options[:force] + stop! + end + + # Permissions are handled by the script, use: :sudo => false + run_script! :start, :sudo => false + end + + ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end + ## + # Run the app's stop script. Raises an exception on failure. + # Post-deploy only. + + def stop + # Permissions are handled by the script, use: :sudo => false + run_script! :stop, :sudo => false + end + + ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} RsyncRepo.new(code_dir).checkout_to self.checkout_path, @shell @info[:scm] = scm_info end ## # Upload common rake tasks from a local path or the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', ... # #=> upload app and common rake files # # File paths may also be used instead of the file's base name but # directory structures will not be followed: # app.upload_tasks 'lib/common/app.rake', 'lib/do_thing.rake' # # Allows options: # :local_path:: str - the path to get rake tasks from # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files[-1] ? files.delete_at(-1) : {} remote_path = options[:remote_path] || "#{self.checkout_path}/lib/tasks" local_path = options[:local_path] || "#{Sunshine::ROOT}/templates/tasks" @shell.call "mkdir -p #{remote_path}" files.map! do |file| if File.basename(file) == file File.join(local_path, "#{file}.rake") else file end end files = Dir.glob("#{Sunshine::ROOT}/templates/tasks/*") if files.empty? files.each do |file| remote_file = File.join remote_path, File.basename(file) @shell.upload file, remote_file end end ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end end end
jcasts/sunshine
45a3ede8b58514ebdc357cb38fd6af310391c576
fixed retrieving deploy env from ENV
diff --git a/lib/sunshine.rb b/lib/sunshine.rb index f66851e..b71288d 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,424 +1,427 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'yaml' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' require 'irb' ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. VERSION = '1.2.1' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { - 'auto' => false, - 'auto_dependencies' => true, - 'deploy_env' => - ( ENV['DEPLOY_ENV'] || - ENV['env'] || - ENV['RACK_ENV'] || - ENV['RAILS_ENV'] || - :development ), + 'auto' => false, + 'auto_dependencies' => true, + 'deploy_env' => :development, 'failed_deploy_behavior' => :revert, - 'level' => 'info', - 'max_deploy_versions' => 5, - 'remote_checkouts' => false, - 'timeout' => 300, - 'sigint_behavior' => :revert, - 'web_directory' => '/srv/http' + 'level' => 'info', + 'max_deploy_versions' => 5, + 'remote_checkouts' => false, + 'timeout' => 300, + 'sigint_behavior' => :revert, + 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end ## # Defines what to do when deploy raises an exception. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.failed_deploy_behavior @config['failed_deploy_behavior'] || :revert end ## # Should sunshine ever ask for user input? True by default; overridden with # the -a option. def self.interactive? !@config['auto'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end ## # Defines what to do when sigint is sent during deploys. # Supported values are: # ::revert: Revert to the previous deploy. # ::console: Start an interactive ruby shell within the app's context. # ::exit: Stop deploy and exit, leaving deploy in unfinished state. # ::prompt: Ask what to do. # Defaults to :revert. Overridden in the config. def self.sigint_behavior @config['sigint_behavior'] || :revert end ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config unless File.file? USER_CONFIG_FILE File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" msg << DEFAULT_CONFIG.to_yaml self.exit 1, msg end load_config_file USER_CONFIG_FILE + + @config['deploy_env'] = + ENV['DEPLOY_ENV'] || + ENV['env'] || + ENV['RACK_ENV'] || + ENV['RAILS_ENV'] || + @config['deploy_env'] + + @config end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset - TrapStack.trap_signal :INT do |msg| $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" logger.info :INT, msg end TrapStack.add_trap "Disconnecting all remote shells." do RemoteShell.disconnect_all end require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' require 'sunshine/trap_stack' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' require 'sunshine/healthcheck' require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies' diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index 7368ff8..4e85a4c 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -1,838 +1,838 @@ module Sunshine ## # App objects are the core of Sunshine deployment. The Sunshine paradygm # is to construct an app object, and run custom deploy code by passing # a block to its deploy method: # # someserver = Sunshine::RemoteShell.new "[email protected]", # :roles => [:web, :app] # # options = { # :name => 'myapp', # :repo => {:type => :svn, :url => 'svn://blah...'}, # :root_path => '/usr/local/myapp', # :remote_shells => '[email protected]' # } # # app = Sunshine::App.new(options) # # app.deploy do |app| # # app_server = Sunshine::Rainbows.new app, :port => 3000 # web_server = Sunshine::Nginx.new app, :point_to => app_server # # app_server.setup # web_server.setup # end # # Multiple apps can be defined, and deployed from a single deploy script. # The constructor also supports passing a yaml file path: # # Sunshine::App.new("path/to/config.yml") # # Deployment can be expressed more concisely by calling App::deploy: # # App.deploy("path/to/config.yml") do |app| # Sunshine::Rainbows.new(app).setup # end # # # An App holds information about where to deploy an application to and # how to deploy it, as well as many convenience methods to setup and # manipulate the deployment process. Most of these methods support passing # remote shell find options: # # app.rake 'db:migrate', :role => :db # app.deploy :host => 'server1.com' # # See App#find for more information. # # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml # # Yaml files must define settings on a per-environment basis. The default # environment will be used if the deploy_env is not found in the config. # Let's consider the following config: # # #config.yml: # --- # :default: # :repo: # :type: :svn # :url: http://subversion/repo/tags/release-001 # :remote_shells: dev.myserver.com # # :qa: # :remote_shells: # - qa1.myserver.com # - qa2.myserver.com # # :qa_special: # :inherits: :qa # :root_path: /path/to/application # # By default, environment definitions inherit the :default environment. In # this instance, :qa_special also inherits from :qa. # With the given config, I could setup the App instance as so: # # App.new "config.yml", :deploy_env => :development # # Note: by default, App will get the deploy_env value # # from Sunshine.deploy_env # # The above will simply load the default config. The following, however, # will load the :qa_special config which inherits from # both :qa and :default: # # App.new "config.yml", :deploy_env => :qa_special # # # Another way of instantiating an App is to pass it a hash. Unlike the yaml # config file, the hash is not on a per-environment basis and isexpected # to already have the correct values for the given environment. # The following is equivalent to loading the above :default environment: # # App.new :remote_shells => "dev.myserver.com", # :repo => { # :type => :svn, # :url => "http://subversion/repo/tags/release-001" # } # # In theory, the minimum amount of information required to instantiate # an app is the repo and remote_shells. If the repo option is omitted, # the App will attempt to detect if the pwd is a checkout out repo and # use that information. If you would like to deploy an application that # is not under source countrol, you may do so by using Sunshine::RsyncRepo, # or passing :rsync in your hash as your repo type. # # # Options supported by App.new are the following: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. class App ## # Initialize and deploy an application. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] end ## # Call a command on specified server apps. # Supports any App#find and Shell#call options. def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Connect server apps. Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected. Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected. Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect server apps. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # If the deploy fails or an exception is raised, it will attempt to # run the Sunshine.failed_deploy_behavior, which is set to :revert by # default. # # If the deploy is interrupted by a SIGINT, it will attempt to run # the Sunshine.sigint_behavior, which is set to :revert by default. # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil state = { :success => false, :stopped => false, :symlinked => false } deploy_trap = TrapStack.add_trap "Interrupted deploy of #{@name}" do handle_interrupted_deploy Sunshine.sigint_behavior, state end Sunshine.logger.info :app, "Beginning deploy of #{@name}" with_session options do |app| begin raise CriticalDeployError, "No servers defined for #{@name}" if @server_apps.empty? make_app_directories checkout_codebase state[:stopped] = stop state[:symlinked] = symlink_current_dir yield(self) if block_given? run_post_user_lambdas health :enable build_control_scripts build_deploy_info_file build_crontab register_as_deployed state[:success] = start(:force => true) || raise(CriticalDeployError, "Could not start #{@name}") rescue => e Sunshine.logger.error :app, "#{e.class}: #{e.message}" do Sunshine.logger.error '>>', e.backtrace.join("\n") end handle_interrupted_deploy Sunshine.failed_deploy_behavior, state end - remove_old_deploys rescue + remove_old_deploys if state[:success] rescue Sunshine.logger.error :app, "Could not remove old deploys" state[:success] &&= deployed? end Sunshine.logger.info :app, "Finished deploy of #{@name}" ensure TrapStack.delete_trap deploy_trap state[:success] end ## # Handles the behavior of a failed or interrupted deploy. # Takes a behavior symbol defining how to handle the interruption # and a hash representing the state of the deploy when it was # interrupted. # # Supported bahavior symbols are: # ::revert: Revert to previous deploy (default) # ::console: Start an interactive console with the app's binding # ::exit: Stop deploy and exit # ::prompt: Ask what to do # # The state hash supports the following keys: # ::stopped: Was the previous deploy stopped. # ::symlinked: Was the new deployed symlinked as the current deploy. def handle_interrupted_deploy behavior, state={} case behavior when :revert revert! if state[:symlinked] start if state[:stopped] when :console self.console! when :exit Sunshine.exit 1, "Error: Deploy of #{@name} failed" when :prompt Sunshine.shell.choose do |menu| menu.prompt = "Deploy interrupted:" menu.choice(:revert) { handle_interrupted_deploy :revert, state } menu.choice(:console){ handle_interrupted_deploy :console, state } menu.choice(:exit) { handle_interrupted_deploy :exit, state } end else end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil copy_option = options && options.has_key?(:copy) && options[:copy] if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end rescue => e raise CriticalDeployError, e end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories rescue => e raise FatalDeployError, e end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Runs bundler on deploy servers. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] rescue => e raise CriticalDeployError, e end ## # Runs GemInstaller on deploy servers. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] rescue => e raise CriticalDeployError, e end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end
jcasts/sunshine
d46d997a5af63f1585763c2813c772cb79d48f33
added ability to change default behavior of sigint and deploy failures
diff --git a/lib/sunshine.rb b/lib/sunshine.rb index 26c3666..f66851e 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,395 +1,424 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'yaml' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' require 'irb' -IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. VERSION = '1.2.1' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { 'auto' => false, 'auto_dependencies' => true, 'deploy_env' => ( ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] || :development ), + 'failed_deploy_behavior' => :revert, 'level' => 'info', 'max_deploy_versions' => 5, 'remote_checkouts' => false, 'timeout' => 300, + 'sigint_behavior' => :revert, 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end + ## + # Defines what to do when deploy raises an exception. + # Supported values are: + # ::revert: Revert to the previous deploy. + # ::console: Start an interactive ruby shell within the app's context. + # ::exit: Stop deploy and exit, leaving deploy in unfinished state. + # ::prompt: Ask what to do. + # Defaults to :revert. Overridden in the config. + + def self.failed_deploy_behavior + @config['failed_deploy_behavior'] || :revert + end + + ## # Should sunshine ever ask for user input? True by default; overridden with # the -a option. def self.interactive? !@config['auto'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end + ## + # Defines what to do when sigint is sent during deploys. + # Supported values are: + # ::revert: Revert to the previous deploy. + # ::console: Start an interactive ruby shell within the app's context. + # ::exit: Stop deploy and exit, leaving deploy in unfinished state. + # ::prompt: Ask what to do. + # Defaults to :revert. Overridden in the config. + + def self.sigint_behavior + @config['sigint_behavior'] || :revert + end + + ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config unless File.file? USER_CONFIG_FILE File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" msg << DEFAULT_CONFIG.to_yaml self.exit 1, msg end load_config_file USER_CONFIG_FILE end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset TrapStack.trap_signal :INT do |msg| $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" logger.info :INT, msg end TrapStack.add_trap "Disconnecting all remote shells." do RemoteShell.disconnect_all end require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' require 'sunshine/trap_stack' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' require 'sunshine/healthcheck' require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies' diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index 17e6a2b..7368ff8 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -1,1138 +1,1188 @@ module Sunshine ## # App objects are the core of Sunshine deployment. The Sunshine paradygm # is to construct an app object, and run custom deploy code by passing # a block to its deploy method: # # someserver = Sunshine::RemoteShell.new "[email protected]", # :roles => [:web, :app] # # options = { # :name => 'myapp', # :repo => {:type => :svn, :url => 'svn://blah...'}, # :root_path => '/usr/local/myapp', # :remote_shells => '[email protected]' # } # # app = Sunshine::App.new(options) # # app.deploy do |app| # # app_server = Sunshine::Rainbows.new app, :port => 3000 # web_server = Sunshine::Nginx.new app, :point_to => app_server # # app_server.setup # web_server.setup # end # # Multiple apps can be defined, and deployed from a single deploy script. # The constructor also supports passing a yaml file path: # # Sunshine::App.new("path/to/config.yml") # # Deployment can be expressed more concisely by calling App::deploy: # # App.deploy("path/to/config.yml") do |app| # Sunshine::Rainbows.new(app).setup # end # # # An App holds information about where to deploy an application to and # how to deploy it, as well as many convenience methods to setup and # manipulate the deployment process. Most of these methods support passing # remote shell find options: # # app.rake 'db:migrate', :role => :db # app.deploy :host => 'server1.com' # # See App#find for more information. # # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml # # Yaml files must define settings on a per-environment basis. The default # environment will be used if the deploy_env is not found in the config. # Let's consider the following config: # # #config.yml: # --- # :default: # :repo: # :type: :svn # :url: http://subversion/repo/tags/release-001 # :remote_shells: dev.myserver.com # # :qa: # :remote_shells: # - qa1.myserver.com # - qa2.myserver.com # # :qa_special: # :inherits: :qa # :root_path: /path/to/application # # By default, environment definitions inherit the :default environment. In # this instance, :qa_special also inherits from :qa. # With the given config, I could setup the App instance as so: # # App.new "config.yml", :deploy_env => :development # # Note: by default, App will get the deploy_env value # # from Sunshine.deploy_env # # The above will simply load the default config. The following, however, # will load the :qa_special config which inherits from # both :qa and :default: # # App.new "config.yml", :deploy_env => :qa_special # # # Another way of instantiating an App is to pass it a hash. Unlike the yaml # config file, the hash is not on a per-environment basis and isexpected # to already have the correct values for the given environment. # The following is equivalent to loading the above :default environment: # # App.new :remote_shells => "dev.myserver.com", # :repo => { # :type => :svn, # :url => "http://subversion/repo/tags/release-001" # } # # In theory, the minimum amount of information required to instantiate # an app is the repo and remote_shells. If the repo option is omitted, # the App will attempt to detect if the pwd is a checkout out repo and # use that information. If you would like to deploy an application that # is not under source countrol, you may do so by using Sunshine::RsyncRepo, # or passing :rsync in your hash as your repo type. # # # Options supported by App.new are the following: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. class App ## # Initialize and deploy an application. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] - - @has_session = false end ## # Call a command on specified server apps. # Supports any App#find and Shell#call options. def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Connect server apps. Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected. Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected. Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect server apps. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # + # If the deploy fails or an exception is raised, it will attempt to + # run the Sunshine.failed_deploy_behavior, which is set to :revert by + # default. + # + # If the deploy is interrupted by a SIGINT, it will attempt to run + # the Sunshine.sigint_behavior, which is set to :revert by default. + # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil - raise CriticalDeployError, "No servers defined for #{@name}" if - @server_apps.empty? - - success = false - stopped = false - symlinked = false - prev_connection = connected? + state = { + :success => false, + :stopped => false, + :symlinked => false + } deploy_trap = - TrapStack.add_trap "Reverting deploy of #{@name}" do - revert! options if symlinked - start options if stopped - disconnect options unless prev_connection + TrapStack.add_trap "Interrupted deploy of #{@name}" do + handle_interrupted_deploy Sunshine.sigint_behavior, state end Sunshine.logger.info :app, "Beginning deploy of #{@name}" with_session options do |app| - make_app_directories - checkout_codebase + begin + raise CriticalDeployError, "No servers defined for #{@name}" if + @server_apps.empty? + + make_app_directories + checkout_codebase - stopped = stop + state[:stopped] = stop - symlinked = symlink_current_dir + state[:symlinked] = symlink_current_dir - yield(self) if block_given? + yield(self) if block_given? - run_post_user_lambdas + run_post_user_lambdas - health :enable + health :enable - build_control_scripts - build_deploy_info_file - build_crontab + build_control_scripts + build_deploy_info_file + build_crontab - register_as_deployed + register_as_deployed - success = start(:force => true) || - raise(CriticalDeployError, "Could not start #{@name}") + state[:success] = start(:force => true) || + raise(CriticalDeployError, "Could not start #{@name}") - remove_old_deploys - success &&= deployed? - end + rescue => e + Sunshine.logger.error :app, "#{e.class}: #{e.message}" do + Sunshine.logger.error '>>', e.backtrace.join("\n") + end - Sunshine.logger.info :app, "Ending deploy of #{@name}" + handle_interrupted_deploy Sunshine.failed_deploy_behavior, state + end - rescue => e - message = "#{e.class}: #{e.message}" + remove_old_deploys rescue + Sunshine.logger.error :app, "Could not remove old deploys" - Sunshine.logger.error :app, message do - Sunshine.logger.error '>>', e.backtrace.join("\n") - revert! options if symlinked - start options if stopped + state[:success] &&= deployed? end + Sunshine.logger.info :app, "Finished deploy of #{@name}" + ensure - disconnect options unless prev_connection || !any_connected? TrapStack.delete_trap deploy_trap + state[:success] + end + - success + ## + # Handles the behavior of a failed or interrupted deploy. + # Takes a behavior symbol defining how to handle the interruption + # and a hash representing the state of the deploy when it was + # interrupted. + # + # Supported bahavior symbols are: + # ::revert: Revert to previous deploy (default) + # ::console: Start an interactive console with the app's binding + # ::exit: Stop deploy and exit + # ::prompt: Ask what to do + # + # The state hash supports the following keys: + # ::stopped: Was the previous deploy stopped. + # ::symlinked: Was the new deployed symlinked as the current deploy. + + def handle_interrupted_deploy behavior, state={} + case behavior + + when :revert + revert! if state[:symlinked] + start if state[:stopped] + + when :console + self.console! + + when :exit + Sunshine.exit 1, "Error: Deploy of #{@name} failed" + + when :prompt + Sunshine.shell.choose do |menu| + menu.prompt = "Deploy interrupted:" + menu.choice(:revert) { handle_interrupted_deploy :revert, state } + menu.choice(:console){ handle_interrupted_deploy :console, state } + menu.choice(:exit) { handle_interrupted_deploy :exit, state } + end + + else + end end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! + IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) + workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil copy_option = options && options.has_key?(:copy) && options[:copy] if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end rescue => e raise CriticalDeployError, e end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories rescue => e raise FatalDeployError, e end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Runs bundler on deploy servers. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] rescue => e raise CriticalDeployError, e end ## # Runs GemInstaller on deploy servers. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] rescue => e raise CriticalDeployError, e end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run a sass task on any or all deploy servers. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. def shell_env env_hash=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. # Post-deploy only. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end ## # Use sudo on deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir rescue => e raise CriticalDeployError, e end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! def threaded_each(options=nil, &block) mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end ## # Upload common rake tasks from the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', :role => :web # #=> upload app and common rake files # # Allows standard DeployServerDispatcher#find options, plus: # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files.last ? files.last.dup : {} options.delete(:remote_path) options = :all if options.empty? with_server_apps options, :msg => "Uploading tasks: #{files.join(" ")}", :send => [:upload_tasks, *files] end ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here # end # # Note: App#with_server_apps calls App#with_session. If you do not need # or want a server connection you can pass :no_session. def with_server_apps search_options, options={} options = search_options.merge options if Hash === search_options message = options[:msg] method = options[:no_threads] ? :each : :threaded_each auto_session = !options[:no_session] block = lambda do send(method, search_options) do |server_app| if block_given? yield(server_app) elsif options[:send] server_app.send(*options[:send]) end end end msg_block = lambda do if message Sunshine.logger.info(:app, message, &block) else block.call end end auto_session ? with_session(&msg_block) : msg_block.call end ## # Runs block ensuring a connection to remote_shells. # Connecting and disconnecting will be ignored if a session # already exists. Supports all App#find options. + # + # Ensures that servers are disconnected after the block is run + # if servers were not previously connected. def with_session options=nil with_filter options do - begin + prev_connection = connected? - prev_connection = connected? + begin connect unless prev_connection - yield self ensure disconnect unless prev_connection end end end private ## # Set all the app paths based on the root deploy path. def set_deploy_paths path @root_path = path || File.join(Sunshine.web_directory, @name) @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end ## # Set the app's deploy servers: # server_apps_from_config "some_server" # #=> [<ServerApp @host="some_server"...>] # # server_apps_from_config ["svr1", "svr2", "svr3"] # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] # # remote_shells = [["svr1", {:roles => "web db app"}], "svr2", "svr3"] # server_apps_from_config remote_shells # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] def server_apps_from_config shells shells = [*shells].compact shells.map{|shell| ServerApp.new(*[self,*shell]) } end ## # Set the app's repo: # repo_from_config SvnRepo.new("myurl") # repo_from_config :type => :svn, :url => "myurl" def repo_from_config repo_def case repo_def when Sunshine::Repo repo_def when Hash Sunshine::Repo.new_of_type repo_def[:type], repo_def[:url], repo_def else Sunshine::Repo.detect Sunshine::PATH end end ## # Load a yml config file, parses it with erb and resolves deploy env # inheritance. def config_from_file config_file, erb_binding=binding, env=@deploy_env return {} unless config_file config_data = YAML.load build_erb(config_file, erb_binding) load_config_for config_data, env end ## # Loads an app yml config file, gets the default config # and the current deploy env and returns a merged config hash. def load_config_for config_hash, env return {} unless config_hash deploy_env_config = (config_hash[env] || {}).dup deploy_env_config[:inherits] ||= [] deploy_env_config[:inherits].unshift(:default) if :default != env && config_hash[:default] merge_config_inheritance deploy_env_config, config_hash end ## # Recursively merges config hashes based on the value at :inherits def merge_config_inheritance main_config, all_configs new_config = {} parents = [*main_config[:inherits]].compact parents.each do |config_name| parent = all_configs[config_name] parent = merge_config_inheritance parent, all_configs new_config = new_config.merge parent end new_config.merge main_config # Two merges important for inheritance order end end end diff --git a/lib/sunshine/shell.rb b/lib/sunshine/shell.rb index 304a357..0f91b3d 100644 --- a/lib/sunshine/shell.rb +++ b/lib/sunshine/shell.rb @@ -1,436 +1,444 @@ module Sunshine ## # The Shell class handles local input, output and execution to the shell. class Shell include Open4 class TimeoutError < CriticalDeployError; end LOCAL_USER = `whoami`.chomp LOCAL_HOST = `hostname`.chomp SUDO_FAILED = /^Sorry, try again./ SUDO_PROMPT = /^Password:/ attr_reader :user, :host, :password, :input, :output, :mutex attr_accessor :env, :sudo, :timeout def initialize output = $stdout, options={} @output = output $stdin.sync @input = HighLine.new $stdin @user = LOCAL_USER @host = LOCAL_HOST @sudo = options[:sudo] @env = options[:env] || {} @password = options[:password] @timeout = options[:timeout] || Sunshine.timeout @cmd_activity = nil @mutex = nil end ## # Checks for equality def == shell @host == shell.host && @user == shell.user rescue false end ## # Prompt the user for input. def ask(*args, &block) sync{ @input.ask(*args, &block) } end ## # Prompt the user to agree. def agree(*args, &block) sync{ @input.agree(*args, &block) } end ## # Execute a command on the local system and return the output. def call cmd, options={}, &block Sunshine.logger.info @host, "Running: #{cmd}" do execute sudo_cmd(cmd, options), &block end end + ## + # Prompt the user to make a choice. + + def choose(&block) + sync{ @input.choose(&block) } + end + + ## # Close the output IO. (Required by the Logger class) def close @output.close end ## # Returns true. Compatibility method with RemoteShell. def connect true end ## # Returns true. Compatibility method with RemoteShell. def connected? true end ## # Returns true. Compatibility method with RemoteShell. def disconnect true end ## # Copies a file. Compatibility method with RemoteShell. def download from_path, to_path, options={}, &block Sunshine.logger.info @host, "Copying #{from_path} -> #{to_path}" do FileUtils.cp_r from_path, to_path end end alias upload download ## # Expands the path. Compatibility method with RemoteShell. def expand_path path File.expand_path path end ## # Checks if file exists. Compatibility method with RemoteShell. def file? filepath File.file? filepath end ## # Start an interactive shell with preset permissions and env. # Optionally pass a command to be run first. def tty! cmd=nil sync do cmd = [cmd, "sh -il"].compact.join " && " pid = fork do exec sudo_cmd(env_cmd(cmd)).to_a.join(" ") end Process.waitpid pid end end ## # Write a file. Compatibility method with RemoteShell. def make_file filepath, content, options={} File.open(filepath, "w+"){|f| f.write(content)} end ## # Get the name of the OS def os_name @os_name ||= call("uname -s").strip.downcase end ## # Prompt the user for a password def prompt_for_password host_info = [@user, @host].compact.join("@") @password = ask("#{host_info} Password:") do |q| q.echo = false end end ## # Build an env command if an env_hash is passed def env_cmd cmd, env_hash=@env if env_hash && !env_hash.empty? env_vars = env_hash.map{|e| e.join("=")} cmd = ["env", env_vars, cmd].flatten end cmd end ## # Wrap command in quotes and escape as needed. def quote_cmd cmd cmd = [*cmd].join(" ") "'#{cmd.gsub(/'/){|s| "'\\''"}}'" end ## # Build an sh -c command def sh_cmd cmd ["sh", "-c", quote_cmd(cmd)] end ## # Build a command with sudo. # If sudo_val is nil, it is considered to mean "pass-through" # and the default shell sudo will be used. # If sudo_val is false, the cmd will be returned unchanged. # If sudo_val is true, the returned command will be prefaced # with sudo -H # If sudo_val is a String, the command will be prefaced # with sudo -H -u string_value def sudo_cmd cmd, sudo_val=nil sudo_val = sudo_val[:sudo] if Hash === sudo_val sudo_val = @sudo if sudo_val.nil? case sudo_val when true ["sudo", "-H", cmd].flatten when String ["sudo", "-H", "-u", sudo_val, cmd].flatten else cmd end end ## # Force symlinking a directory. def symlink target, symlink_name call "ln -sfT #{target} #{symlink_name}" rescue false end ## # Synchronize a block with the current mutex if it exists. def sync if @mutex @mutex.synchronize{ yield } else yield end end ## # Returns true if command was run successfully, otherwise returns false. def syscall cmd, options=nil call(cmd, options) && true rescue false end ## # Checks if timeout occurred. def timed_out? start_time=@cmd_activity, max_time=@timeout return unless max_time Time.now.to_i - start_time.to_i > max_time end ## # Update the time of the last command activity def update_timeout @cmd_activity = Time.now end ## # Execute a block while setting the shell's mutex. # Sets the mutex to its original value on exit. # Executing commands with a mutex is used for user prompts. def with_mutex mutex old_mutex, @mutex = @mutex, mutex yield @mutex = old_mutex end ## # Runs the passed block within a connection session. # If the shell is already connected, connecting and disconnecting # is ignored; otherwise, the session method will ensure that # the shell's connection gets closed after the block has been # executed. def with_session prev_connection = connected? connect unless prev_connection yield disconnect unless prev_connection end ## # Write string to stdout (by default). def write str @output.write str end alias << write ## # Execute a command with open4 and loop until the process exits. # The cmd argument may be a string or an array. If a block is passed, # it will be called when data is received and passed the stream type # and stream string value: # shell.execute "test -s 'blah' && echo 'true'" do |stream, str| # stream #=> :stdout # string #=> 'true' # end # # The method returns the output from the stdout stream by default, and # raises a CmdError if the exit status of the command is not zero. def execute cmd cmd = [cmd] unless Array === cmd pid, inn, out, err = popen4(*cmd) inn.sync = true log_methods = {out => :debug, err => :error} result, status = process_streams(pid, out, err) do |stream, data| stream_name = :out if stream == out stream_name = :err if stream == err stream_name = :inn if stream == inn # User blocks should run with sync threads to avoid badness. sync do Sunshine.logger.send log_methods[stream], "#{@host}:#{stream_name}", data yield(stream_name, data, inn) if block_given? end if password_required?(stream_name, data) then kill_process(pid) unless Sunshine.interactive? send_password_to_stream(inn, data) end end raise_command_failed(status, cmd) unless status.success? result[out].join.chomp ensure inn.close rescue nil out.close rescue nil err.close rescue nil end private def raise_command_failed(status, cmd) raise CmdError, "Execution failed with status #{status.exitstatus}: #{[*cmd].join ' '}" end def password_required? stream_name, data stream_name == :err && data =~ SUDO_PROMPT end def send_password_to_stream inn, data prompt_for_password if data =~ SUDO_FAILED inn.puts @password || prompt_for_password end def kill_process pid, kill_type="KILL" begin Process.kill kill_type, pid Process.wait rescue end end def process_streams pid, *streams result = Hash.new{|h,k| h[k] = []} update_timeout # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 raise TimeoutError if timed_out? next if selected.nil? or selected.empty? selected.each do |stream| update_timeout if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) yield(stream, data) result[stream] << data end end return result, status end end end
jcasts/sunshine
63aec631ae512fea9102b3abf76eb4dc55026e52
added commands doc for -S
diff --git a/lib/commands/list.rb b/lib/commands/list.rb index c052806..ec4523d 100644 --- a/lib/commands/list.rb +++ b/lib/commands/list.rb @@ -1,322 +1,323 @@ module Sunshine ## # List and perform simple state actions on lists of sunshine apps. # # Usage: sunshine list [options] app_name [more names...] # # Arguments: # app_name Name of an application to list. # # Options: # -s, --status Check if an app is running. # -d, --details Get details about the deployed apps. # -h, --health [STATUS] Set or get the healthcheck status. # (enable, disable, remove) # -f, --format FORMAT Set the output format (txt, yml, json) # -u, --user USER User to use for remote login. Use with -r # -r, --remote svr1,svr2 Run on one or more remote servers. + # -S, --sudo Run remote commands using sudo or sudo -u USER # -v, --verbose Run in verbose mode. class ListCommand < DefaultCommand ## # Takes an array and a hash, runs the command and returns: # true: success # false: failed # exitcode: # code == 0: success # code != 0: failed # and optionally an accompanying message. def self.exec names, config action = config['return'] || :exist? args = config[action.to_s] || [] args = [args, names].flatten output = exec_each_server config do |shell| new(shell).send(action, *args) end return output end ## # Executes common list functionality for each deploy server. def self.exec_each_server config shells = config['servers'] format = config['format'] responses = {} success = true shells.each do |shell| shell.with_session do begin state, response = yield(shell) rescue => e state = false response = "#{e.class}: #{e.message}\n#{e.backtrace.join("\n")}" end host = shell.host success = state if success responses[host] = build_response state, response end end output = format ? self.send(format, responses) : responses return success, output end ## # Formats response as text output: # ------------------ # subdomain.host.com # ------------------ # app_name: running def self.txt_format res_hash str_out = "" res_hash.each do |host, response| separator = "-" * host.length host_status = if Hash === response[:data] apps_status = response[:data].map do |app_name, status| "#{app_name}: #{status[:data]}\n" end apps_status.join("\n") else response[:data] end str_out << "\n" str_out << [separator, host, separator].join("\n") str_out << "\n" str_out << host_status str_out << "\n" end str_out end ## # Formats response as yaml: def self.yml_format res_hash res_hash.to_yaml end ## # Formats response as json: def self.json_format res_hash res_hash.to_json end attr_accessor :app_list, :shell def initialize shell @shell = shell @app_list = self.class.load_list @shell end ## # Reads and returns the specified apps' info file. # Returns a response hash (see ListCommand#each_app). def details(*app_names) each_app(*app_names) do |server_app| "\n#{server_app.deploy_details.to_yaml}" end end ## # Returns the path of specified apps. # Returns a response hash (see ListCommand#each_app). def exist?(*app_names) each_app(*app_names) do |server_app| server_app.root_path end end ## # Get or set the healthcheck state. # Returns a response hash (see ListCommand#each_app). def health(*app_names) action = app_names.delete_at(0) if Symbol === app_names.first each_app(*app_names) do |server_app| server_app.health.send action if action server_app.health.status end end ## # Checks if the apps' pids are present. # Returns a response hash (see ListCommand#each_app). def status(*app_names) each_app(*app_names) do |server_app| server_app.status end end ## # Runs a command and returns the status for each app_name: # status_after_command 'restart', ['app1', 'app2'] def status_after_command cmd, app_names each_app(*app_names) do |server_app| yield(server_app) if block_given? begin server_app.run_script cmd server_app.running? ? 'running' : 'down' rescue CmdError => e raise "Failed running #{cmd}: #{server_app.status}" end end end # Do something with each server app and build a response hash: # each_app do |server_app| # ... # end # # Restrict it to a set of apps if they are present on the server: # each_app('app1', 'app2') do |server_app| # ... # end # # Returns a response hash: # {"app_name" => {:success => true, :data => "somedata"} ...} def each_app(*app_names) app_names = @app_list.keys if app_names.empty? response_for_each(*app_names) do |name| path = @app_list[name] raise "Application not found." unless path server_app = ServerApp.new name, @shell, :root_path => path yield(server_app) if block_given? end end ## # Builds a response object for each item passed and returns # the result of the passed block as its data value. def response_for_each(*items) response = {} success = true items.each do |item| begin data = yield(item) if block_given? response[item] = self.class.build_response true, data rescue => e success = false response[item] = self.class.build_response false, e.message end end [success, response] end ## # Builds a standard response entry: # {:success => true, :data => "somedata"} def self.build_response success, data=nil {:success => success, :data => data} end ## # Load the app list yaml file from the server. def self.load_list server - yml_list = server.call "cat #{Sunshine::APP_LIST_PATH} || echo ''" + yml_list = server.call "cat #{Sunshine::APP_LIST_PATH} || echo" list = YAML.load yml_list list = {} unless Hash === list list end ## # Write the app list hash to the remote server. def self.save_list list, server path = server.expand_path Sunshine::APP_LIST_PATH server.make_file path, list.to_yaml end ## # Parses the argv passed to the command def self.parse_args argv parse_remote_args(argv) do |opt, options| opt.banner = <<-EOF Usage: #{opt.program_name} list [options] app_name [more names...] Arguments: app_name Name of an application to list. EOF opt.on('-s', '--status', 'Check if an app is running.') do options['return'] = :status end opt.on('-d', '--details', 'Get details about the deployed apps.') do options['return'] = :details end vals = [:enable, :disable, :remove] desc = "Set or get the healthcheck status. (#{vals.join(", ")})" opt.on('-h', '--health [STATUS]', vals, desc) do |status| options['health'] = status.to_sym if status options['return'] = :health end end end end end diff --git a/lib/commands/restart.rb b/lib/commands/restart.rb index 737788d..54d645a 100644 --- a/lib/commands/restart.rb +++ b/lib/commands/restart.rb @@ -1,62 +1,63 @@ module Sunshine ## # Runs the restart script of all specified sunshine apps. # # Usage: sunshine restart [options] app_name [more names...] # # Arguments: # app_name Name of the application to restart. # # Options: - # -f, --format FORMAT Set the output format (txt, yml, json) - # -u, --user USER User to use for remote login. Use with -r. - # -r, --remote svr1,svr2 Run on one or more remote servers. - # -v, --verbose Run in verbose mode. + # -f, --format FORMAT Set the output format (txt, yml, json) + # -u, --user USER User to use for remote login. Use with -r. + # -r, --remote svr1,svr2 Run on one or more remote servers. + # -S, --sudo Run remote commands using sudo or sudo -u USER + # -v, --verbose Run in verbose mode. class RestartCommand < ListCommand ## # Takes an array and a hash, runs the command and returns: # true: success # false: failed # exitcode: # code == 0: success # code != 0: failed # and optionally an accompanying message. def self.exec names, config output = exec_each_server config do |shell| new(shell).restart(names) end return output end ## # Restart specified apps. def restart app_names status_after_command :restart, app_names end ## # Parses the argv passed to the command def self.parse_args argv parse_remote_args(argv) do |opt, options| opt.banner = <<-EOF Usage: #{opt.program_name} restart [options] app_name [more names...] Arguments: app_name Name of the application to restart. EOF end end end end diff --git a/lib/commands/rm.rb b/lib/commands/rm.rb index 3f9b5a0..90005cb 100644 --- a/lib/commands/rm.rb +++ b/lib/commands/rm.rb @@ -1,83 +1,84 @@ module Sunshine ## # Unregister a sunshine app. # # Usage: sunshine rm [options] app_name [more names...] # # Arguments: # app_name Name of the application to remove. # # Options: - # -d, --delete Delete the app directory. - # -f, --format FORMAT Set the output format (txt, yml, json) - # -u, --user USER User to use for remote login. Use with -r. - # -r, --remote svr1,svr2 Run on one or more remote servers. - # -v, --verbose Run in verbose mode. + # -d, --delete Delete the app directory. + # -f, --format FORMAT Set the output format (txt, yml, json) + # -u, --user USER User to use for remote login. Use with -r. + # -r, --remote svr1,svr2 Run on one or more remote servers. + # -S, --sudo Run remote commands using sudo or sudo -u USER + # -v, --verbose Run in verbose mode. class RmCommand < ListCommand ## # Takes an array and a hash, runs the command and returns: # true: success # false: failed # exitcode: # code == 0: success # code != 0: failed # and optionally an accompanying message. def self.exec names, config delete_dir = config['delete_dir'] output = exec_each_server config do |shell| server_command = new(shell) results = server_command.remove(names, delete_dir) self.save_list server_command.app_list, shell results end return output end ## # Remove a registered app on a given deploy server def remove app_names, delete_dir=false each_app(*app_names) do |server_app| if delete_dir server_app.stop rescue nil server_app.shell.call "rm -rf #{server_app.root_path}" server_app.crontab.delete! end @app_list.delete server_app.name end end ## # Parses the argv passed to the command def self.parse_args argv parse_remote_args(argv) do |opt, options| opt.banner = <<-EOF Usage: #{opt.program_name} rm [options] app_name [more names...] Arguments: app_name Name of the application to remove. EOF opt.on('-d', '--delete', 'Delete the app directory.') do options['delete_dir'] = true end end end end end diff --git a/lib/commands/script.rb b/lib/commands/script.rb index ac53319..a95491f 100644 --- a/lib/commands/script.rb +++ b/lib/commands/script.rb @@ -1,67 +1,68 @@ module Sunshine ## # Runs a given script of all specified sunshine apps. # # Usage: sunshine script script_name [options] app_name [more names...] # # Arguments: # script_name Name of the script to run. # app_name Name of the application to run script for. # # Options: - # -f, --format FORMAT Set the output format (txt, yml, json) - # -u, --user USER User to use for remote login. Use with -r. - # -r, --remote svr1,svr2 Run on one or more remote servers. - # -v, --verbose Run in verbose mode. + # -f, --format FORMAT Set the output format (txt, yml, json) + # -u, --user USER User to use for remote login. Use with -r. + # -r, --remote svr1,svr2 Run on one or more remote servers. + # -S, --sudo Run remote commands using sudo or sudo -u USER + # -v, --verbose Run in verbose mode. class ScriptCommand < ListCommand ## # Takes an array and a hash, runs the command and returns: # true: success # false: failed # exitcode: # code == 0: success # code != 0: failed # and optionally an accompanying message. def self.exec names, config script_name = names.delete_at(0) output = exec_each_server config do |shell| new(shell).script(script_name, names) end return output end ## # Run specified script for apps. def script name, app_names each_app(*app_names) do |server_app| server_app.run_script name end end ## # Parses the argv passed to the command def self.parse_args argv parse_remote_args(argv) do |opt, options| opt.banner = <<-EOF Usage: #{opt.program_name} script script_name [options] app_name [more names...] Arguments: script_name Name of the script to run. app_name Name of the application to run script for. EOF end end end end diff --git a/lib/commands/stop.rb b/lib/commands/stop.rb index 678360b..36f346b 100644 --- a/lib/commands/stop.rb +++ b/lib/commands/stop.rb @@ -1,61 +1,62 @@ module Sunshine ## # Runs the stop script of all specified sunshine apps. # # Usage: sunshine stop [options] app_name [more names...] # # Arguments: # app_name Name of the application to stop. # # Options: - # -f, --format FORMAT Set the output format (txt, yml, json) - # -u, --user USER User to use for remote login. Use with -r. - # -r, --remote svr1,svr2 Run on one or more remote servers. - # -v, --verbose Run in verbose mode. + # -f, --format FORMAT Set the output format (txt, yml, json) + # -u, --user USER User to use for remote login. Use with -r. + # -r, --remote svr1,svr2 Run on one or more remote servers. + # -S, --sudo Run remote commands using sudo or sudo -u USER + # -v, --verbose Run in verbose mode. class StopCommand < ListCommand ## # Takes an array and a hash, runs the command and returns: # true: success # false: failed # exitcode: # code == 0: success # code != 0: failed # and optionally an accompanying message. def self.exec names, config output = exec_each_server config do |shell| new(shell).stop(names) end return output end ## # Stop specified apps. def stop app_names status_after_command :stop, app_names end ## # Parses the argv passed to the command def self.parse_args argv parse_remote_args(argv) do |opt, options| opt.banner = <<-EOF Usage: #{opt.program_name} stop [options] app_name [more names...] Arguments: app_name Name of the application to stop. EOF end end end end
jcasts/sunshine
8e3b7cc00c742f04e044136e146aafe17999d4c7
added load error rescuing for sunshine for dev purposes
diff --git a/bin/sunshine b/bin/sunshine index 08ff6ba..e2050e4 100755 --- a/bin/sunshine +++ b/bin/sunshine @@ -1,5 +1,12 @@ #!/usr/bin/env ruby -w -require 'sunshine' +begin + require 'sunshine' +rescue LoadError => e + raise e unless e.message =~ %r{no such file to load -- sunshine} + + $: << File.join(File.dirname(__FILE__), "../lib") + require 'sunshine' +end Sunshine.run
jcasts/sunshine
5a7a8e5cc66adff29bdfaaafef0a45fe22ea8114
with_session now calls with_filter as per expected behavior when passing server find options
diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index 8957496..17e6a2b 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -1,1136 +1,1138 @@ module Sunshine ## # App objects are the core of Sunshine deployment. The Sunshine paradygm # is to construct an app object, and run custom deploy code by passing # a block to its deploy method: # # someserver = Sunshine::RemoteShell.new "[email protected]", # :roles => [:web, :app] # # options = { # :name => 'myapp', # :repo => {:type => :svn, :url => 'svn://blah...'}, # :root_path => '/usr/local/myapp', # :remote_shells => '[email protected]' # } # # app = Sunshine::App.new(options) # # app.deploy do |app| # # app_server = Sunshine::Rainbows.new app, :port => 3000 # web_server = Sunshine::Nginx.new app, :point_to => app_server # # app_server.setup # web_server.setup # end # # Multiple apps can be defined, and deployed from a single deploy script. # The constructor also supports passing a yaml file path: # # Sunshine::App.new("path/to/config.yml") # # Deployment can be expressed more concisely by calling App::deploy: # # App.deploy("path/to/config.yml") do |app| # Sunshine::Rainbows.new(app).setup # end # # # An App holds information about where to deploy an application to and # how to deploy it, as well as many convenience methods to setup and # manipulate the deployment process. Most of these methods support passing # remote shell find options: # # app.rake 'db:migrate', :role => :db # app.deploy :host => 'server1.com' # # See App#find for more information. # # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml # # Yaml files must define settings on a per-environment basis. The default # environment will be used if the deploy_env is not found in the config. # Let's consider the following config: # # #config.yml: # --- # :default: # :repo: # :type: :svn # :url: http://subversion/repo/tags/release-001 # :remote_shells: dev.myserver.com # # :qa: # :remote_shells: # - qa1.myserver.com # - qa2.myserver.com # # :qa_special: # :inherits: :qa # :root_path: /path/to/application # # By default, environment definitions inherit the :default environment. In # this instance, :qa_special also inherits from :qa. # With the given config, I could setup the App instance as so: # # App.new "config.yml", :deploy_env => :development # # Note: by default, App will get the deploy_env value # # from Sunshine.deploy_env # # The above will simply load the default config. The following, however, # will load the :qa_special config which inherits from # both :qa and :default: # # App.new "config.yml", :deploy_env => :qa_special # # # Another way of instantiating an App is to pass it a hash. Unlike the yaml # config file, the hash is not on a per-environment basis and isexpected # to already have the correct values for the given environment. # The following is equivalent to loading the above :default environment: # # App.new :remote_shells => "dev.myserver.com", # :repo => { # :type => :svn, # :url => "http://subversion/repo/tags/release-001" # } # # In theory, the minimum amount of information required to instantiate # an app is the repo and remote_shells. If the repo option is omitted, # the App will attempt to detect if the pwd is a checkout out repo and # use that information. If you would like to deploy an application that # is not under source countrol, you may do so by using Sunshine::RsyncRepo, # or passing :rsync in your hash as your repo type. # # # Options supported by App.new are the following: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. class App ## # Initialize and deploy an application. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] @has_session = false end ## # Call a command on specified server apps. # Supports any App#find and Shell#call options. def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Connect server apps. Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected. Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected. Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect server apps. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil raise CriticalDeployError, "No servers defined for #{@name}" if @server_apps.empty? success = false stopped = false symlinked = false prev_connection = connected? deploy_trap = TrapStack.add_trap "Reverting deploy of #{@name}" do revert! options if symlinked start options if stopped disconnect options unless prev_connection end Sunshine.logger.info :app, "Beginning deploy of #{@name}" - with_session options do + with_session options do |app| - with_filter options do |app| - make_app_directories - checkout_codebase + make_app_directories + checkout_codebase - stopped = stop + stopped = stop - symlinked = symlink_current_dir + symlinked = symlink_current_dir - yield(self) if block_given? + yield(self) if block_given? - run_post_user_lambdas + run_post_user_lambdas - health :enable + health :enable - build_control_scripts - build_deploy_info_file - build_crontab + build_control_scripts + build_deploy_info_file + build_crontab - register_as_deployed + register_as_deployed - success = start(:force => true) || - raise(CriticalDeployError, "Could not start #{@name}") + success = start(:force => true) || + raise(CriticalDeployError, "Could not start #{@name}") - remove_old_deploys - success &&= deployed? - end + remove_old_deploys + success &&= deployed? end Sunshine.logger.info :app, "Ending deploy of #{@name}" rescue => e message = "#{e.class}: #{e.message}" Sunshine.logger.error :app, message do Sunshine.logger.error '>>', e.backtrace.join("\n") revert! options if symlinked start options if stopped end ensure disconnect options unless prev_connection || !any_connected? TrapStack.delete_trap deploy_trap success end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil copy_option = options && options.has_key?(:copy) && options[:copy] if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end rescue => e raise CriticalDeployError, e end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories rescue => e raise FatalDeployError, e end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Runs bundler on deploy servers. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] rescue => e raise CriticalDeployError, e end ## # Runs GemInstaller on deploy servers. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] rescue => e raise CriticalDeployError, e end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run a sass task on any or all deploy servers. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. def shell_env env_hash=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. # Post-deploy only. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end ## # Use sudo on deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir rescue => e raise CriticalDeployError, e end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! def threaded_each(options=nil, &block) mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end ## # Upload common rake tasks from the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', :role => :web # #=> upload app and common rake files # # Allows standard DeployServerDispatcher#find options, plus: # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files.last ? files.last.dup : {} options.delete(:remote_path) options = :all if options.empty? with_server_apps options, :msg => "Uploading tasks: #{files.join(" ")}", :send => [:upload_tasks, *files] end ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here # end # # Note: App#with_server_apps calls App#with_session. If you do not need # or want a server connection you can pass :no_session. def with_server_apps search_options, options={} options = search_options.merge options if Hash === search_options message = options[:msg] method = options[:no_threads] ? :each : :threaded_each auto_session = !options[:no_session] block = lambda do send(method, search_options) do |server_app| if block_given? yield(server_app) elsif options[:send] server_app.send(*options[:send]) end end end msg_block = lambda do if message Sunshine.logger.info(:app, message, &block) else block.call end end auto_session ? with_session(&msg_block) : msg_block.call end ## # Runs block ensuring a connection to remote_shells. # Connecting and disconnecting will be ignored if a session # already exists. Supports all App#find options. def with_session options=nil + with_filter options do + begin - prev_connection = connected?(options) - connect options unless prev_connection + prev_connection = connected? + connect unless prev_connection - yield self + yield self - ensure - disconnect options unless prev_connection + ensure + disconnect unless prev_connection + end + end end private ## # Set all the app paths based on the root deploy path. def set_deploy_paths path @root_path = path || File.join(Sunshine.web_directory, @name) @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end ## # Set the app's deploy servers: # server_apps_from_config "some_server" # #=> [<ServerApp @host="some_server"...>] # # server_apps_from_config ["svr1", "svr2", "svr3"] # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] # # remote_shells = [["svr1", {:roles => "web db app"}], "svr2", "svr3"] # server_apps_from_config remote_shells # #=> [<ServerApp @host="svr1">,<ServerApp @host="svr2">, ...] def server_apps_from_config shells shells = [*shells].compact shells.map{|shell| ServerApp.new(*[self,*shell]) } end ## # Set the app's repo: # repo_from_config SvnRepo.new("myurl") # repo_from_config :type => :svn, :url => "myurl" def repo_from_config repo_def case repo_def when Sunshine::Repo repo_def when Hash Sunshine::Repo.new_of_type repo_def[:type], repo_def[:url], repo_def else Sunshine::Repo.detect Sunshine::PATH end end ## # Load a yml config file, parses it with erb and resolves deploy env # inheritance. def config_from_file config_file, erb_binding=binding, env=@deploy_env return {} unless config_file config_data = YAML.load build_erb(config_file, erb_binding) load_config_for config_data, env end ## # Loads an app yml config file, gets the default config # and the current deploy env and returns a merged config hash. def load_config_for config_hash, env return {} unless config_hash deploy_env_config = (config_hash[env] || {}).dup deploy_env_config[:inherits] ||= [] deploy_env_config[:inherits].unshift(:default) if :default != env && config_hash[:default] merge_config_inheritance deploy_env_config, config_hash end ## # Recursively merges config hashes based on the value at :inherits def merge_config_inheritance main_config, all_configs new_config = {} parents = [*main_config[:inherits]].compact parents.each do |config_name| parent = all_configs[config_name] parent = merge_config_inheritance parent, all_configs new_config = new_config.merge parent end new_config.merge main_config # Two merges important for inheritance order end end end
jcasts/sunshine
cbe78390aa52c14581e092b8f37f173a5ccf7183
moved signal traps to the TrapStack class
diff --git a/Manifest.txt b/Manifest.txt index 07d901e..d933f92 100644 --- a/Manifest.txt +++ b/Manifest.txt @@ -1,81 +1,82 @@ History.txt Manifest.txt README.txt Rakefile bin/sunshine examples/deploy_tasks.rake examples/standalone_deploy.rb examples/sunshine_deploy.rb lib/commands/add.rb lib/commands/default.rb lib/commands/list.rb lib/commands/restart.rb lib/commands/rm.rb lib/commands/run.rb lib/commands/script.rb lib/commands/start.rb lib/commands/stop.rb lib/sunshine.rb lib/sunshine/app.rb lib/sunshine/binder.rb lib/sunshine/crontab.rb lib/sunshine/daemon.rb lib/sunshine/daemons/apache.rb lib/sunshine/daemons/ar_sendmail.rb lib/sunshine/daemons/delayed_job.rb lib/sunshine/daemons/mongrel_rails.rb lib/sunshine/daemons/nginx.rb lib/sunshine/daemons/rainbows.rb lib/sunshine/daemons/server.rb lib/sunshine/daemons/server_cluster.rb lib/sunshine/daemons/thin.rb lib/sunshine/daemons/unicorn.rb lib/sunshine/dependencies.rb lib/sunshine/dependency_lib.rb lib/sunshine/exceptions.rb lib/sunshine/healthcheck.rb lib/sunshine/output.rb lib/sunshine/package_managers/apt.rb lib/sunshine/package_managers/dependency.rb lib/sunshine/package_managers/gem.rb lib/sunshine/package_managers/yum.rb lib/sunshine/remote_shell.rb lib/sunshine/repo.rb lib/sunshine/repos/git_repo.rb lib/sunshine/repos/rsync_repo.rb lib/sunshine/repos/svn_repo.rb lib/sunshine/server_app.rb lib/sunshine/shell.rb +lib/sunshine/trap_stack.rb templates/apache/apache.conf.erb templates/mongrel_rails/mongrel_rails.conf.erb templates/nginx/nginx.conf.erb templates/nginx/nginx_optimize.conf templates/nginx/nginx_proxy.conf templates/rainbows/rainbows.conf.erb templates/sunshine/middleware/health.rb templates/sunshine/sunshine.rake templates/thin/thin.conf.erb templates/unicorn/unicorn.conf.erb test/fixtures/app_configs/test_app.yml test/fixtures/sunshine_test/test_upload test/helper_methods.rb test/mocks/mock_object.rb test/mocks/mock_open4.rb test/test_helper.rb test/unit/test_app.rb test/unit/test_binder.rb test/unit/test_crontab.rb test/unit/test_daemon.rb test/unit/test_git_repo.rb test/unit/test_healthcheck.rb test/unit/test_nginx.rb test/unit/test_rainbows.rb test/unit/test_remote_shell.rb test/unit/test_repo.rb test/unit/test_server.rb test/unit/test_server_app.rb test/unit/test_server_cluster.rb test/unit/test_shell.rb test/unit/test_sunshine.rb test/unit/test_svn_repo.rb test/unit/test_unicorn.rb diff --git a/lib/sunshine.rb b/lib/sunshine.rb index ceeb410..26c3666 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,426 +1,395 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'yaml' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' require 'irb' IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. VERSION = '1.2.1' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { 'auto' => false, 'auto_dependencies' => true, 'deploy_env' => ( ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] || :development ), 'level' => 'info', 'max_deploy_versions' => 5, 'remote_checkouts' => false, 'timeout' => 300, 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end ## # Should sunshine ever ask for user input? True by default; overridden with # the -a option. def self.interactive? !@config['auto'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end - ## - # Adds an INT signal trap with its description on the stack. - # Returns a trap_item Array. - - def self.add_trap desc, &block - trap_item = [desc, block] - (@trap_stack ||= []).unshift trap_item - trap_item - end - - add_trap "Disconnecting all remote shells." do - RemoteShell.disconnect_all - end - - - ## - # Call a trap item and display it's message. - - def self.call_trap trap_item - return unless trap_item - - msg, block = trap_item - - logger.info :INT, msg do - block.call - end - end - - - ## - # Remove a trap_item from the stack. - - def self.delete_trap trap_item - @trap_stack.delete trap_item - end - ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config unless File.file? USER_CONFIG_FILE File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" msg << DEFAULT_CONFIG.to_yaml self.exit 1, msg end load_config_file USER_CONFIG_FILE end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset - trap "INT" do + + TrapStack.trap_signal :INT do |msg| $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" + logger.info :INT, msg + end - call_trap @trap_stack.shift - exit 1 + TrapStack.add_trap "Disconnecting all remote shells." do + RemoteShell.disconnect_all end + require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' + require 'sunshine/trap_stack' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' require 'sunshine/healthcheck' require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies' diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index f3227c2..8957496 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -1,843 +1,844 @@ module Sunshine ## # App objects are the core of Sunshine deployment. The Sunshine paradygm # is to construct an app object, and run custom deploy code by passing # a block to its deploy method: # # someserver = Sunshine::RemoteShell.new "[email protected]", # :roles => [:web, :app] # # options = { # :name => 'myapp', # :repo => {:type => :svn, :url => 'svn://blah...'}, # :root_path => '/usr/local/myapp', # :remote_shells => '[email protected]' # } # # app = Sunshine::App.new(options) # # app.deploy do |app| # # app_server = Sunshine::Rainbows.new app, :port => 3000 # web_server = Sunshine::Nginx.new app, :point_to => app_server # # app_server.setup # web_server.setup # end # # Multiple apps can be defined, and deployed from a single deploy script. # The constructor also supports passing a yaml file path: # # Sunshine::App.new("path/to/config.yml") # # Deployment can be expressed more concisely by calling App::deploy: # # App.deploy("path/to/config.yml") do |app| # Sunshine::Rainbows.new(app).setup # end # # # An App holds information about where to deploy an application to and # how to deploy it, as well as many convenience methods to setup and # manipulate the deployment process. Most of these methods support passing # remote shell find options: # # app.rake 'db:migrate', :role => :db # app.deploy :host => 'server1.com' # # See App#find for more information. # # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml # # Yaml files must define settings on a per-environment basis. The default # environment will be used if the deploy_env is not found in the config. # Let's consider the following config: # # #config.yml: # --- # :default: # :repo: # :type: :svn # :url: http://subversion/repo/tags/release-001 # :remote_shells: dev.myserver.com # # :qa: # :remote_shells: # - qa1.myserver.com # - qa2.myserver.com # # :qa_special: # :inherits: :qa # :root_path: /path/to/application # # By default, environment definitions inherit the :default environment. In # this instance, :qa_special also inherits from :qa. # With the given config, I could setup the App instance as so: # # App.new "config.yml", :deploy_env => :development # # Note: by default, App will get the deploy_env value # # from Sunshine.deploy_env # # The above will simply load the default config. The following, however, # will load the :qa_special config which inherits from # both :qa and :default: # # App.new "config.yml", :deploy_env => :qa_special # # # Another way of instantiating an App is to pass it a hash. Unlike the yaml # config file, the hash is not on a per-environment basis and isexpected # to already have the correct values for the given environment. # The following is equivalent to loading the above :default environment: # # App.new :remote_shells => "dev.myserver.com", # :repo => { # :type => :svn, # :url => "http://subversion/repo/tags/release-001" # } # # In theory, the minimum amount of information required to instantiate # an app is the repo and remote_shells. If the repo option is omitted, # the App will attempt to detect if the pwd is a checkout out repo and # use that information. If you would like to deploy an application that # is not under source countrol, you may do so by using Sunshine::RsyncRepo, # or passing :rsync in your hash as your repo type. # # # Options supported by App.new are the following: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. class App ## # Initialize and deploy an application. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] @has_session = false end ## # Call a command on specified server apps. # Supports any App#find and Shell#call options. def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Connect server apps. Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected. Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected. Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect server apps. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil raise CriticalDeployError, "No servers defined for #{@name}" if @server_apps.empty? success = false stopped = false symlinked = false prev_connection = connected? - deploy_trap = Sunshine.add_trap "Reverting deploy of #{@name}" do - revert! options if symlinked - start options if stopped - disconnect options unless prev_connection - end + deploy_trap = + TrapStack.add_trap "Reverting deploy of #{@name}" do + revert! options if symlinked + start options if stopped + disconnect options unless prev_connection + end Sunshine.logger.info :app, "Beginning deploy of #{@name}" with_session options do with_filter options do |app| make_app_directories checkout_codebase stopped = stop symlinked = symlink_current_dir yield(self) if block_given? run_post_user_lambdas health :enable build_control_scripts build_deploy_info_file build_crontab register_as_deployed success = start(:force => true) || raise(CriticalDeployError, "Could not start #{@name}") remove_old_deploys success &&= deployed? end end Sunshine.logger.info :app, "Ending deploy of #{@name}" rescue => e message = "#{e.class}: #{e.message}" Sunshine.logger.error :app, message do Sunshine.logger.error '>>', e.backtrace.join("\n") revert! options if symlinked start options if stopped end ensure disconnect options unless prev_connection || !any_connected? - Sunshine.delete_trap deploy_trap + TrapStack.delete_trap deploy_trap success end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end ## # Starts an IRB console with the instance's binding. def console! workspace = IRB::WorkSpace.new binding irb = IRB::Irb.new workspace irb.context.irb_name = "sunshine(#{@name})" irb.context.prompt_c = "%N:%03n:%i* " irb.context.prompt_i = "%N:%03n:%i> " irb.context.prompt_n = "%N:%03n:%i> " IRB.class_eval do @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context end #TODO: remove sigint trap when irb session is closed #trap("INT") do # irb.signal_handle #end catch(:IRB_EXIT) do irb.eval_input end end ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil copy_option = options && options.has_key?(:copy) && options[:copy] if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end rescue => e raise CriticalDeployError, e end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories rescue => e raise FatalDeployError, e end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Runs bundler on deploy servers. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] rescue => e raise CriticalDeployError, e end ## # Runs GemInstaller on deploy servers. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] rescue => e raise CriticalDeployError, e end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run a sass task on any or all deploy servers. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. def shell_env env_hash=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. def status options=nil statuses = {} diff --git a/lib/sunshine/trap_stack.rb b/lib/sunshine/trap_stack.rb new file mode 100644 index 0000000..0ffb4b8 --- /dev/null +++ b/lib/sunshine/trap_stack.rb @@ -0,0 +1,54 @@ +module Sunshine + + ## + # The TrapStack class handles setting multiple trap blocks as a stack. + # Once a trap block is triggered, it gets popped off the stack. + + class TrapStack + + ## + # Adds an INT signal trap with its description on the stack. + # Returns a trap_item Array. + + def self.add_trap desc=nil, &block + @trap_stack.unshift [desc, block] + @trap_stack.first + end + + + + ## + # Call a trap item and display it's message. + + def self.call_trap trap_item + return unless trap_item + + msg, trap_block = trap_item + + yield msg if block_given? + + trap_block.call + end + + + ## + # Remove a trap_item from the stack. + + def self.delete_trap trap_item + @trap_stack.delete trap_item + end + + + ## + # Sets the default trap. + + def self.trap_signal sig, &block + @trap_stack = [] + + trap sig do + call_trap @trap_stack.shift, &block + exit 1 + end + end + end +end
jcasts/sunshine
6322560aca9e72261af9e36b9d35cd91b236186f
started implementing app.console
diff --git a/lib/sunshine.rb b/lib/sunshine.rb index 0f76e8e..ceeb410 100644 --- a/lib/sunshine.rb +++ b/lib/sunshine.rb @@ -1,423 +1,426 @@ require 'rubygems' require 'open4' require 'rainbow' require 'highline' require 'json' require 'yaml' require 'erb' require 'logger' require 'optparse' require 'time' require 'fileutils' require 'tmpdir' +require 'irb' + +IRB.setup nil unless defined?(IRB::UnrecognizedSwitch) ## # Main module, used for configuration and running commands. module Sunshine ## # Sunshine version. VERSION = '1.2.1' ## # Path to the list of installed sunshine apps. APP_LIST_PATH = "~/.sunshine_list" ## # Commands supported by Sunshine. COMMANDS = %w{add list restart rm run script start stop} ## # File DATA from Sunshine run files. DATA = defined?(::DATA) ? ::DATA : nil ## # Default configuration. DEFAULT_CONFIG = { 'auto' => false, 'auto_dependencies' => true, 'deploy_env' => ( ENV['DEPLOY_ENV'] || ENV['env'] || ENV['RACK_ENV'] || ENV['RAILS_ENV'] || :development ), 'level' => 'info', 'max_deploy_versions' => 5, 'remote_checkouts' => false, 'timeout' => 300, 'web_directory' => '/srv/http' } ## # Path where Sunshine assumes repo information can be found if missing. PATH = Dir.getwd ## # Root directory of the Sunshine gem. ROOT = File.expand_path File.join(File.dirname(__FILE__), "..") ## # Default Sunshine config file USER_CONFIG_FILE = File.expand_path("~/.sunshine") ## # Temp directory used by various sunshine classes # for uploads, checkouts, etc... TMP_DIR = File.join Dir.tmpdir, "sunshine_#{$$}" FileUtils.mkdir_p TMP_DIR ## # Returns the Sunshine config hash. def self.config @config ||= DEFAULT_CONFIG.dup end ## # The default deploy environment to use. Set with the -e option. # See App#deploy_env for app specific deploy environments. def self.deploy_env @config['deploy_env'].to_s end ## # Automatically install dependencies as needed. Defaults to true. # Overridden in the ~/.sunshine config file or at setup time. def self.auto_dependencies? @config['auto_dependencies'] end ## # Returns the main Sunshine dependencies library. If passed a block, # evaluates the block within the dependency lib instance: # # Sunshine.dependencies do # yum 'new_dep' # gem 'commander' # end def self.dependencies(&block) @dependency_lib ||= DependencyLib.new @dependency_lib.instance_eval(&block) if block_given? @dependency_lib end ## # Should sunshine ever ask for user input? True by default; overridden with # the -a option. def self.interactive? !@config['auto'] end ## # Handles all output for sunshine. See Sunshine::Output. def self.logger @logger end ## # Maximum number of deploys (history) to keep on the remote server, # 5 by default. Overridden in the config. def self.max_deploy_versions @config['max_deploy_versions'] end ## # Check if the codebase should be checked out remotely, or checked out # locally and rsynced up. Overridden in the config. def self.remote_checkouts? @config['remote_checkouts'] end ## # Handles input/output to the shell. See Sunshine::Shell. def self.shell @shell ||= Sunshine::Shell.new end ## # How long to wait on a command to finish when no output is received. # Defaults to 300 (seconds). Overridden in the config. # Set to false to disable timeout. def self.timeout @config['timeout'] end ## # Check if trace log should be output at all. # This value can be assigned by default in ~/.sunshine # or switched off with the run command's --no-trace option. # Defaults to true. def self.trace? @config['trace'] end ## # The default directory where apps should be deployed to: # '/var/www' by default. Overridden in the config. # See also App#deploy_path. def self.web_directory @config['web_directory'] end ## # Adds an INT signal trap with its description on the stack. # Returns a trap_item Array. def self.add_trap desc, &block trap_item = [desc, block] (@trap_stack ||= []).unshift trap_item trap_item end add_trap "Disconnecting all remote shells." do RemoteShell.disconnect_all end ## # Call a trap item and display it's message. def self.call_trap trap_item return unless trap_item msg, block = trap_item logger.info :INT, msg do block.call end end ## # Remove a trap_item from the stack. def self.delete_trap trap_item @trap_stack.delete trap_item end ## # Global value of sudo to use. Returns true, nil, or a username. # This value can be assigned by default in ~/.sunshine # or with the --sudo [username] option. Defaults to nil. def self.sudo @config['sudo'] end ## # Cleanup after Sunshine has run, remove temp dirs, etc... def self.cleanup FileUtils.rm_rf TMP_DIR if Dir.glob("#{TMP_DIR}/*").empty? end ## # Loads a yaml config file to run setup with. def self.load_config_file conf setup YAML.load_file(conf) end ## # Loads the USER_CONFIG_FILE and runs setup. Creates the default # config file and exits if not present. def self.load_user_config unless File.file? USER_CONFIG_FILE File.open(USER_CONFIG_FILE, "w+"){|f| f.write DEFAULT_CONFIG.to_yaml} msg = "Missing config file was created for you: #{USER_CONFIG_FILE}\n\n" msg << DEFAULT_CONFIG.to_yaml self.exit 1, msg end load_config_file USER_CONFIG_FILE end ## # Loads an array of libraries or gems. def self.require_libs(*libs) libs.compact.each{|lib| require lib } end ## # Setup Sunshine with a custom config: # Sunshine.setup 'level' => 'debug', 'deploy_env' => :production def self.setup new_config={}, reset=false @config = DEFAULT_CONFIG.dup if reset trap "INT" do $stderr << "\n\n" logger.indent = 0 logger.fatal :INT, "Caught INT signal!" call_trap @trap_stack.shift exit 1 end require_libs(*new_config['require']) config.merge! new_config log_level = Logger.const_get config['level'].upcase rescue Logger::INFO @logger = Sunshine::Output.new :level => log_level config end ## # Run Sunshine with the passed argv and exits with appropriate exitcode. # run %w{run my_script.rb -l debug} # run %w{list -d} # run %w{--rakefile} def self.run argv=ARGV command = find_command argv.first argv.shift if command command ||= DefaultCommand setup command.parse_args(argv) result = command.exec argv, config self.exit(*result) end ## # Find the sunshine command to run based on the passed name. # Handles partial command names if they can be uniquely mapped to a command. # find_command "ru" #=> Sunshine::RunCommand # find_command "l" #=> Sunshine::ListCommand # find_command "zzz" #=> nil def self.find_command name commands = COMMANDS.select{|c| c =~ /^#{name}/} return unless commands.length == 1 && commands.first Sunshine.const_get "#{commands.first.capitalize}Command" end ## # Exits sunshine process and returns the appropriate exit code # exit 0, "ok" # exit false, "ok" # # both output: stdout >> ok - exitcode 0 # exit 1, "oh noes" # exit true, "oh noes" # # both output: stderr >> oh noes - exitcode 1 def self.exit status, msg=nil self.cleanup status = case status when true 0 when false 1 when Integer status else status.to_i end output = status == 0 ? $stdout : $stderr output << "#{msg}\n" if !msg.nil? Kernel.exit status end require 'sunshine/exceptions' require 'sunshine/shell' require 'sunshine/remote_shell' require 'sunshine/output' require 'sunshine/binder' require 'sunshine/server_app' require 'sunshine/app' require 'sunshine/dependency_lib' require 'sunshine/package_managers/dependency' require 'sunshine/package_managers/apt' require 'sunshine/package_managers/yum' require 'sunshine/package_managers/gem' require 'sunshine/repo' require 'sunshine/repos/svn_repo' require 'sunshine/repos/git_repo' require 'sunshine/repos/rsync_repo' require 'sunshine/daemon' require 'sunshine/daemons/server_cluster' require 'sunshine/daemons/server' require 'sunshine/daemons/apache' require 'sunshine/daemons/nginx' require 'sunshine/daemons/thin' require 'sunshine/daemons/unicorn' require 'sunshine/daemons/rainbows' require 'sunshine/daemons/mongrel_rails' require 'sunshine/daemons/ar_sendmail' require 'sunshine/daemons/delayed_job' require 'sunshine/crontab' require 'sunshine/healthcheck' require 'commands/default' require 'commands/list' require 'commands/add' require 'commands/run' require 'commands/restart' require 'commands/rm' require 'commands/script' require 'commands/start' require 'commands/stop' end Sunshine.load_user_config require 'sunshine/dependencies' diff --git a/lib/sunshine/app.rb b/lib/sunshine/app.rb index 2aaf2b7..f3227c2 100644 --- a/lib/sunshine/app.rb +++ b/lib/sunshine/app.rb @@ -1,967 +1,995 @@ module Sunshine ## # App objects are the core of Sunshine deployment. The Sunshine paradygm # is to construct an app object, and run custom deploy code by passing # a block to its deploy method: # # someserver = Sunshine::RemoteShell.new "[email protected]", # :roles => [:web, :app] # # options = { # :name => 'myapp', # :repo => {:type => :svn, :url => 'svn://blah...'}, # :root_path => '/usr/local/myapp', # :remote_shells => '[email protected]' # } # # app = Sunshine::App.new(options) # # app.deploy do |app| # # app_server = Sunshine::Rainbows.new app, :port => 3000 # web_server = Sunshine::Nginx.new app, :point_to => app_server # # app_server.setup # web_server.setup # end # # Multiple apps can be defined, and deployed from a single deploy script. # The constructor also supports passing a yaml file path: # # Sunshine::App.new("path/to/config.yml") # # Deployment can be expressed more concisely by calling App::deploy: # # App.deploy("path/to/config.yml") do |app| # Sunshine::Rainbows.new(app).setup # end # # # An App holds information about where to deploy an application to and # how to deploy it, as well as many convenience methods to setup and # manipulate the deployment process. Most of these methods support passing # remote shell find options: # # app.rake 'db:migrate', :role => :db # app.deploy :host => 'server1.com' # # See App#find for more information. # # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml # # Yaml files must define settings on a per-environment basis. The default # environment will be used if the deploy_env is not found in the config. # Let's consider the following config: # # #config.yml: # --- # :default: # :repo: # :type: :svn # :url: http://subversion/repo/tags/release-001 # :remote_shells: dev.myserver.com # # :qa: # :remote_shells: # - qa1.myserver.com # - qa2.myserver.com # # :qa_special: # :inherits: :qa # :root_path: /path/to/application # # By default, environment definitions inherit the :default environment. In # this instance, :qa_special also inherits from :qa. # With the given config, I could setup the App instance as so: # # App.new "config.yml", :deploy_env => :development # # Note: by default, App will get the deploy_env value # # from Sunshine.deploy_env # # The above will simply load the default config. The following, however, # will load the :qa_special config which inherits from # both :qa and :default: # # App.new "config.yml", :deploy_env => :qa_special # # # Another way of instantiating an App is to pass it a hash. Unlike the yaml # config file, the hash is not on a per-environment basis and isexpected # to already have the correct values for the given environment. # The following is equivalent to loading the above :default environment: # # App.new :remote_shells => "dev.myserver.com", # :repo => { # :type => :svn, # :url => "http://subversion/repo/tags/release-001" # } # # In theory, the minimum amount of information required to instantiate # an app is the repo and remote_shells. If the repo option is omitted, # the App will attempt to detect if the pwd is a checkout out repo and # use that information. If you would like to deploy an application that # is not under source countrol, you may do so by using Sunshine::RsyncRepo, # or passing :rsync in your hash as your repo type. # # # Options supported by App.new are the following: # # :deploy_env:: String - specify the env to deploy with; defaults to # Sunshine#deploy_env. # # :deploy_name:: String - if you want to specify a name for your deploy and # checkout directory (affects the checkout_path); defaults to Time.now.to_i. # # :remote_shells:: String|Array|Sunshine::Shell - the shell(s) to use for # deployment. Accepts any single instance or array of a Sunshine::Shell # type instance or Sunshine::Shell instantiator-friendly arguments. # # :repo:: Hash|Sunshine::Repo - the scm and repo to use for deployment. # Accepts any hash that can be passed to Sunshine::Repo::new_of_type # or any Sunshine::Repo object. # # :root_path:: String - the absolute path the deployed application # should live in; defaults to "#{Sunshine.web_directory}/#{@name}". # # :shell_env:: Hash - environment variables to add to deploy shells. # # :sudo:: true|false|nil|String - which sudo value should be assigned to # deploy shells; defaults to Sunshine#sudo. For more information on using # sudo, see the Using Permissions section in README.txt. class App ## # Initialize and deploy an application. # Takes any arguments supported by the constructor. def self.deploy(*args, &block) app = new(*args) app.deploy(&block) app end attr_reader :name, :repo, :server_apps, :sudo, :deploy_name, :deploy_env attr_reader :root_path, :checkout_path, :current_path, :deploys_path attr_reader :shared_path, :log_path, :scripts_path attr_accessor :remote_checkout ## # App instantiation can be done in several ways: # App.new instantiation_hash # App.new "path/to/config.yml", optional_extra_hash # App.new #=> will attempt to load ruby's file DATA as yaml def initialize config_file=Sunshine::DATA, options={} options, config_file = config_file, Sunshine::DATA if Hash === config_file @deploy_env = options[:deploy_env] || Sunshine.deploy_env binder = Binder.new self binder.import_hash options binder.forward :deploy_env options = config_from_file(config_file, binder.get_binding).merge options @repo = repo_from_config options[:repo] @name = options[:name] || @repo.name @deploy_name = options[:deploy_name] || Time.now.to_i.to_s @deploy_env = options[:deploy_env] if options[:deploy_env] set_deploy_paths options[:root_path] @server_apps = server_apps_from_config options[:remote_shells] @remote_checkout = options[:remote_checkout] || Sunshine.remote_checkouts? self.sudo = options[:sudo] || Sunshine.sudo @shell_env = { "RACK_ENV" => @deploy_env.to_s, "RAILS_ENV" => @deploy_env.to_s } shell_env options[:shell_env] @post_user_lambdas = [] @has_session = false end ## # Call a command on specified server apps. # Supports any App#find and Shell#call options. def call cmd, options=nil, &block with_server_apps options, :msg => "Running #{cmd}" do |server_app| server_app.shell.call cmd, options, &block end end ## # Connect server apps. Supports any App#find options. def connect options=nil Sunshine.logger.info :app, "Connecting..." do threaded_each options do |server_app| server_app.shell.connect end end end ## # Check if all server apps are connected. Supports any App#find options. def connected? options=nil each options do |server_app| return false unless server_app.shell.connected? end true end ## # Check if any server apps are connected. Supports any App#find options. def any_connected? options=nil each options do |server_app| return true if server_app.shell.connected? end false end ## # Disconnect server apps. Supports any App#find options. def disconnect options=nil Sunshine.logger.info :app, "Disconnecting..." do threaded_each options do |server_app| server_app.shell.disconnect end end end ## # Deploy the application to deploy servers and # call user's post-deploy code. Supports any App#find options. # # Note: The deploy method will stop the former deploy just before # symlink and the passed block is run. # # Note: Once deployment is complete, the deploy method will attempt to # run App#start. def deploy options=nil raise CriticalDeployError, "No servers defined for #{@name}" if @server_apps.empty? success = false stopped = false symlinked = false prev_connection = connected? deploy_trap = Sunshine.add_trap "Reverting deploy of #{@name}" do revert! options if symlinked start options if stopped disconnect options unless prev_connection end Sunshine.logger.info :app, "Beginning deploy of #{@name}" with_session options do with_filter options do |app| make_app_directories checkout_codebase stopped = stop symlinked = symlink_current_dir yield(self) if block_given? run_post_user_lambdas health :enable build_control_scripts build_deploy_info_file build_crontab register_as_deployed success = start(:force => true) || raise(CriticalDeployError, "Could not start #{@name}") remove_old_deploys success &&= deployed? end end Sunshine.logger.info :app, "Ending deploy of #{@name}" rescue => e message = "#{e.class}: #{e.message}" Sunshine.logger.error :app, message do Sunshine.logger.error '>>', e.backtrace.join("\n") revert! options if symlinked start options if stopped end ensure disconnect options unless prev_connection || !any_connected? Sunshine.delete_trap deploy_trap success end ## # Symlink current directory to previous checkout and remove # the current deploy directory. Supports any App#find options. def revert!(options=nil) with_server_apps options, :msg => "Reverting to previous deploy.", :send => :revert! end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = @shell_env["PATH"] || "$PATH" paths << path shell_env "PATH" => paths.join(":") end ## # Add a command to the crontab to be generated remotely: # add_to_crontab "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will append jobs to already existing cron jobs for this # application and job name, including previous deploys. def add_to_crontab name, cronjob, options=nil each options do |server_app| server_app.crontab[name] << cronjob end end ## # Add a command to the crontab to be generated remotely: # cronjob "reboot", "@reboot /path/to/app/start", :role => :web # # Note: This method will override already existing cron jobs for this # application and job name, including previous deploys. def cronjob name, cronjob, options=nil each options do |server_app| server_app.crontab[name] = cronjob end end ## # Add a command to a control script to be generated remotely: # add_to_script :start, "do this on start" # add_to_script :start, "start_mail", :role => :mail def add_to_script name, script, options=nil each options do |server_app| server_app.scripts[name] << script end end ## # Define lambdas to run right after the user's yield. # app.after_user_script do |app| # ... # end def after_user_script &block @post_user_lambdas << block end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts options=nil with_server_apps options, :msg => "Building control scripts", :send => :build_control_scripts end ## # Writes the crontab on all or selected server apps. # To add or remove from the crontab, see App#add_to_crontab and # App#remove_cronjob. def build_crontab options=nil with_server_apps options, :msg => "Building the crontab" do |server_app| server_app.crontab.write! end end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file options=nil with_server_apps options, :msg => "Creating info file", :send => :build_deploy_info_file end ## # Parse an erb file and return the newly created string. # Default binding is the app's binding. def build_erb erb_file, custom_binding=nil str = File === erb_file ? erb_file.read : File.read(erb_file) ERB.new(str, nil, '-').result(custom_binding || binding) end + ## + # Starts an IRB console with the instance's binding. + + def console! + workspace = IRB::WorkSpace.new binding + irb = IRB::Irb.new workspace + + irb.context.irb_name = "sunshine(#{@name})" + irb.context.prompt_c = "%N:%03n:%i* " + irb.context.prompt_i = "%N:%03n:%i> " + irb.context.prompt_n = "%N:%03n:%i> " + + IRB.class_eval do + @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] + @CONF[:MAIN_CONTEXT] = irb.context + end + + #TODO: remove sigint trap when irb session is closed + #trap("INT") do + # irb.signal_handle + #end + + catch(:IRB_EXIT) do + irb.eval_input + end + end + + ## # Checks out the app's codebase to one or all deploy servers. # Supports all App#find options, plus: # :copy:: Bool - Checkout locally and rsync; defaults to false. def checkout_codebase options=nil copy_option = options && options.has_key?(:copy) && options[:copy] if @remote_checkout && !copy_option with_server_apps options, :msg => "Checking out codebase (remotely)", :send => [:checkout_repo, @repo] else Sunshine.logger.info :app, "Checking out codebase (locally)" do tmp_path = File.join Sunshine::TMP_DIR, "#{@name}_checkout" scm_info = @repo.checkout_to tmp_path with_server_apps options, :send => [:upload_codebase, tmp_path, scm_info] end end rescue => e raise CriticalDeployError, e end ## # Get a hash of deploy information for each server app. # Post-deploy only. def deploy_details options=nil details = {} with_server_apps options, :msg => "Getting deploy info..." do |server_app| details[server_app.shell.host] = server_app.deploy_details end details end ## # Check if app has been deployed successfully. def deployed? options=nil with_server_apps options, :msg => "Checking deploy", :no_threads => true do |server_app| return false unless server_app.deployed? end true end ## # Iterate over each server app. def each(options=nil, &block) server_apps = find(options) server_apps.each(&block) end ## # Find server apps matching the passed requirements. # Returns an array of server apps. # find :user => 'db' # find :host => 'someserver.com' # find :role => :web # # The find method also supports passing arrays and will match # any server app that matches any one condition: # find :user => ['root', 'john'] # # Returns all server apps who's user is either 'root' or 'john'. def find query=nil return @server_apps if query.nil? || query == :all @server_apps.select do |sa| next unless [*query[:user]].include? sa.shell.user if query[:user] next unless [*query[:host]].include? sa.shell.host if query[:host] next unless sa.has_roles?(query[:role], true) if query[:role] true end end ## # Decrypt a file using gpg. Allows all DeployServerDispatcher#find # options, plus: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} options[:passphrase] ||= Sunshine.shell.ask("Enter gpg passphrase:") do |q| q.echo = false end with_server_apps options, :msg => "Gpg decrypt: #{gpg_file}", :send => [:gpg_decrypt, gpg_file, options] end ## # Gets or sets the healthcheck state. Returns a hash of host/state # pairs. State values are :enabled, :disabled, and :down. The method # argument can be omitted or take a value of :enable, :disable, or :remove: # app.health # #=> Returns the health status for all server_apps # # app.health :role => :web # #=> Returns the status of all server_apps of role :web # # app.health :enable # #=> Enables all health checking and returns the status # # app.health :disable, :role => :web # #=> Disables health checking for :web server_apps and returns the status def health method=nil, options=nil valid_methods = [:enable, :disable, :remove] options = method if options.nil? && Hash === method valid_method = valid_methods.include? method message = "#{method.to_s.capitalize[0..-2]}ing" if valid_method message ||= "Getting status of" message = "#{message} healthcheck" statuses = {} with_server_apps options, :msg => message do |server_app| server_app.health.send method if valid_method statuses[server_app.shell.host] = server_app.health.status end statuses end ## # Install dependencies defined as a Sunshine dependency object: # rake = Sunshine.dependencies.gem 'rake', :version => '~>0.8' # apache = Sunshine.dependencies.yum 'apache' # app.install_deps rake, apache # # Deploy servers can also be specified as a dispatcher, array, or single # deploy server, by passing standard 'find' options: # postgres = Sunshine.dependencies.yum 'postgresql' # pgserver = Sunshine.dependencies.yum 'postgresql-server' # app.install_deps postgres, pgserver, :role => 'db' # # If a dependency was already defined in the Sunshine dependency tree, # the dependency name may be passed instead of the object: # app.install_deps 'nginx', 'ruby' def install_deps(*deps) options = Hash === deps[-1] ? deps.delete_at(-1) : {} with_server_apps options, :msg => "Installing dependencies: #{deps.map{|d| d.to_s}.join(" ")}", :send => [:install_deps, *deps] end ## # Creates the required application directories. def make_app_directories options=nil with_server_apps options, :msg => "Creating #{@name} directories", :send => :make_app_directories rescue => e raise FatalDeployError, e end ## # Assign the prefered package manager to all server_apps: # app.prefer_pkg_manager Settler::Yum # # Package managers are typically detected automatically by each # individual server_apps. def prefer_pkg_manager pkg_manager, options=nil with_server_apps options, :send => [:pkg_manager=, pkg_manager] end ## # Run a rake task on any or all deploy servers. def rake command, options=nil with_server_apps options, :msg => "Running Rake task '#{command}'", :send => [:rake, command] end ## # Adds the app to the deploy servers deployed-apps list. def register_as_deployed options=nil with_server_apps options, :msg => "Registering app with deploy servers", :send => :register_as_deployed end ## # Remove a cron job from the remote crontabs: # remove_cronjob "reboot", :role => :web # remove_cronjob :all # #=> deletes all cronjobs related to this app def remove_cronjob name, options=nil with_server_apps options, :msg => "Removing cronjob #{name.inspect}" do |server_app| if name == :all server_app.crontab.clear else server_app.crontab.delete(name) end end end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys options=nil with_server_apps options, :msg => "Removing old deploys (max = #{Sunshine.max_deploy_versions})", :send => :remove_old_deploys end ## # Run the restart script of a deployed app on the specified # deploy servers. # Post-deploy only. def restart options=nil with_server_apps options, :msg => "Running restart script", :send => :restart end ## # Runs bundler on deploy servers. def run_bundler options=nil with_server_apps options, :msg => "Running Bundler", :send => [:run_bundler, options] rescue => e raise CriticalDeployError, e end ## # Runs GemInstaller on deploy servers. def run_geminstaller options=nil with_server_apps options, :msg => "Running GemInstaller", :send => [:run_geminstaller, options] rescue => e raise CriticalDeployError, e end ## # Run lambdas that were saved for after the user's script. # See #after_user_script. def run_post_user_lambdas Sunshine.logger.info :app, "Running post deploy lambdas" do with_session{ @post_user_lambdas.each{|l| l.call self} } end end ## # Run the given script of a deployed app on the specified # deploy servers. # Post-deploy only. def run_script name, options=nil with_server_apps options, :msg => "Running #{name} script", :send => [:run_script, name, options] end ## # Run a sass task on any or all deploy servers. def sass *sass_names options = sass_names.delete_at(-1) if Hash === sass_names.last with_server_apps options, :msg => "Running Sass for #{sass_names.join(' ')}", :send => [:sass, *sass_names] end ## # Set and return the remote shell env variables. # Also assigns shell environment to the app's deploy servers. def shell_env env_hash=nil env_hash ||= {} @shell_env.merge!(env_hash) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Shell env: #{@shell_env.inspect}" do |server_app| server_app.shell_env.merge!(@shell_env) end @shell_env.dup end ## # Run the start script of a deployed app on the specified # deploy servers. # Post-deploy only. def start options=nil with_server_apps options, :msg => "Running start script", :send => [:start, options] end ## # Get a hash of which deploy server apps are :running or :down. # Post-deploy only. def status options=nil statuses = {} with_server_apps options, :msg => "Querying app status..." do |server_app| statuses[server_app.shell.host] = server_app.status end statuses end ## # Run the stop script of a deployed app on the specified # deploy servers. # Post-deploy only. def stop options=nil with_server_apps options, :msg => "Running stop script", :send => :stop end ## # Use sudo on deploy servers. Set to true/false, or # a username to use 'sudo -u'. def sudo=(value) with_server_apps :all, :no_threads => true, :no_session => true, :msg => "Using sudo = #{value.inspect}" do |server_app| server_app.shell.sudo = value end @sudo = value end ## # Creates a symlink to the app's checkout path. def symlink_current_dir options=nil with_server_apps options, :msg => "Symlinking #{@checkout_path} -> #{@current_path}", :send => :symlink_current_dir rescue => e raise CriticalDeployError, e end ## # Iterate over all deploy servers but create a thread for each # deploy server. Means you can't return from the passed block! def threaded_each(options=nil, &block) mutex = Mutex.new threads = [] error = nil return_val = each(options) do |server_app| thread = Thread.new do server_app.shell.with_mutex mutex do begin yield server_app rescue => e error = e end end end threads << thread end threads.each{|t| t.join } raise error if error return_val end ## # Upload common rake tasks from the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', :role => :web # #=> upload app and common rake files # # Allows standard DeployServerDispatcher#find options, plus: # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files.last ? files.last.dup : {} options.delete(:remote_path) options = :all if options.empty? with_server_apps options, :msg => "Uploading tasks: #{files.join(" ")}", :send => [:upload_tasks, *files] end ## # Execute a block with a specified server app filter: # app.with_filter :role => :cdn do |app| # app.sass 'file1', 'file2', 'file3' # app.rake 'asset:packager:build_all' # end def with_filter filter_hash old_server_apps, @server_apps = @server_apps, find(filter_hash) yield self ensure @server_apps = old_server_apps end ## # Calls a method for server_apps found with the passed options, # and with an optional log message. Will attempt to run the methods in # a session to avoid multiple ssh login prompts. Supports all App#find # options, plus: # :no_threads:: bool - disable threaded execution # :no_session:: bool - disable auto session creation # :msg:: "some message" - log message # # app.with_server_apps :all, :msg => "doing something" do |server_app| # # do something here # end # # app.with_server_apps :role => :db, :user => "bob" do |server_app| # # do something here # end # # Note: App#with_server_apps calls App#with_session. If you do not need # or want a server connection you can pass :no_session. def with_server_apps search_options, options={} options = search_options.merge options if Hash === search_options message = options[:msg] method = options[:no_threads] ? :each : :threaded_each auto_session = !options[:no_session] block = lambda do send(method, search_options) do |server_app|
jcasts/sunshine
886c8591ff7d40c91a3e3b3ce8c54c26561ed44a
fix for Repo.valid?
diff --git a/lib/sunshine/repo.rb b/lib/sunshine/repo.rb index 755dc62..6325efe 100644 --- a/lib/sunshine/repo.rb +++ b/lib/sunshine/repo.rb @@ -1,149 +1,149 @@ module Sunshine class RepoError < Exception; end ## # An abstract class to wrap simple basic scm features. The primary function # of repo objects is to get information about the scm branch that is being # deployed and to check it out on remote deploy servers: # svn = SvnRepo.new "svn://path/to/repo", :flags => "--ignore-externals" # # The :flags option can be a String or an Array and supports any scm # checkout (or clone for git) options. class Repo ## # Adds subclasses to a repo_types hash for easy def self.inherited subclass @@repo_types ||= {} # Turn Sunshine::ScmNameRepo into :scm_name class_key = subclass.to_s.split("::").last class_key = $1 if class_key =~ /(\w+)Repo$/ class_key.gsub!(/([a-z0-9])([A-Z])/, '\1_\2') class_key = class_key.downcase @@repo_types[class_key] = subclass end ## # Creates a new repo subclass object: # Repo.new_of_type :svn, "https://path/to/repo/tags/releasetag" # Repo.new_of_type :git, "[email protected]:repo/path" def self.new_of_type repo_type, url, options={} repo_class = @@repo_types[repo_type.to_s] raise RepoError, "Invalid type #{repo_type.inspect}" unless repo_class repo_class.new(url, options) end ## # Looks for .git and .svn directories and determines if the passed path # is a recognized repo. Does not check for RsyncRepo since it's a # special case. Returns the appropriate repo object: # Repo.detect "path/to/svn/repo/dir" # #=> <SvnRepo @url="svn://url/of/checked/out/repo"> # Repo.detect "path/to/git/repo/dir" # #=> <GitRepo, @url="git://url/of/git/repo", @branch="master"> # Repo.detect "invalid/repo/path" # #=> nil def self.detect path=".", shell=nil @@repo_types.values.each do |repo| if repo.valid? path info = repo.get_info path, shell return repo.new(info[:url], info) end end nil end ## # Gets repo information for the specified dir - Implemented by subclass def self.get_info path=".", shell=nil raise RepoError, "The 'get_info' method must be implemented by child classes" end ## # Checks if current working directory is a valid repo. # Defaults to false. Subclasses must override this method to enable # auto detecting of a given scm implementation. - def self.valid? + def self.valid? *args false end attr_reader :url, :scm def initialize url, options={} @scm = self.class.name.split("::").last.sub('Repo', '').downcase @url = url.to_s @flags = [*options[:flags]].compact end ## # Checkout code to a shell and return an info log hash: # repo.chekout_to "some/path", remote_shell # #=> {:revision => 123, :committer => 'someone', :date => time_obj ...} def checkout_to path, shell=nil shell ||= Sunshine.shell shell.call "test -d #{path} && rm -rf #{path} || echo false" shell.call "mkdir -p #{path}" do_checkout path, shell get_repo_info path, shell end ## # Checkout the repo - implemented by subclass def do_checkout path, shell raise RepoError, "The 'do_checkout' method must be implemented by child classes" end ## # Get the project name of the specified repo - implemented by subclass def name raise RepoError, "The 'name' method must be implemented by child classes" end ## # Returns the set scm flags as a string def scm_flags @flags.join(" ") end ## # Returns the repo information as a hash. def get_repo_info path=".", shell=nil defaults = {:type => @scm, :url => @url, :path => path} defaults.merge self.class.get_info(path, shell) end end end
jcasts/sunshine
19e1ae15404fcacf7638a88c134bf294d8377e5e
added sunshine version to info file
diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index 14c1fbf..c5e94e1 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -1,684 +1,685 @@ module Sunshine ## # Handles App deployment functionality for a single deploy server. # # Server apps can be assigned any number of roles for classification. # :roles:: sym|array - roles assigned (web, db, app, etc...) # By default server apps get the special :all role which will # always return true when calling: # server_app.has_roles? :some_role # # ServerApp objects can be instantiated several ways: # ServerApp.new app_instance, shell_instance, options_hash # # When passing an App instance, the new ServerApp will keep an active link # to the app's properties. Name, deploy, and path attributes will be # actively linked. # # Rely on ServerApp to create a RemoteShell instance to use: # ServerApp.new app_instance, "host.com", options_hash # # Instantiate with app name and rely on Sunshine defaults for app paths: # ServerApp.new "app_name", shell_instance, options_hash # # Explicitely assign the app's root path: # ServerApp.new "app_name", ..., :root_path => "/path/to/app_root" # # Assigning a specific deploy name to use can be done with the # :deploy_name option: # ServerApp.new "app_name", ..., :deploy_name => "deploy" class ServerApp ## # Define an attribue that will get a value from app, or locally if # @app isn't set. def self.app_attr *attribs attribs.each do |attrib| class_eval <<-STR, __FILE__, __LINE__ + 1 def #{attrib} @app ? @app.send(:#{attrib}) : @#{attrib} end STR end end ## # Creates dependency instance methods such as gem_install, yum_install, etc # on both App and ServerApp classes. def self.register_dependency_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = Hash === names.last ? names.delete_at(-1) : Hash.new names.each do |name| dep = #{dep_class}.new(name, options) dep.install! :call => @shell end end STR App.class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = names.last if Hash === names.last with_server_apps options, :msg => "Installing #{dep_class.short_name} packages", :send => [:#{dep_class.short_name}_install, *names] end STR end ## # Creates a ServerApp instance from a deploy info file. def self.from_info_file path, shell=nil shell ||= Sunshine.shell opts = YAML.load shell.call("cat #{path}") opts[:root_path] = opts.delete :path sa_shell = shell.dup sa_shell.env = opts[:env] || Hash.new sa_shell.connect if shell.connected? new opts[:name], sa_shell, opts end app_attr :name, :deploy_name app_attr :root_path, :checkout_path, :current_path app_attr :deploys_path, :log_path, :shared_path, :scripts_path attr_accessor :app, :roles, :scripts, :info, :shell, :crontab, :health attr_writer :pkg_manager ## # Create a server app instance. Supports the following # argument configurations: # # ServerApp.new app_inst, "myserver.com", :roles => :web # ServerApp.new "app_name", shell_inst, options_hash def initialize app, host, options={} @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell @health = Healthcheck.new shared_path, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No daemons for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :name => self.name, :env => shell_env, :roles => @roles, - :path => self.root_path + :path => self.root_path, + :sunshine_version => Sunshine::VERSION }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec self.root_path, 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart @shell.call "#{self.root_path}/restart" rescue false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the script_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block rescue false end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script :status, :sudo => false end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} RsyncRepo.new(code_dir).checkout_to self.checkout_path, @shell @info[:scm] = scm_info end ## # Upload common rake tasks from a local path or the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', ... # #=> upload app and common rake files # # File paths may also be used instead of the file's base name but # directory structures will not be followed: # app.upload_tasks 'lib/common/app.rake', 'lib/do_thing.rake' # # Allows options: # :local_path:: str - the path to get rake tasks from # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files[-1] ? files.delete_at(-1) : {} remote_path = options[:remote_path] || "#{self.checkout_path}/lib/tasks" local_path = options[:local_path] || "#{Sunshine::ROOT}/templates/tasks" @shell.call "mkdir -p #{remote_path}" files.map! do |file| if File.basename(file) == file File.join(local_path, "#{file}.rake") else file end end files = Dir.glob("#{Sunshine::ROOT}/templates/tasks/*") if files.empty? files.each do |file| remote_file = File.join remote_path, File.basename(file) @shell.upload file, remote_file end end ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end end end diff --git a/test/unit/test_server_app.rb b/test/unit/test_server_app.rb index 415c4e6..30a041f 100644 --- a/test/unit/test_server_app.rb +++ b/test/unit/test_server_app.rb @@ -1,488 +1,489 @@ require 'test_helper' class TestServerApp < Test::Unit::TestCase def setup mock_svn_response @app = mock_app @app.repo.extend MockObject @sa = Sunshine::ServerApp.new @app, mock_remote_shell @sa.extend MockObject use_remote_shell @sa.shell end def test_from_info_file info_data = @sa.get_deploy_info.to_yaml @sa.shell.mock :call, :args => "cat info/path", :return => info_data server_app = Sunshine::ServerApp.from_info_file "info/path", @sa.shell assert_equal @sa.root_path, server_app.root_path assert_equal @sa.checkout_path, server_app.checkout_path assert_equal @sa.current_path, server_app.current_path assert_equal @sa.deploys_path, server_app.deploys_path assert_equal @sa.log_path, server_app.log_path assert_equal @sa.shared_path, server_app.shared_path assert_equal @sa.scripts_path, server_app.scripts_path assert_equal @sa.roles, server_app.roles assert_equal @sa.shell.env, server_app.shell_env assert_equal @sa.name, server_app.name assert_equal @sa.deploy_name, server_app.deploy_name end def test_init default_info = {:ports => {}} assert_equal default_info, @sa.info assert_equal @app, @sa.app assert_equal Hash.new, @sa.scripts assert_equal [:all], @sa.roles end def test_init_roles sa = Sunshine::ServerApp.new @app, "host", :roles => "role1 role2" assert_equal [:role1, :role2], sa.roles sa = Sunshine::ServerApp.new @app, "host", :roles => %w{role3 role4} assert_equal [:role3, :role4], sa.roles end def test_add_shell_paths @sa.add_shell_paths "test/path1", "test/path2" assert_equal "test/path1:test/path2:$PATH", @sa.shell_env['PATH'] @sa.add_shell_paths "test/path3", "test/path4" assert_equal "test/path3:test/path4:test/path1:test/path2:$PATH", @sa.shell_env['PATH'] end def test_app_attr sa_root_path = "local/server_app/path" sa_deploy_name = "local_deploy_name" @sa = Sunshine::ServerApp.new "test", "host", :root_path => sa_root_path, :deploy_name => sa_deploy_name assert_equal sa_root_path, @sa.root_path assert_equal sa_deploy_name, @sa.deploy_name assert_equal "test", @sa.name @sa.app = @app assert_not_equal sa_root_path, @sa.root_path assert_not_equal sa_deploy_name, @sa.deploy_name assert_not_equal "test", @sa.name assert_equal @app.root_path, @sa.root_path assert_equal @app.deploy_name, @sa.deploy_name assert_equal @app.name, @sa.name end def test_build_control_scripts @sa.scripts[:start] << "start" @sa.scripts[:stop] << "stop" @sa.scripts[:custom] << "custom" @sa.build_control_scripts [:start, :stop, :custom].each do |script| content = @sa.make_bash_script script, @sa.scripts[script] assert @sa.method_called?(:write_script, :args => [script, content]) end content = @sa.make_env_bash_script assert @sa.method_called?(:write_script, :args => ["env", content]) content = @sa.make_bash_script :restart, ["#{@sa.app.root_path}/stop", "#{@sa.app.root_path}/start"] assert @sa.method_called?(:write_script, :args => [:restart, content]) end def test_build_deploy_info_file @sa.shell.mock :file?, :return => false args = ["#{@app.scripts_path}/info", @sa.get_deploy_info.to_yaml] @sa.build_deploy_info_file assert @sa.shell.method_called?(:make_file, :args => args) args = ["#{@app.scripts_path}/info", "#{@app.root_path}/info"] assert @sa.shell.method_called?(:symlink, :args => args) end def test_checkout_repo @sa.checkout_repo @app.repo repo = @sa.app.repo args = [@app.checkout_path, @sa.shell] assert repo.method_called?(:checkout_to, :args => args) info = @app.repo.checkout_to @app.checkout_path, @sa.shell assert_equal info, @sa.info[:scm] end def test_deploy_details deploy_details = {:item => "thing"} other_details = {:key => "value"} @sa.shell.mock :call, :args => ["cat #{@sa.root_path}/info"], :return => other_details.to_yaml @sa.instance_variable_set "@deploy_details", deploy_details assert_equal deploy_details, @sa.deploy_details assert_equal other_details, @sa.deploy_details(true) end def test_not_deployed? @sa.mock :deploy_details, :args => [true], :return => nil assert_equal false, @sa.deployed? end def test_server_checked_deployed? @sa.mock :deploy_details, :args => [true], :return => {:deploy_name => @sa.deploy_name} assert_equal true, @sa.deployed? end def test_cached_details_deployed? @sa.instance_variable_set "@deploy_details", :deploy_name => @sa.deploy_name assert_equal true, @sa.deployed? end def test_get_deploy_info test_info = { :deployed_at => Time.now.to_s, :deployed_as => @sa.shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(@app.checkout_path), :name => @sa.name, :env => @sa.shell_env, :roles => @sa.roles, - :path => @app.root_path + :path => @app.root_path, + :sunshine_version => Sunshine::VERSION }.merge @sa.info deploy_info = @sa.get_deploy_info deploy_info.each do |key, val| next if key == :deployed_at assert_equal test_info[key], val end end def test_has_all_roles assert @sa.has_roles?([:web, :app, :blarg]) assert @sa.has_roles?([:web, :app, :blarg], true) end def test_has_roles @sa.roles = [:web, :app] assert @sa.has_roles?(:web) assert @sa.has_roles?([:web, :app]) assert [email protected]_roles?([:blarg, :web, :app]) assert @sa.has_roles?([:blarg, :web, :app], true) end def test_install_deps nginx_dep = Sunshine.dependencies.get 'nginx', :prefer => @sa.pkg_manager @sa.install_deps "ruby", nginx_dep assert_dep_install 'ruby', Sunshine::Yum assert_dep_install 'nginx', Sunshine::Yum end def test_install_deps_bad_type nginx_dep = Sunshine.dependencies.get 'nginx' @sa.install_deps nginx_dep, :type => Sunshine::Gem raise "Didn't raise missing dependency when it should have." rescue Sunshine::DependencyLib::MissingDependency => e assert_equal "No dependency 'nginx' [Sunshine::Gem]", e.message end def test_make_app_directories @sa.make_app_directories assert_server_call "mkdir -p #{@sa.directories.join(" ")}" end def test_make_bash_script app_script = @sa.make_bash_script "blah", [1,2,3,4] assert_bash_script "blah", [1,2,3,4], app_script end def test_make_env_bash_script @sa.shell.env = {"BLAH" => "blarg", "HOME" => "/home/blah"} test_script = "#!/bin/bash\nenv BLAH=blarg HOME=/home/blah \"$@\"" assert_equal test_script, @sa.make_env_bash_script end def test_rake @sa.rake "db:migrate" assert_dep_install 'rake', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && rake db:migrate" end def test_register_as_deployed Sunshine::AddCommand.extend MockObject unless MockObject === Sunshine::AddCommand @sa.register_as_deployed args = [@app.root_path, {'servers' => [@sa.shell]}] assert Sunshine::AddCommand.method_called?(:exec, :args => args) end def test_remove_old_deploys Sunshine.setup 'max_deploy_versions' => 3 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_server_call "rm -rf #{removed.join(" ")}" end def test_remove_old_deploys_unnecessary Sunshine.setup 'max_deploy_versions' => 5 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.mock :call, :args => ["ls -1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_not_called "rm -rf #{removed.join(" ")}" end def test_revert! deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" last_deploy = "#{@app.deploys_path}/ploy5" assert_server_call "ln -sfT #{last_deploy} #{@app.current_path}" end def test_no_previous_revert! @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" end def test_run_bundler @sa.run_bundler assert_dep_install 'bundler', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && gem bundle" end def test_run_geminstaller @sa.run_geminstaller assert_dep_install 'geminstaller', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && geminstaller -e" end def test_sass sass_files = %w{file1 file2 file3} @sa.sass(*sass_files) assert_dep_install 'haml', @sa.pkg_manager sass_files.each do |file| sass_file = "public/stylesheets/sass/#{file}.sass" css_file = "public/stylesheets/#{file}.css" assert_server_call \ "cd #{@app.checkout_path} && sass #{sass_file} #{css_file}" end end def test_shell_env assert_equal @sa.shell.env, @sa.shell_env end def test_symlink_current_dir @sa.symlink_current_dir assert_server_call "ln -sfT #{@app.checkout_path} #{@app.current_path}" end def test_upload_tasks files = %w{task1 task2} @sa.upload_tasks(*files) assert_server_call "mkdir -p #{@app.checkout_path}/lib/tasks" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{@app.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_with_remote_path files = %w{task1 task2} path = "/path/to/remote/tasks" @sa.upload_tasks files[0], files[1], :remote_path => path assert_server_call "mkdir -p #{path}" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{path}/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_with_local_path files = %w{task1 task2} path = "/path/to/local/tasks" args = files.dup << {:local_path => path} @sa.upload_tasks(*args) assert_server_call "mkdir -p #{@sa.checkout_path}/lib/tasks" files.each do |f| args = ["#{path}/#{f}.rake", "#{@sa.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_all files = Dir.glob("templates/tasks/*").map{|f| File.basename(f, ".rake")} @sa.upload_tasks assert_server_call "mkdir -p #{@app.checkout_path}/lib/tasks" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{@app.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_write_script @sa.shell.mock :file?, :return => false @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert @sa.shell.method_called?(:make_file, :args => args) end def test_symlink_scripts_to_root @sa.shell.mock :call, :args => ["ls -1 #{@sa.scripts_path}"], :return => "script_name\n" args = ["#{@app.scripts_path}/script_name", "#{@app.root_path}/script_name"] @sa.symlink_scripts_to_root assert @sa.shell.method_called?(:symlink, :args => args) end def test_write_script_existing @sa.shell.mock :file?, :return => true @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert [email protected]_called?(:make_file, :args => args) end end
jcasts/sunshine
1b97c480ff537d61a5afc02391e114a570015991
added building server app from deploy info file
diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index 84cc288..14c1fbf 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -1,683 +1,684 @@ module Sunshine ## # Handles App deployment functionality for a single deploy server. # # Server apps can be assigned any number of roles for classification. # :roles:: sym|array - roles assigned (web, db, app, etc...) # By default server apps get the special :all role which will # always return true when calling: # server_app.has_roles? :some_role # # ServerApp objects can be instantiated several ways: # ServerApp.new app_instance, shell_instance, options_hash # # When passing an App instance, the new ServerApp will keep an active link # to the app's properties. Name, deploy, and path attributes will be # actively linked. # # Rely on ServerApp to create a RemoteShell instance to use: # ServerApp.new app_instance, "host.com", options_hash # # Instantiate with app name and rely on Sunshine defaults for app paths: # ServerApp.new "app_name", shell_instance, options_hash # # Explicitely assign the app's root path: # ServerApp.new "app_name", ..., :root_path => "/path/to/app_root" # # Assigning a specific deploy name to use can be done with the # :deploy_name option: # ServerApp.new "app_name", ..., :deploy_name => "deploy" class ServerApp ## # Define an attribue that will get a value from app, or locally if # @app isn't set. def self.app_attr *attribs attribs.each do |attrib| class_eval <<-STR, __FILE__, __LINE__ + 1 def #{attrib} @app ? @app.send(:#{attrib}) : @#{attrib} end STR end end ## # Creates dependency instance methods such as gem_install, yum_install, etc # on both App and ServerApp classes. def self.register_dependency_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = Hash === names.last ? names.delete_at(-1) : Hash.new names.each do |name| dep = #{dep_class}.new(name, options) dep.install! :call => @shell end end STR App.class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = names.last if Hash === names.last with_server_apps options, :msg => "Installing #{dep_class.short_name} packages", :send => [:#{dep_class.short_name}_install, *names] end STR end ## # Creates a ServerApp instance from a deploy info file. - def from_info_file path, shell=nil + def self.from_info_file path, shell=nil shell ||= Sunshine.shell opts = YAML.load shell.call("cat #{path}") opts[:root_path] = opts.delete :path sa_shell = shell.dup sa_shell.env = opts[:env] || Hash.new - sa_shell.connect + sa_shell.connect if shell.connected? new opts[:name], sa_shell, opts end app_attr :name, :deploy_name app_attr :root_path, :checkout_path, :current_path app_attr :deploys_path, :log_path, :shared_path, :scripts_path attr_accessor :app, :roles, :scripts, :info, :shell, :crontab, :health attr_writer :pkg_manager ## # Create a server app instance. Supports the following # argument configurations: # # ServerApp.new app_inst, "myserver.com", :roles => :web # ServerApp.new "app_name", shell_inst, options_hash def initialize app, host, options={} @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell @health = Healthcheck.new shared_path, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No daemons for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), + :name => self.name, :env => shell_env, :roles => @roles, :path => self.root_path }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec self.root_path, 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart @shell.call "#{self.root_path}/restart" rescue false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the script_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block rescue false end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script :status, :sudo => false end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} RsyncRepo.new(code_dir).checkout_to self.checkout_path, @shell @info[:scm] = scm_info end ## # Upload common rake tasks from a local path or the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', ... # #=> upload app and common rake files # # File paths may also be used instead of the file's base name but # directory structures will not be followed: # app.upload_tasks 'lib/common/app.rake', 'lib/do_thing.rake' # # Allows options: # :local_path:: str - the path to get rake tasks from # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files[-1] ? files.delete_at(-1) : {} remote_path = options[:remote_path] || "#{self.checkout_path}/lib/tasks" local_path = options[:local_path] || "#{Sunshine::ROOT}/templates/tasks" @shell.call "mkdir -p #{remote_path}" files.map! do |file| if File.basename(file) == file File.join(local_path, "#{file}.rake") else file end end files = Dir.glob("#{Sunshine::ROOT}/templates/tasks/*") if files.empty? files.each do |file| remote_file = File.join remote_path, File.basename(file) @shell.upload file, remote_file end end ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end end end diff --git a/test/unit/test_server_app.rb b/test/unit/test_server_app.rb index 58b6bab..415c4e6 100644 --- a/test/unit/test_server_app.rb +++ b/test/unit/test_server_app.rb @@ -1,465 +1,488 @@ require 'test_helper' class TestServerApp < Test::Unit::TestCase def setup mock_svn_response @app = mock_app @app.repo.extend MockObject @sa = Sunshine::ServerApp.new @app, mock_remote_shell @sa.extend MockObject use_remote_shell @sa.shell end + def test_from_info_file + info_data = @sa.get_deploy_info.to_yaml + @sa.shell.mock :call, :args => "cat info/path", :return => info_data + + server_app = Sunshine::ServerApp.from_info_file "info/path", @sa.shell + + assert_equal @sa.root_path, server_app.root_path + assert_equal @sa.checkout_path, server_app.checkout_path + assert_equal @sa.current_path, server_app.current_path + assert_equal @sa.deploys_path, server_app.deploys_path + assert_equal @sa.log_path, server_app.log_path + assert_equal @sa.shared_path, server_app.shared_path + assert_equal @sa.scripts_path, server_app.scripts_path + assert_equal @sa.roles, server_app.roles + + assert_equal @sa.shell.env, server_app.shell_env + assert_equal @sa.name, server_app.name + assert_equal @sa.deploy_name, server_app.deploy_name + end + + def test_init default_info = {:ports => {}} assert_equal default_info, @sa.info assert_equal @app, @sa.app assert_equal Hash.new, @sa.scripts assert_equal [:all], @sa.roles end def test_init_roles sa = Sunshine::ServerApp.new @app, "host", :roles => "role1 role2" assert_equal [:role1, :role2], sa.roles sa = Sunshine::ServerApp.new @app, "host", :roles => %w{role3 role4} assert_equal [:role3, :role4], sa.roles end def test_add_shell_paths @sa.add_shell_paths "test/path1", "test/path2" assert_equal "test/path1:test/path2:$PATH", @sa.shell_env['PATH'] @sa.add_shell_paths "test/path3", "test/path4" assert_equal "test/path3:test/path4:test/path1:test/path2:$PATH", @sa.shell_env['PATH'] end def test_app_attr sa_root_path = "local/server_app/path" sa_deploy_name = "local_deploy_name" @sa = Sunshine::ServerApp.new "test", "host", :root_path => sa_root_path, :deploy_name => sa_deploy_name assert_equal sa_root_path, @sa.root_path assert_equal sa_deploy_name, @sa.deploy_name assert_equal "test", @sa.name @sa.app = @app assert_not_equal sa_root_path, @sa.root_path assert_not_equal sa_deploy_name, @sa.deploy_name assert_not_equal "test", @sa.name assert_equal @app.root_path, @sa.root_path assert_equal @app.deploy_name, @sa.deploy_name assert_equal @app.name, @sa.name end def test_build_control_scripts @sa.scripts[:start] << "start" @sa.scripts[:stop] << "stop" @sa.scripts[:custom] << "custom" @sa.build_control_scripts [:start, :stop, :custom].each do |script| content = @sa.make_bash_script script, @sa.scripts[script] assert @sa.method_called?(:write_script, :args => [script, content]) end content = @sa.make_env_bash_script assert @sa.method_called?(:write_script, :args => ["env", content]) content = @sa.make_bash_script :restart, ["#{@sa.app.root_path}/stop", "#{@sa.app.root_path}/start"] assert @sa.method_called?(:write_script, :args => [:restart, content]) end def test_build_deploy_info_file @sa.shell.mock :file?, :return => false args = ["#{@app.scripts_path}/info", @sa.get_deploy_info.to_yaml] @sa.build_deploy_info_file assert @sa.shell.method_called?(:make_file, :args => args) args = ["#{@app.scripts_path}/info", "#{@app.root_path}/info"] assert @sa.shell.method_called?(:symlink, :args => args) end def test_checkout_repo @sa.checkout_repo @app.repo repo = @sa.app.repo args = [@app.checkout_path, @sa.shell] assert repo.method_called?(:checkout_to, :args => args) info = @app.repo.checkout_to @app.checkout_path, @sa.shell assert_equal info, @sa.info[:scm] end def test_deploy_details deploy_details = {:item => "thing"} other_details = {:key => "value"} @sa.shell.mock :call, :args => ["cat #{@sa.root_path}/info"], :return => other_details.to_yaml @sa.instance_variable_set "@deploy_details", deploy_details assert_equal deploy_details, @sa.deploy_details assert_equal other_details, @sa.deploy_details(true) end def test_not_deployed? @sa.mock :deploy_details, :args => [true], :return => nil assert_equal false, @sa.deployed? end def test_server_checked_deployed? @sa.mock :deploy_details, :args => [true], :return => {:deploy_name => @sa.deploy_name} assert_equal true, @sa.deployed? end def test_cached_details_deployed? @sa.instance_variable_set "@deploy_details", :deploy_name => @sa.deploy_name assert_equal true, @sa.deployed? end def test_get_deploy_info test_info = { :deployed_at => Time.now.to_s, :deployed_as => @sa.shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(@app.checkout_path), + :name => @sa.name, + :env => @sa.shell_env, :roles => @sa.roles, :path => @app.root_path }.merge @sa.info deploy_info = @sa.get_deploy_info deploy_info.each do |key, val| next if key == :deployed_at assert_equal test_info[key], val end end def test_has_all_roles assert @sa.has_roles?([:web, :app, :blarg]) assert @sa.has_roles?([:web, :app, :blarg], true) end def test_has_roles @sa.roles = [:web, :app] assert @sa.has_roles?(:web) assert @sa.has_roles?([:web, :app]) assert [email protected]_roles?([:blarg, :web, :app]) assert @sa.has_roles?([:blarg, :web, :app], true) end def test_install_deps nginx_dep = Sunshine.dependencies.get 'nginx', :prefer => @sa.pkg_manager @sa.install_deps "ruby", nginx_dep assert_dep_install 'ruby', Sunshine::Yum assert_dep_install 'nginx', Sunshine::Yum end def test_install_deps_bad_type nginx_dep = Sunshine.dependencies.get 'nginx' @sa.install_deps nginx_dep, :type => Sunshine::Gem raise "Didn't raise missing dependency when it should have." rescue Sunshine::DependencyLib::MissingDependency => e assert_equal "No dependency 'nginx' [Sunshine::Gem]", e.message end def test_make_app_directories @sa.make_app_directories assert_server_call "mkdir -p #{@sa.directories.join(" ")}" end def test_make_bash_script app_script = @sa.make_bash_script "blah", [1,2,3,4] assert_bash_script "blah", [1,2,3,4], app_script end def test_make_env_bash_script @sa.shell.env = {"BLAH" => "blarg", "HOME" => "/home/blah"} test_script = "#!/bin/bash\nenv BLAH=blarg HOME=/home/blah \"$@\"" assert_equal test_script, @sa.make_env_bash_script end def test_rake @sa.rake "db:migrate" assert_dep_install 'rake', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && rake db:migrate" end def test_register_as_deployed Sunshine::AddCommand.extend MockObject unless MockObject === Sunshine::AddCommand @sa.register_as_deployed args = [@app.root_path, {'servers' => [@sa.shell]}] assert Sunshine::AddCommand.method_called?(:exec, :args => args) end def test_remove_old_deploys Sunshine.setup 'max_deploy_versions' => 3 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_server_call "rm -rf #{removed.join(" ")}" end def test_remove_old_deploys_unnecessary Sunshine.setup 'max_deploy_versions' => 5 deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.mock :call, :args => ["ls -1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" removed = deploys[0..1].map{|d| "#{@app.deploys_path}/#{d}"} @sa.remove_old_deploys assert_not_called "rm -rf #{removed.join(" ")}" end def test_revert! deploys = %w{ploy1 ploy2 ploy3 ploy4 ploy5} @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "#{deploys.join("\n")}\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" last_deploy = "#{@app.deploys_path}/ploy5" assert_server_call "ln -sfT #{last_deploy} #{@app.current_path}" end def test_no_previous_revert! @sa.shell.mock :call, :args => ["ls -rc1 #{@app.deploys_path}"], :return => "\n" @sa.revert! assert_server_call "rm -rf #{@app.checkout_path}" assert_server_call "ls -rc1 #{@app.deploys_path}" end def test_run_bundler @sa.run_bundler assert_dep_install 'bundler', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && gem bundle" end def test_run_geminstaller @sa.run_geminstaller assert_dep_install 'geminstaller', @sa.pkg_manager assert_server_call "cd #{@app.checkout_path} && geminstaller -e" end def test_sass sass_files = %w{file1 file2 file3} @sa.sass(*sass_files) assert_dep_install 'haml', @sa.pkg_manager sass_files.each do |file| sass_file = "public/stylesheets/sass/#{file}.sass" css_file = "public/stylesheets/#{file}.css" assert_server_call \ "cd #{@app.checkout_path} && sass #{sass_file} #{css_file}" end end def test_shell_env assert_equal @sa.shell.env, @sa.shell_env end def test_symlink_current_dir @sa.symlink_current_dir assert_server_call "ln -sfT #{@app.checkout_path} #{@app.current_path}" end def test_upload_tasks files = %w{task1 task2} @sa.upload_tasks(*files) assert_server_call "mkdir -p #{@app.checkout_path}/lib/tasks" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{@app.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_with_remote_path files = %w{task1 task2} path = "/path/to/remote/tasks" @sa.upload_tasks files[0], files[1], :remote_path => path assert_server_call "mkdir -p #{path}" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{path}/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_with_local_path files = %w{task1 task2} path = "/path/to/local/tasks" args = files.dup << {:local_path => path} @sa.upload_tasks(*args) assert_server_call "mkdir -p #{@sa.checkout_path}/lib/tasks" files.each do |f| args = ["#{path}/#{f}.rake", "#{@sa.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_upload_tasks_all files = Dir.glob("templates/tasks/*").map{|f| File.basename(f, ".rake")} @sa.upload_tasks assert_server_call "mkdir -p #{@app.checkout_path}/lib/tasks" files.each do |f| args = ["#{Sunshine::ROOT}/templates/tasks/#{f}.rake", "#{@app.checkout_path}/lib/tasks/#{f}.rake"] assert @sa.shell.method_called?(:upload, :args => args) end end def test_write_script @sa.shell.mock :file?, :return => false @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert @sa.shell.method_called?(:make_file, :args => args) end def test_symlink_scripts_to_root @sa.shell.mock :call, :args => ["ls -1 #{@sa.scripts_path}"], :return => "script_name\n" args = ["#{@app.scripts_path}/script_name", "#{@app.root_path}/script_name"] @sa.symlink_scripts_to_root assert @sa.shell.method_called?(:symlink, :args => args) end def test_write_script_existing @sa.shell.mock :file?, :return => true @sa.write_script "script_name", "script contents" args = ["#{@app.scripts_path}/script_name", "script contents", {:flags => "--chmod=ugo=rwx"}] assert [email protected]_called?(:make_file, :args => args) end end
jcasts/sunshine
5a28dc12dd0778182686f2671f3ffacadc09b048
added ability to instantiate a server app from the deploy info file
diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index 266df46..84cc288 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -1,595 +1,619 @@ module Sunshine ## # Handles App deployment functionality for a single deploy server. # # Server apps can be assigned any number of roles for classification. # :roles:: sym|array - roles assigned (web, db, app, etc...) # By default server apps get the special :all role which will # always return true when calling: # server_app.has_roles? :some_role # # ServerApp objects can be instantiated several ways: # ServerApp.new app_instance, shell_instance, options_hash # # When passing an App instance, the new ServerApp will keep an active link # to the app's properties. Name, deploy, and path attributes will be # actively linked. # # Rely on ServerApp to create a RemoteShell instance to use: # ServerApp.new app_instance, "host.com", options_hash # # Instantiate with app name and rely on Sunshine defaults for app paths: # ServerApp.new "app_name", shell_instance, options_hash # # Explicitely assign the app's root path: # ServerApp.new "app_name", ..., :root_path => "/path/to/app_root" # # Assigning a specific deploy name to use can be done with the # :deploy_name option: # ServerApp.new "app_name", ..., :deploy_name => "deploy" class ServerApp ## # Define an attribue that will get a value from app, or locally if # @app isn't set. def self.app_attr *attribs attribs.each do |attrib| class_eval <<-STR, __FILE__, __LINE__ + 1 def #{attrib} @app ? @app.send(:#{attrib}) : @#{attrib} end STR end end ## # Creates dependency instance methods such as gem_install, yum_install, etc # on both App and ServerApp classes. def self.register_dependency_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = Hash === names.last ? names.delete_at(-1) : Hash.new names.each do |name| dep = #{dep_class}.new(name, options) dep.install! :call => @shell end end STR App.class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = names.last if Hash === names.last with_server_apps options, :msg => "Installing #{dep_class.short_name} packages", :send => [:#{dep_class.short_name}_install, *names] end STR end + ## + # Creates a ServerApp instance from a deploy info file. + + def from_info_file path, shell=nil + shell ||= Sunshine.shell + + opts = YAML.load shell.call("cat #{path}") + opts[:root_path] = opts.delete :path + + sa_shell = shell.dup + sa_shell.env = opts[:env] || Hash.new + sa_shell.connect + + new opts[:name], sa_shell, opts + end + + app_attr :name, :deploy_name app_attr :root_path, :checkout_path, :current_path app_attr :deploys_path, :log_path, :shared_path, :scripts_path attr_accessor :app, :roles, :scripts, :info, :shell, :crontab, :health attr_writer :pkg_manager + ## + # Create a server app instance. Supports the following + # argument configurations: + # + # ServerApp.new app_inst, "myserver.com", :roles => :web + # ServerApp.new "app_name", shell_inst, options_hash + def initialize app, host, options={} @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell @health = Healthcheck.new shared_path, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No daemons for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), :env => shell_env, :roles => @roles, :path => self.root_path }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec self.root_path, 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart @shell.call "#{self.root_path}/restart" rescue false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the script_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block rescue false end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script :status, :sudo => false end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} RsyncRepo.new(code_dir).checkout_to self.checkout_path, @shell @info[:scm] = scm_info end ## # Upload common rake tasks from a local path or the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', ... # #=> upload app and common rake files # # File paths may also be used instead of the file's base name but # directory structures will not be followed: # app.upload_tasks 'lib/common/app.rake', 'lib/do_thing.rake'
jcasts/sunshine
a494f1366e52ffb857d7f7401a59f17c9ba524ec
added ability to pass optional cmd to shell tty
diff --git a/lib/sunshine/remote_shell.rb b/lib/sunshine/remote_shell.rb index 2ec5113..2c349f0 100644 --- a/lib/sunshine/remote_shell.rb +++ b/lib/sunshine/remote_shell.rb @@ -1,270 +1,274 @@ module Sunshine ## # Keeps an SSH connection open to a server the app will be deployed to. # Deploy servers use the ssh command and support any ssh feature. # By default, deploy servers use the ControlMaster feature to share # socket connections, with the ControlPath = ~/.ssh/sunshine-%r%h:%p # # Setting session-persistant environment variables is supported by # accessing the @env attribute. class RemoteShell < Shell class ConnectionError < FatalDeployError; end ## # The loop to keep the ssh connection open. LOGIN_LOOP = "echo ok; echo ready; "+ "for (( ; ; )); do kill -0 $PPID && sleep 10 || exit; done;" LOGIN_TIMEOUT = 30 ## # Closes all remote shell connections. def self.disconnect_all return unless defined?(@remote_shells) @remote_shells.each{|rs| rs.disconnect} end ## # Registers a remote shell for global access from the class. # Handled automatically on initialization. def self.register remote_shell (@remote_shells ||= []) << remote_shell end attr_reader :host, :user, :pid attr_accessor :ssh_flags, :rsync_flags ## # Remote shells essentially need a host and optional user. # Typical instantiation is done through either of these methods: # RemoteShell.new "user@host" # RemoteShell.new "host", :user => "user" # # The constructor also supports the following options: # :env:: hash - hash of environment variables to set for the ssh session # :password:: string - password for ssh login; if missing the deploy server # will attempt to prompt the user for a password. def initialize host, options={} super $stdout, options @host, @user = host.split("@").reverse @user ||= options[:user] @rsync_flags = ["-azP"] @rsync_flags.concat [*options[:rsync_flags]] if options[:rsync_flags] @ssh_flags = [ "-o ControlMaster=auto", "-o ControlPath=~/.ssh/sunshine-%r@%h:%p" ] @ssh_flags.concat ["-l", @user] if @user @ssh_flags.concat [*options[:ssh_flags]] if options[:ssh_flags] @pid, @inn, @out, @err = nil self.class.register self end ## # Runs a command via SSH. Optional block is passed the # stream(stderr, stdout) and string data. def call command_str, options={}, &block Sunshine.logger.info @host, "Running: #{command_str}" do execute build_remote_cmd(command_str, options), &block end end ## # Connect to host via SSH and return process pid def connect return true if connected? cmd = ssh_cmd quote_cmd(LOGIN_LOOP), :sudo => false @pid, @inn, @out, @err = popen4 cmd.join(" ") @inn.sync = true data = "" ready = nil start_time = Time.now.to_i until ready || @out.eof? data << @out.readpartial(1024) ready = data =~ /ready/ raise TimeoutError if timed_out?(start_time, LOGIN_TIMEOUT) end unless connected? disconnect host_info = [@user, @host].compact.join("@") raise ConnectionError, "Can't connect to #{host_info}" end @inn.close @pid end ## # Check if SSH session is open and returns process pid def connected? Process.kill(0, @pid) && @pid rescue false end ## # Disconnect from host def disconnect @inn.close rescue nil @out.close rescue nil @err.close rescue nil kill_process @pid, "HUP" rescue nil @pid = nil end ## # Download a file via rsync def download from_path, to_path, options={}, &block from_path = "#{@host}:#{from_path}" Sunshine.logger.info @host, "Downloading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Expand a path: # shell.expand_path "~user/thing" # #=> "/home/user/thing" def expand_path path dir = File.dirname path full_dir = call "cd #{dir} && pwd" File.join full_dir, File.basename(path) end ## # Checks if the given file exists def file? filepath syscall "test -f #{filepath}" end ## # Start an interactive shell with preset permissions and env. + # Optionally pass a command to be run first. - def interactive! + def tty! cmd=nil sync do + cmd = [cmd, "sh -il"].compact.join " && " + cmd = quote_cmd cmd + pid = fork do exec \ - ssh_cmd(sudo_cmd(env_cmd("sh -il")), :flags => "-t").to_a.join(" ") + ssh_cmd(sudo_cmd(env_cmd(cmd)), :flags => "-t").to_a.join(" ") end Process.waitpid pid end end ## # Create a file remotely def make_file filepath, content, options={} temp_filepath = "#{TMP_DIR}/#{File.basename(filepath)}_#{Time.now.to_i}#{rand(10000)}" File.open(temp_filepath, "w+"){|f| f.write(content)} self.upload temp_filepath, filepath, options File.delete(temp_filepath) end ## # Builds an ssh command with permissions, env, etc. def build_remote_cmd cmd, options={} cmd = sh_cmd cmd cmd = env_cmd cmd cmd = sudo_cmd cmd, options cmd = ssh_cmd cmd, options end ## # Uploads a file via rsync def upload from_path, to_path, options={}, &block to_path = "#{@host}:#{to_path}" Sunshine.logger.info @host, "Uploading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Figure out which rsync flags to use. def build_rsync_flags options flags = @rsync_flags.dup remote_rsync = 'rsync' rsync_sudo = sudo_cmd remote_rsync, options unless rsync_sudo == remote_rsync flags << "--rsync-path='#{ rsync_sudo.join(" ") }'" end flags << "-e \"ssh #{@ssh_flags.join(' ')}\"" if @ssh_flags flags.concat [*options[:flags]] if options[:flags] flags end ## # Creates an rsync command. def rsync_cmd from_path, to_path, options={} cmd = ["rsync", build_rsync_flags(options), from_path, to_path] cmd.flatten.compact.join(" ") end ## # Wraps the command in an ssh call. def ssh_cmd cmd, options=nil options ||= {} flags = [*options[:flags]].concat @ssh_flags ["ssh", flags, @host, cmd].flatten.compact end end end diff --git a/lib/sunshine/shell.rb b/lib/sunshine/shell.rb index 4e0d38d..304a357 100644 --- a/lib/sunshine/shell.rb +++ b/lib/sunshine/shell.rb @@ -1,434 +1,436 @@ module Sunshine ## # The Shell class handles local input, output and execution to the shell. class Shell include Open4 class TimeoutError < CriticalDeployError; end LOCAL_USER = `whoami`.chomp LOCAL_HOST = `hostname`.chomp SUDO_FAILED = /^Sorry, try again./ SUDO_PROMPT = /^Password:/ attr_reader :user, :host, :password, :input, :output, :mutex attr_accessor :env, :sudo, :timeout def initialize output = $stdout, options={} @output = output $stdin.sync @input = HighLine.new $stdin @user = LOCAL_USER @host = LOCAL_HOST @sudo = options[:sudo] @env = options[:env] || {} @password = options[:password] @timeout = options[:timeout] || Sunshine.timeout @cmd_activity = nil @mutex = nil end ## # Checks for equality def == shell @host == shell.host && @user == shell.user rescue false end ## # Prompt the user for input. def ask(*args, &block) sync{ @input.ask(*args, &block) } end ## # Prompt the user to agree. def agree(*args, &block) sync{ @input.agree(*args, &block) } end ## # Execute a command on the local system and return the output. def call cmd, options={}, &block Sunshine.logger.info @host, "Running: #{cmd}" do execute sudo_cmd(cmd, options), &block end end ## # Close the output IO. (Required by the Logger class) def close @output.close end ## # Returns true. Compatibility method with RemoteShell. def connect true end ## # Returns true. Compatibility method with RemoteShell. def connected? true end ## # Returns true. Compatibility method with RemoteShell. def disconnect true end ## # Copies a file. Compatibility method with RemoteShell. def download from_path, to_path, options={}, &block Sunshine.logger.info @host, "Copying #{from_path} -> #{to_path}" do FileUtils.cp_r from_path, to_path end end alias upload download ## # Expands the path. Compatibility method with RemoteShell. def expand_path path File.expand_path path end ## # Checks if file exists. Compatibility method with RemoteShell. def file? filepath File.file? filepath end ## # Start an interactive shell with preset permissions and env. + # Optionally pass a command to be run first. - def interactive! + def tty! cmd=nil sync do + cmd = [cmd, "sh -il"].compact.join " && " pid = fork do - exec sudo_cmd(env_cmd("sh -il")).to_a.join(" ") + exec sudo_cmd(env_cmd(cmd)).to_a.join(" ") end Process.waitpid pid end end ## # Write a file. Compatibility method with RemoteShell. def make_file filepath, content, options={} File.open(filepath, "w+"){|f| f.write(content)} end ## # Get the name of the OS def os_name @os_name ||= call("uname -s").strip.downcase end ## # Prompt the user for a password def prompt_for_password host_info = [@user, @host].compact.join("@") @password = ask("#{host_info} Password:") do |q| q.echo = false end end ## # Build an env command if an env_hash is passed def env_cmd cmd, env_hash=@env if env_hash && !env_hash.empty? env_vars = env_hash.map{|e| e.join("=")} cmd = ["env", env_vars, cmd].flatten end cmd end ## # Wrap command in quotes and escape as needed. def quote_cmd cmd cmd = [*cmd].join(" ") "'#{cmd.gsub(/'/){|s| "'\\''"}}'" end ## # Build an sh -c command def sh_cmd cmd ["sh", "-c", quote_cmd(cmd)] end ## # Build a command with sudo. # If sudo_val is nil, it is considered to mean "pass-through" # and the default shell sudo will be used. # If sudo_val is false, the cmd will be returned unchanged. # If sudo_val is true, the returned command will be prefaced # with sudo -H # If sudo_val is a String, the command will be prefaced # with sudo -H -u string_value def sudo_cmd cmd, sudo_val=nil sudo_val = sudo_val[:sudo] if Hash === sudo_val sudo_val = @sudo if sudo_val.nil? case sudo_val when true ["sudo", "-H", cmd].flatten when String ["sudo", "-H", "-u", sudo_val, cmd].flatten else cmd end end ## # Force symlinking a directory. def symlink target, symlink_name call "ln -sfT #{target} #{symlink_name}" rescue false end ## # Synchronize a block with the current mutex if it exists. def sync if @mutex @mutex.synchronize{ yield } else yield end end ## # Returns true if command was run successfully, otherwise returns false. def syscall cmd, options=nil call(cmd, options) && true rescue false end ## # Checks if timeout occurred. def timed_out? start_time=@cmd_activity, max_time=@timeout return unless max_time Time.now.to_i - start_time.to_i > max_time end ## # Update the time of the last command activity def update_timeout @cmd_activity = Time.now end ## # Execute a block while setting the shell's mutex. # Sets the mutex to its original value on exit. # Executing commands with a mutex is used for user prompts. def with_mutex mutex old_mutex, @mutex = @mutex, mutex yield @mutex = old_mutex end ## # Runs the passed block within a connection session. # If the shell is already connected, connecting and disconnecting # is ignored; otherwise, the session method will ensure that # the shell's connection gets closed after the block has been # executed. def with_session prev_connection = connected? connect unless prev_connection yield disconnect unless prev_connection end ## # Write string to stdout (by default). def write str @output.write str end alias << write ## # Execute a command with open4 and loop until the process exits. # The cmd argument may be a string or an array. If a block is passed, # it will be called when data is received and passed the stream type # and stream string value: # shell.execute "test -s 'blah' && echo 'true'" do |stream, str| # stream #=> :stdout # string #=> 'true' # end # # The method returns the output from the stdout stream by default, and # raises a CmdError if the exit status of the command is not zero. def execute cmd cmd = [cmd] unless Array === cmd pid, inn, out, err = popen4(*cmd) inn.sync = true log_methods = {out => :debug, err => :error} result, status = process_streams(pid, out, err) do |stream, data| stream_name = :out if stream == out stream_name = :err if stream == err stream_name = :inn if stream == inn # User blocks should run with sync threads to avoid badness. sync do Sunshine.logger.send log_methods[stream], "#{@host}:#{stream_name}", data yield(stream_name, data, inn) if block_given? end if password_required?(stream_name, data) then kill_process(pid) unless Sunshine.interactive? send_password_to_stream(inn, data) end end raise_command_failed(status, cmd) unless status.success? result[out].join.chomp ensure inn.close rescue nil out.close rescue nil err.close rescue nil end private def raise_command_failed(status, cmd) raise CmdError, "Execution failed with status #{status.exitstatus}: #{[*cmd].join ' '}" end def password_required? stream_name, data stream_name == :err && data =~ SUDO_PROMPT end def send_password_to_stream inn, data prompt_for_password if data =~ SUDO_FAILED inn.puts @password || prompt_for_password end def kill_process pid, kill_type="KILL" begin Process.kill kill_type, pid Process.wait rescue end end def process_streams pid, *streams result = Hash.new{|h,k| h[k] = []} update_timeout # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 raise TimeoutError if timed_out? next if selected.nil? or selected.empty? selected.each do |stream| update_timeout if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) yield(stream, data) result[stream] << data end end return result, status end end end
jcasts/sunshine
d97a146080e3877781b48bbba0af46ea4cd9e653
added deploy env variables to info file creation
diff --git a/lib/sunshine/server_app.rb b/lib/sunshine/server_app.rb index eb1fe41..266df46 100644 --- a/lib/sunshine/server_app.rb +++ b/lib/sunshine/server_app.rb @@ -1,658 +1,659 @@ module Sunshine ## # Handles App deployment functionality for a single deploy server. # # Server apps can be assigned any number of roles for classification. # :roles:: sym|array - roles assigned (web, db, app, etc...) # By default server apps get the special :all role which will # always return true when calling: # server_app.has_roles? :some_role # # ServerApp objects can be instantiated several ways: # ServerApp.new app_instance, shell_instance, options_hash # # When passing an App instance, the new ServerApp will keep an active link # to the app's properties. Name, deploy, and path attributes will be # actively linked. # # Rely on ServerApp to create a RemoteShell instance to use: # ServerApp.new app_instance, "host.com", options_hash # # Instantiate with app name and rely on Sunshine defaults for app paths: # ServerApp.new "app_name", shell_instance, options_hash # # Explicitely assign the app's root path: # ServerApp.new "app_name", ..., :root_path => "/path/to/app_root" # # Assigning a specific deploy name to use can be done with the # :deploy_name option: # ServerApp.new "app_name", ..., :deploy_name => "deploy" class ServerApp ## # Define an attribue that will get a value from app, or locally if # @app isn't set. def self.app_attr *attribs attribs.each do |attrib| class_eval <<-STR, __FILE__, __LINE__ + 1 def #{attrib} @app ? @app.send(:#{attrib}) : @#{attrib} end STR end end ## # Creates dependency instance methods such as gem_install, yum_install, etc # on both App and ServerApp classes. def self.register_dependency_type dep_class class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = Hash === names.last ? names.delete_at(-1) : Hash.new names.each do |name| dep = #{dep_class}.new(name, options) dep.install! :call => @shell end end STR App.class_eval <<-STR, __FILE__, __LINE__ + 1 def #{dep_class.short_name}_install(*names) options = names.last if Hash === names.last with_server_apps options, :msg => "Installing #{dep_class.short_name} packages", :send => [:#{dep_class.short_name}_install, *names] end STR end app_attr :name, :deploy_name app_attr :root_path, :checkout_path, :current_path app_attr :deploys_path, :log_path, :shared_path, :scripts_path attr_accessor :app, :roles, :scripts, :info, :shell, :crontab, :health attr_writer :pkg_manager def initialize app, host, options={} @app = App === app ? app : nil name = @app && @app.name || app assign_local_app_attr name, options @deploy_details = nil @roles = options[:roles] || [:all] @roles = @roles.split(" ") if String === @roles @roles = [*@roles].compact.map{|r| r.to_sym } @scripts = Hash.new{|h, k| h[k] = []} @info = {:ports => {}} @pkg_manager = nil @shell = case host when String then RemoteShell.new host, options when Shell then host else raise "Could not get remote shell '#{host}'" end @crontab = Crontab.new name, @shell @health = Healthcheck.new shared_path, @shell @all_deploy_names = nil @previous_deploy_name = nil end ## # Add paths the the shell $PATH env. def add_shell_paths(*paths) path = shell_env["PATH"] || "$PATH" paths << path shell_env.merge! "PATH" => paths.join(":") end ## # Creates and uploads all control scripts for the application. # To add to, or define a control script, see App#add_to_script. def build_control_scripts @shell.call "mkdir -p #{self.scripts_path}" write_script "env", make_env_bash_script build_scripts = @scripts.dup if build_scripts[:restart].empty? && !build_scripts[:start].empty? && !build_scripts[:stop].empty? build_scripts[:restart] << "#{self.root_path}/stop" build_scripts[:restart] << "#{self.root_path}/start" end if build_scripts[:status].empty? build_scripts[:status] << "echo 'No daemons for #{self.name}'; exit 1;" end build_scripts.each do |name, cmds| if cmds.empty? Sunshine.logger.warn @shell.host, "#{name} script is empty" end bash = make_bash_script name, cmds write_script name, bash end symlink_scripts_to_root end ## # Creates a yaml file with deploy information. To add custom information # to the info file, use the app's info hash attribute: # app.info[:key] = "some value" def build_deploy_info_file deploy_info = get_deploy_info.to_yaml info_filepath = "#{self.scripts_path}/info" @shell.make_file info_filepath, deploy_info @shell.symlink info_filepath, "#{self.root_path}/info" end ## # Checks out the app's codebase to the checkout path. def checkout_repo repo, scm_info={} install_deps repo.scm Sunshine.logger.info repo.scm, "Checking out to #{@shell.host} #{self.checkout_path}" do @info[:scm] = repo.checkout_to self.checkout_path, @shell @info[:scm].merge! scm_info end end ## # Get post-mortum information about the app's deploy, from the # generated deploy info file. # Post-deploy only. def deploy_details reload=false return @deploy_details if @deploy_details && !reload @deploy_details = YAML.load @shell.call("cat #{self.root_path}/info") rescue nil @deploy_details = nil unless Hash === @deploy_details @deploy_details end ## # Checks if the server_app's current info file deploy_name matches # the server_app's deploy_name attribute. def deployed? success = @deploy_details[:deploy_name] == self.deploy_name if @deploy_details return success if success deploy_details(true)[:deploy_name] == self.deploy_name rescue false end ## # An array of all directories used by the app. # Does not include symlinked directories. def directories [root_path, deploys_path, shared_path, log_path, checkout_path, scripts_path] end ## # Builds a hash with information about the deploy at hand. def get_deploy_info { :deployed_at => Time.now.to_s, :deployed_as => @shell.call("whoami"), :deployed_by => Sunshine.shell.user, :deploy_name => File.basename(self.checkout_path), + :env => shell_env, :roles => @roles, :path => self.root_path }.merge @info end ## # Decrypt a file using gpg. Allows options: # :output:: str - the path the output file should go to # :passphrase:: str - the passphrase gpg should use def gpg_decrypt gpg_file, options={} output_file = options[:output] || gpg_file.gsub(/\.gpg$/, '') passphrase = options[:passphrase] passphrase_file = "#{self.root_path}/tmp/gpg_passphrase" gpg_cmd = "gpg --batch --no-tty --yes --output #{output_file} "+ "--passphrase-file #{passphrase_file} --decrypt #{gpg_file}" @shell.call "mkdir -p #{File.dirname(passphrase_file)}" @shell.make_file passphrase_file, passphrase @shell.call "cd #{self.checkout_path} && #{gpg_cmd}" @shell.call "rm -f #{passphrase_file}" end ## # Check if this server app includes the specified roles: # server_app.has_roles? :web # server_app.has_roles? [:web, :app] # # The boolean operator may be changed to OR by passing true as the # second argument: # server_app.roles = [:web, :app] # server_app.has_roles? [:web, :db] #=> false # server_app.has_roles? [:web, :db], true #=> true def has_roles? roles, match_any=false roles = [*roles] return true if @roles.include? :all return !(roles & @roles).empty? if match_any (roles & @roles).length == roles.length end ## # Install dependencies previously defined in Sunshine.dependencies. # Will not execute if Sunshine.auto_dependencies? is false. def install_deps(*deps) return unless Sunshine.auto_dependencies? options = {:call => @shell, :prefer => pkg_manager} options.merge! deps.delete_at(-1) if Hash === deps.last args = deps << options Sunshine.dependencies.install(*args) end ## # Creates the required application directories. def make_app_directories @shell.call "mkdir -p #{self.directories.join(" ")}" end ## # Makes an array of bash commands into a script that # echoes 'true' on success. def make_bash_script name, cmds cmds = cmds.map{|cmd| "(#{cmd})" } cmds << "echo true" bash = <<-STR #!/bin/bash if [ "$1" == "--no-env" ]; then #{cmds.flatten.join(" && ")} else #{self.root_path}/env #{self.root_path}/#{name} --no-env fi STR end ## # Creates the one-off env script that will be used by other scripts # to correctly set their env variables. def make_env_bash_script env_str = shell_env.map{|e| e.join("=")}.join(" ") "#!/bin/bash\nenv #{env_str} \"$@\"" end ## # Returns the type of package management system to use. def pkg_manager @pkg_manager ||= DependencyLib.dependency_types.detect do |dt| dt.system_manager? @shell end end ## # Returns an array of all deploys in the deploys_path dir, # starting with the oldest. def all_deploy_names reload=false return @all_deploy_names if @all_deploy_names && !reload @all_deploy_names = @shell.call("ls -rc1 #{self.deploys_path}").split("\n") end ## # Returns the name of the previous deploy. def previous_deploy_name reload=false return @previous_deploy_name if @previous_deploy_name && !reload arr = all_deploy_names(reload) arr.delete(@deploy_name) @previous_deploy_name = arr.last end ## # Run a rake task the deploy server. def rake command install_deps 'rake', :type => Gem @shell.call "cd #{self.checkout_path} && rake #{command}" end ## # Adds the app to the deploy server's deployed-apps list def register_as_deployed AddCommand.exec self.root_path, 'servers' => [@shell] end ## # Removes old deploys from the checkout_dir # based on Sunshine's max_deploy_versions. def remove_old_deploys deploys = all_deploy_names true return unless deploys.length > Sunshine.max_deploy_versions lim = Sunshine.max_deploy_versions + 1 rm_deploys = deploys[0..-lim] rm_deploys.map!{|d| "#{self.deploys_path}/#{d}"} @shell.call "rm -rf #{rm_deploys.join(" ")}" end ## # Run the app's restart script. Returns false on failure. # Post-deploy only. def restart @shell.call "#{self.root_path}/restart" rescue false end ## # Symlink current directory to previous checkout and remove # the current deploy directory. def revert! @shell.call "rm -rf #{self.checkout_path}" last_deploy = previous_deploy_name(true) if last_deploy && !last_deploy.empty? @shell.symlink "#{self.deploys_path}/#{last_deploy}", self.current_path Sunshine.logger.info @shell.host, "Reverted to #{last_deploy}" else @crontab.delete! Sunshine.logger.info @shell.host, "No previous deploy to revert to." end end ## # Runs bundler. Installs the bundler gem if missing. def run_bundler options={} install_deps 'bundler', :type => Gem @shell.call "cd #{self.checkout_path} && gem bundle", options end ## # Runs geminstaller. :( # Deprecated: how about trying bundler or isolate? # If sudo is required to install to your GEM_HOME, make sure to # pass it as an argument: # server_app.run_geminstaller :sudo => true def run_geminstaller options={} install_deps 'geminstaller', :type => Gem # Without sudo gems get installed to ~user/.gems @shell.call "cd #{self.checkout_path} && geminstaller -e", options end ## # Runs a script from the script_path. # Post-deploy only. def run_script name, options=nil, &block options ||= {} script_path = File.join self.root_path, name.to_s @shell.call script_path, options, &block rescue false end ## # Check if the app pids are present. # Post-deploy only. def running? # Permissions are handled by the script, use: :sudo => false run_script :status, :sudo => false end ## # Run a sass task on any or all deploy servers. def sass *sass_names install_deps 'haml', :type => Gem sass_names.flatten.each do |name| sass_file = "public/stylesheets/sass/#{name}.sass" css_file = "public/stylesheets/#{name}.css" sass_cmd = "cd #{self.checkout_path} && sass #{sass_file} #{css_file}" @shell.call sass_cmd end end ## # Get the deploy server's shell environment. def shell_env @shell.env end ## # Run the app's start script. Returns false on failure. # Post-deploy only. def start options=nil options ||= {} if running? return unless options[:force] stop end # Permissions are handled by the script, use: :sudo => false run_script :start, :sudo => false end ## # Get the app's status: :running or :down. def status running? ? :running : :down end ## # Run the app's stop script. Returns false on failure. # Post-deploy only. def stop # Permissions are handled by the script, use: :sudo => false run_script :stop, :sudo => false end ## # Creates a symlink to the app's checkout path. def symlink_current_dir @shell.symlink self.checkout_path, self.current_path end ## # Creates a symlink of every script in the scripts_path dir in the # app's root directory for easy access. def symlink_scripts_to_root scripts = @shell.call("ls -1 #{self.scripts_path}").split("\n") scripts.each do |name| script_file = File.join self.scripts_path, name pointer_file = File.join self.root_path, name @shell.symlink script_file, pointer_file end end ## # Assumes the passed code_dir is the root directory of the checked out # codebase and uploads it to the checkout_path. def upload_codebase code_dir, scm_info={} RsyncRepo.new(code_dir).checkout_to self.checkout_path, @shell @info[:scm] = scm_info end ## # Upload common rake tasks from a local path or the sunshine lib. # app.upload_tasks # #=> upload all tasks # app.upload_tasks 'app', 'common', ... # #=> upload app and common rake files # # File paths may also be used instead of the file's base name but # directory structures will not be followed: # app.upload_tasks 'lib/common/app.rake', 'lib/do_thing.rake' # # Allows options: # :local_path:: str - the path to get rake tasks from # :remote_path:: str - the remote absolute path to upload the files to def upload_tasks *files options = Hash === files[-1] ? files.delete_at(-1) : {} remote_path = options[:remote_path] || "#{self.checkout_path}/lib/tasks" local_path = options[:local_path] || "#{Sunshine::ROOT}/templates/tasks" @shell.call "mkdir -p #{remote_path}" files.map! do |file| if File.basename(file) == file File.join(local_path, "#{file}.rake") else file end end files = Dir.glob("#{Sunshine::ROOT}/templates/tasks/*") if files.empty? files.each do |file| remote_file = File.join remote_path, File.basename(file) @shell.upload file, remote_file end end ## # Write an executable bash script to the app's scripts dir # on the deploy server, and symlink them to the root dir. def write_script name, contents script_file = "#{self.scripts_path}/#{name}" @shell.make_file script_file, contents, :flags => '--chmod=ugo=rwx' unless @shell.file? script_file end private ## # Set all the app paths based on the root app path. def assign_local_app_attr name, options={} @name = name @deploy_name = options[:deploy_name] || Time.now.to_i default_root = File.join(Sunshine.web_directory, @name) @root_path = options[:root_path] || default_root @current_path = "#{@root_path}/current" @deploys_path = "#{@root_path}/deploys" @shared_path = "#{@root_path}/shared" @log_path = "#{@shared_path}/log" @checkout_path = "#{@deploys_path}/#{@deploy_name}" @scripts_path = "#{@checkout_path}/sunshine_scripts" end end end
jcasts/sunshine
5e86f3a7166fbadd0529b8920f1fa7162445a1ca
added fix for non arrays
diff --git a/lib/sunshine/remote_shell.rb b/lib/sunshine/remote_shell.rb index 254c4d7..2ec5113 100644 --- a/lib/sunshine/remote_shell.rb +++ b/lib/sunshine/remote_shell.rb @@ -1,269 +1,270 @@ module Sunshine ## # Keeps an SSH connection open to a server the app will be deployed to. # Deploy servers use the ssh command and support any ssh feature. # By default, deploy servers use the ControlMaster feature to share # socket connections, with the ControlPath = ~/.ssh/sunshine-%r%h:%p # # Setting session-persistant environment variables is supported by # accessing the @env attribute. class RemoteShell < Shell class ConnectionError < FatalDeployError; end ## # The loop to keep the ssh connection open. LOGIN_LOOP = "echo ok; echo ready; "+ "for (( ; ; )); do kill -0 $PPID && sleep 10 || exit; done;" LOGIN_TIMEOUT = 30 ## # Closes all remote shell connections. def self.disconnect_all return unless defined?(@remote_shells) @remote_shells.each{|rs| rs.disconnect} end ## # Registers a remote shell for global access from the class. # Handled automatically on initialization. def self.register remote_shell (@remote_shells ||= []) << remote_shell end attr_reader :host, :user, :pid attr_accessor :ssh_flags, :rsync_flags ## # Remote shells essentially need a host and optional user. # Typical instantiation is done through either of these methods: # RemoteShell.new "user@host" # RemoteShell.new "host", :user => "user" # # The constructor also supports the following options: # :env:: hash - hash of environment variables to set for the ssh session # :password:: string - password for ssh login; if missing the deploy server # will attempt to prompt the user for a password. def initialize host, options={} super $stdout, options @host, @user = host.split("@").reverse @user ||= options[:user] @rsync_flags = ["-azP"] @rsync_flags.concat [*options[:rsync_flags]] if options[:rsync_flags] @ssh_flags = [ "-o ControlMaster=auto", "-o ControlPath=~/.ssh/sunshine-%r@%h:%p" ] @ssh_flags.concat ["-l", @user] if @user @ssh_flags.concat [*options[:ssh_flags]] if options[:ssh_flags] @pid, @inn, @out, @err = nil self.class.register self end ## # Runs a command via SSH. Optional block is passed the # stream(stderr, stdout) and string data. def call command_str, options={}, &block Sunshine.logger.info @host, "Running: #{command_str}" do execute build_remote_cmd(command_str, options), &block end end ## # Connect to host via SSH and return process pid def connect return true if connected? cmd = ssh_cmd quote_cmd(LOGIN_LOOP), :sudo => false @pid, @inn, @out, @err = popen4 cmd.join(" ") @inn.sync = true data = "" ready = nil start_time = Time.now.to_i until ready || @out.eof? data << @out.readpartial(1024) ready = data =~ /ready/ raise TimeoutError if timed_out?(start_time, LOGIN_TIMEOUT) end unless connected? disconnect host_info = [@user, @host].compact.join("@") raise ConnectionError, "Can't connect to #{host_info}" end @inn.close @pid end ## # Check if SSH session is open and returns process pid def connected? Process.kill(0, @pid) && @pid rescue false end ## # Disconnect from host def disconnect @inn.close rescue nil @out.close rescue nil @err.close rescue nil kill_process @pid, "HUP" rescue nil @pid = nil end ## # Download a file via rsync def download from_path, to_path, options={}, &block from_path = "#{@host}:#{from_path}" Sunshine.logger.info @host, "Downloading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Expand a path: # shell.expand_path "~user/thing" # #=> "/home/user/thing" def expand_path path dir = File.dirname path full_dir = call "cd #{dir} && pwd" File.join full_dir, File.basename(path) end ## # Checks if the given file exists def file? filepath syscall "test -f #{filepath}" end ## # Start an interactive shell with preset permissions and env. def interactive! sync do pid = fork do - exec ssh_cmd(sudo_cmd(env_cmd("sh -il")), :flags => "-t").join(" ") + exec \ + ssh_cmd(sudo_cmd(env_cmd("sh -il")), :flags => "-t").to_a.join(" ") end Process.waitpid pid end end ## # Create a file remotely def make_file filepath, content, options={} temp_filepath = "#{TMP_DIR}/#{File.basename(filepath)}_#{Time.now.to_i}#{rand(10000)}" File.open(temp_filepath, "w+"){|f| f.write(content)} self.upload temp_filepath, filepath, options File.delete(temp_filepath) end ## # Builds an ssh command with permissions, env, etc. def build_remote_cmd cmd, options={} cmd = sh_cmd cmd cmd = env_cmd cmd cmd = sudo_cmd cmd, options cmd = ssh_cmd cmd, options end ## # Uploads a file via rsync def upload from_path, to_path, options={}, &block to_path = "#{@host}:#{to_path}" Sunshine.logger.info @host, "Uploading #{from_path} -> #{to_path}" do execute rsync_cmd(from_path, to_path, options), &block end end ## # Figure out which rsync flags to use. def build_rsync_flags options flags = @rsync_flags.dup remote_rsync = 'rsync' rsync_sudo = sudo_cmd remote_rsync, options unless rsync_sudo == remote_rsync flags << "--rsync-path='#{ rsync_sudo.join(" ") }'" end flags << "-e \"ssh #{@ssh_flags.join(' ')}\"" if @ssh_flags flags.concat [*options[:flags]] if options[:flags] flags end ## # Creates an rsync command. def rsync_cmd from_path, to_path, options={} cmd = ["rsync", build_rsync_flags(options), from_path, to_path] cmd.flatten.compact.join(" ") end ## # Wraps the command in an ssh call. def ssh_cmd cmd, options=nil options ||= {} flags = [*options[:flags]].concat @ssh_flags ["ssh", flags, @host, cmd].flatten.compact end end end diff --git a/lib/sunshine/shell.rb b/lib/sunshine/shell.rb index 1a72e45..4e0d38d 100644 --- a/lib/sunshine/shell.rb +++ b/lib/sunshine/shell.rb @@ -1,434 +1,434 @@ module Sunshine ## # The Shell class handles local input, output and execution to the shell. class Shell include Open4 class TimeoutError < CriticalDeployError; end LOCAL_USER = `whoami`.chomp LOCAL_HOST = `hostname`.chomp SUDO_FAILED = /^Sorry, try again./ SUDO_PROMPT = /^Password:/ attr_reader :user, :host, :password, :input, :output, :mutex attr_accessor :env, :sudo, :timeout def initialize output = $stdout, options={} @output = output $stdin.sync @input = HighLine.new $stdin @user = LOCAL_USER @host = LOCAL_HOST @sudo = options[:sudo] @env = options[:env] || {} @password = options[:password] @timeout = options[:timeout] || Sunshine.timeout @cmd_activity = nil @mutex = nil end ## # Checks for equality def == shell @host == shell.host && @user == shell.user rescue false end ## # Prompt the user for input. def ask(*args, &block) sync{ @input.ask(*args, &block) } end ## # Prompt the user to agree. def agree(*args, &block) sync{ @input.agree(*args, &block) } end ## # Execute a command on the local system and return the output. def call cmd, options={}, &block Sunshine.logger.info @host, "Running: #{cmd}" do execute sudo_cmd(cmd, options), &block end end ## # Close the output IO. (Required by the Logger class) def close @output.close end ## # Returns true. Compatibility method with RemoteShell. def connect true end ## # Returns true. Compatibility method with RemoteShell. def connected? true end ## # Returns true. Compatibility method with RemoteShell. def disconnect true end ## # Copies a file. Compatibility method with RemoteShell. def download from_path, to_path, options={}, &block Sunshine.logger.info @host, "Copying #{from_path} -> #{to_path}" do FileUtils.cp_r from_path, to_path end end alias upload download ## # Expands the path. Compatibility method with RemoteShell. def expand_path path File.expand_path path end ## # Checks if file exists. Compatibility method with RemoteShell. def file? filepath File.file? filepath end ## # Start an interactive shell with preset permissions and env. def interactive! sync do pid = fork do - exec sudo_cmd(env_cmd("sh -il")).join(" ") + exec sudo_cmd(env_cmd("sh -il")).to_a.join(" ") end Process.waitpid pid end end ## # Write a file. Compatibility method with RemoteShell. def make_file filepath, content, options={} File.open(filepath, "w+"){|f| f.write(content)} end ## # Get the name of the OS def os_name @os_name ||= call("uname -s").strip.downcase end ## # Prompt the user for a password def prompt_for_password host_info = [@user, @host].compact.join("@") @password = ask("#{host_info} Password:") do |q| q.echo = false end end ## # Build an env command if an env_hash is passed def env_cmd cmd, env_hash=@env if env_hash && !env_hash.empty? env_vars = env_hash.map{|e| e.join("=")} cmd = ["env", env_vars, cmd].flatten end cmd end ## # Wrap command in quotes and escape as needed. def quote_cmd cmd cmd = [*cmd].join(" ") "'#{cmd.gsub(/'/){|s| "'\\''"}}'" end ## # Build an sh -c command def sh_cmd cmd ["sh", "-c", quote_cmd(cmd)] end ## # Build a command with sudo. # If sudo_val is nil, it is considered to mean "pass-through" # and the default shell sudo will be used. # If sudo_val is false, the cmd will be returned unchanged. # If sudo_val is true, the returned command will be prefaced # with sudo -H # If sudo_val is a String, the command will be prefaced # with sudo -H -u string_value def sudo_cmd cmd, sudo_val=nil sudo_val = sudo_val[:sudo] if Hash === sudo_val sudo_val = @sudo if sudo_val.nil? case sudo_val when true ["sudo", "-H", cmd].flatten when String ["sudo", "-H", "-u", sudo_val, cmd].flatten else cmd end end ## # Force symlinking a directory. def symlink target, symlink_name call "ln -sfT #{target} #{symlink_name}" rescue false end ## # Synchronize a block with the current mutex if it exists. def sync if @mutex @mutex.synchronize{ yield } else yield end end ## # Returns true if command was run successfully, otherwise returns false. def syscall cmd, options=nil call(cmd, options) && true rescue false end ## # Checks if timeout occurred. def timed_out? start_time=@cmd_activity, max_time=@timeout return unless max_time Time.now.to_i - start_time.to_i > max_time end ## # Update the time of the last command activity def update_timeout @cmd_activity = Time.now end ## # Execute a block while setting the shell's mutex. # Sets the mutex to its original value on exit. # Executing commands with a mutex is used for user prompts. def with_mutex mutex old_mutex, @mutex = @mutex, mutex yield @mutex = old_mutex end ## # Runs the passed block within a connection session. # If the shell is already connected, connecting and disconnecting # is ignored; otherwise, the session method will ensure that # the shell's connection gets closed after the block has been # executed. def with_session prev_connection = connected? connect unless prev_connection yield disconnect unless prev_connection end ## # Write string to stdout (by default). def write str @output.write str end alias << write ## # Execute a command with open4 and loop until the process exits. # The cmd argument may be a string or an array. If a block is passed, # it will be called when data is received and passed the stream type # and stream string value: # shell.execute "test -s 'blah' && echo 'true'" do |stream, str| # stream #=> :stdout # string #=> 'true' # end # # The method returns the output from the stdout stream by default, and # raises a CmdError if the exit status of the command is not zero. def execute cmd cmd = [cmd] unless Array === cmd pid, inn, out, err = popen4(*cmd) inn.sync = true log_methods = {out => :debug, err => :error} result, status = process_streams(pid, out, err) do |stream, data| stream_name = :out if stream == out stream_name = :err if stream == err stream_name = :inn if stream == inn # User blocks should run with sync threads to avoid badness. sync do Sunshine.logger.send log_methods[stream], "#{@host}:#{stream_name}", data yield(stream_name, data, inn) if block_given? end if password_required?(stream_name, data) then kill_process(pid) unless Sunshine.interactive? send_password_to_stream(inn, data) end end raise_command_failed(status, cmd) unless status.success? result[out].join.chomp ensure inn.close rescue nil out.close rescue nil err.close rescue nil end private def raise_command_failed(status, cmd) raise CmdError, "Execution failed with status #{status.exitstatus}: #{[*cmd].join ' '}" end def password_required? stream_name, data stream_name == :err && data =~ SUDO_PROMPT end def send_password_to_stream inn, data prompt_for_password if data =~ SUDO_FAILED inn.puts @password || prompt_for_password end def kill_process pid, kill_type="KILL" begin Process.kill kill_type, pid Process.wait rescue end end def process_streams pid, *streams result = Hash.new{|h,k| h[k] = []} update_timeout # Handle process termination ourselves status = nil Thread.start do status = Process.waitpid2(pid).last end until streams.empty? do # don't busy loop selected, = select streams, nil, nil, 0.1 raise TimeoutError if timed_out? next if selected.nil? or selected.empty? selected.each do |stream| update_timeout if stream.eof? then streams.delete stream if status # we've quit, so no more writing next end data = stream.readpartial(1024) yield(stream, data) result[stream] << data end end return result, status end end end
jan-kuechler/unitlib
dfe20a1a80a2b5d28cffb3009f2c3aa30a65d6b4
Fixed typo in the doc-comment for ul_quit()
diff --git a/include/unitlib.h b/include/unitlib.h index e015b95..b242d47 100644 --- a/include/unitlib.h +++ b/include/unitlib.h @@ -1,249 +1,248 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" #define UL_VERSION "0.5.1" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #define UL_API UL_LINKAGE typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; typedef enum ul_format { UL_FMT_PLAIN = 0, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, UL_NUM_FORMATS, } ul_format_t; typedef enum ul_cmpres { UL_DIFFERENT = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, UL_ERROR = 0xFF, } ul_cmpres_t; enum ul_fmtop { UL_FOP_REDUCE = 0x01, }; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** - * Deinitializes the unitlib and frees all. This function - * has to be called at the end of the program. - * internals resources. + * Deinitializes the unitlib and frees all internals resources. + * This function has to be called at the end of the program. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the full name of unitlib, including the version * @return String in the form "unitlib-x.yz" */ UL_API const char *ul_get_name(void); /** * Returns the version of unitlib * @return String in the form "x.yz" */ UL_API const char *ul_get_version(void); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Checks whether a unit is reduceable to a composed unit * @param unit The unit * @return True if the unit is reduceable, false if not or if an error occured */ UL_API bool ul_reduceable(const unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, int fops); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, int fops) { return ul_fprint(stdout, unit, format, fops); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, int fops); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option * @param fops A bitmap containing UL_FOP_* flags * @return Length of the formated string */ UL_API size_t ul_length(const unit_t *unit, ul_format_t format, int fops); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
bed6e83f6a4aace14d497816bc9a46652967ebad
Added some default conversion rules
diff --git a/etc/rules b/etc/rules new file mode 100644 index 0000000..f90054e --- /dev/null +++ b/etc/rules @@ -0,0 +1,36 @@ +# unitlib conversion rules + +# Newton +N = kg m s^-2 + +# Joule +J = N m + +# Watt +W = J s^-1 + +# Pascal +Pa = N m^-2 + +# Hertz +Hz = s^-1 + +# Volt +V = W A^-1 + +# Ohm +Omega = V A^-1 + +# Tesla +T = V s m^-2 + +# Weber +Wb = T m^2 + +# Farad +F = A s V^-1 + +# Coulomb +C = A s + +
jan-kuechler/unitlib
e7f5b549ca6f5c6e27ab7206ae00c95bcbfcb5b7
Changed version to 0.5.1
diff --git a/include/unitlib.h b/include/unitlib.h index 2076a81..e015b95 100644 --- a/include/unitlib.h +++ b/include/unitlib.h @@ -1,249 +1,249 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" -#define UL_VERSION "0.5" +#define UL_VERSION "0.5.1" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #define UL_API UL_LINKAGE typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; typedef enum ul_format { UL_FMT_PLAIN = 0, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, UL_NUM_FORMATS, } ul_format_t; typedef enum ul_cmpres { UL_DIFFERENT = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, UL_ERROR = 0xFF, } ul_cmpres_t; enum ul_fmtop { UL_FOP_REDUCE = 0x01, }; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the full name of unitlib, including the version * @return String in the form "unitlib-x.yz" */ UL_API const char *ul_get_name(void); /** * Returns the version of unitlib * @return String in the form "x.yz" */ UL_API const char *ul_get_version(void); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Checks whether a unit is reduceable to a composed unit * @param unit The unit * @return True if the unit is reduceable, false if not or if an error occured */ UL_API bool ul_reduceable(const unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, int fops); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, int fops) { return ul_fprint(stdout, unit, format, fops); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, int fops); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option * @param fops A bitmap containing UL_FOP_* flags * @return Length of the formated string */ UL_API size_t ul_length(const unit_t *unit, ul_format_t format, int fops); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
2ec78b2fbb2a64f1d298f8881d3709f58a53dd11
Auto create 'bin' directory if it does not exist.
diff --git a/Makefile b/Makefile index 02bbc1d..7112745 100644 --- a/Makefile +++ b/Makefile @@ -1,110 +1,113 @@ ## # Makefile for unitlib ## MSVC_COMPAT = -mms-bitfields -mno-cygwin BIN_DIR = bin SRC_DIR = src INC_DIR = include TST_DIR = test CC = gcc CFLAGS = -O2 -std=c99 -Wall -Wextra -I$(INC_DIR) AR = ar RANLIB = ranlib SRCFILES = $(SRC_DIR)/unitlib.c $(SRC_DIR)/parser.c $(SRC_DIR)/format.c HDRFILES = $(INC_DIR)/unitlib.h $(SRC_DIR)/intern.h $(INC_DIR)/unitlib-config.h TARGET = $(BIN_DIR)/libunit.a DLL = $(BIN_DIR)/libunit.dll IMPLIB = $(BIN_DIR)/libunit.lib HEADER = $(INC_DIR)/unitlib-config.h $(INC_DIR)/unitlib.h WIN_DLL_INSTALL = /c/Windows WIN_LIB_INSTALL = /g/Programmieren/lib WIN_HDR_INSTALL = /g/Programmieren/include PREFIX = /usr INSTALL_LIB = $(PREFIX)/lib INSTALL_HDR = $(PREFIX)/include -OBJFILES = $(INC_DIR)/unitlib.o $(INC_DIR)/parser.o $(INC_DIR)/format.o +OBJFILES = $(BIN_DIR)/unitlib.o $(BIN_DIR)/parser.o $(BIN_DIR)/format.o TESTPROG = $(TST_DIR)/test.exe SMASHPROG = $(TST_DIR)/smash.exe UNITTEST = $(TST_DIR)/ultest -.PHONY: test clean allclean +.PHONY: test clean allclean prepare all: $(TARGET) dll: $(DLL) install-dll: dll cp $(DLL) $(WIN_DLL_INSTALL) cp $(DLL) $(WIN_LIB_INSTALL) cp $(IMPLIB) $(WIN_LIB_INSTALL) cp $(HEADER) $(WIN_HDR_INSTALL) install: cp $(TARGET) $(INSTALL_LIB) cp $(HEADER) $(INSTALL_HDR) uninstall: rm $(INSTALL_LIB)/$(TARGET) cd $(INSTALL_HDR) rm $(HEADER) test: $(TESTPROG) @./$(TESTPROG) utest: $(UNITTEST) @./$(UNITTEST) smash: $(SMASHPROG) @./$(SMASHPROG) -$(TARGET): $(OBJFILES) +$(TARGET): prepare $(OBJFILES) @$(AR) rc $(TARGET) $(OBJFILES) @$(RANLIB) $(TARGET) -$(DLL): $(SRCFILES) $(HDRFILES) Makefile +$(DLL): prepare $(SRCFILES) $(HDRFILES) Makefile @$(CC) $(CFLAGS) $(MSVC_COMPAT) -shared -o $(DLL) $(SRCFILES) -Wl,--output-def,$(BIN_DIR)/libunit.def lib.exe /DEF:$(BIN_DIR)/libunit.def /OUT:$(BIN_DIR)/libunit.lib /MACHINE:X86 -$(INC_DIR)/unitlib.o: $(SRC_DIR)/unitlib.c $(HDRFILES) - @$(CC) $(CFLAGS) -o $(INC_DIR)/unitlib.o -c $(SRC_DIR)/unitlib.c +$(BIN_DIR)/unitlib.o: $(SRC_DIR)/unitlib.c $(HDRFILES) + @$(CC) $(CFLAGS) -o $(BIN_DIR)/unitlib.o -c $(SRC_DIR)/unitlib.c -$(INC_DIR)/parser.o: $(SRC_DIR)/parser.c $(HDRFILES) - @$(CC) $(CFLAGS) -o $(INC_DIR)/parser.o -c $(SRC_DIR)/parser.c +$(BIN_DIR)/parser.o: $(SRC_DIR)/parser.c $(HDRFILES) + @$(CC) $(CFLAGS) -o $(BIN_DIR)/parser.o -c $(SRC_DIR)/parser.c -$(INC_DIR)/format.o: $(SRC_DIR)/format.c $(HDRFILES) - @$(CC) $(CFLAGS) -o $(INC_DIR)/format.o -c $(SRC_DIR)/format.c +$(BIN_DIR)/format.o: $(SRC_DIR)/format.c $(HDRFILES) + @$(CC) $(CFLAGS) -o $(BIN_DIR)/format.o -c $(SRC_DIR)/format.c $(TESTPROG): $(TARGET) $(TST_DIR)/_test.c @$(CC) -o $(TESTPROG) -g -L. $(TST_DIR)/test.c -lunit $(SMASHPROG): $(TARGET) $(TST_DIR)/_test.c @$(CC) -o $(SMASHPROG) -L. -DSMASH $(TST_DIR)/test.c -lunit $(UNITTEST): $(TARGET) $(TST_DIR)/unittest.c @$(CC) -std=gnu99 -I$(INC_DIR) -o $(UNITTEST) -L$(BIN_DIR) $(TST_DIR)/unittest.c -lunit +prepare: + @if [ ! -d $(BIN_DIR) ]; then mkdir $(BIN_DIR); fi + clean: @rm -f $(OBJFILES) @rm -f $(TESTPROG) @rm -f $(SMASHPROG) @rm -f $(UNITTEST) allclean: clean @rm -f $(TARGET) @rm -f $(DLL) @rm -f $(IMPLIB) @rm -f libunit.def @rm -f libunit.exp
jan-kuechler/unitlib
736e43af99b13061e03832c131b53919d6a8aa16
Changed directory structure
diff --git a/Makefile b/Makefile index bb4b6e3..02bbc1d 100644 --- a/Makefile +++ b/Makefile @@ -1,106 +1,110 @@ ## # Makefile for unitlib ## MSVC_COMPAT = -mms-bitfields -mno-cygwin +BIN_DIR = bin +SRC_DIR = src +INC_DIR = include +TST_DIR = test + CC = gcc -CFLAGS = -O2 -std=c99 -Wall -Wextra +CFLAGS = -O2 -std=c99 -Wall -Wextra -I$(INC_DIR) AR = ar RANLIB = ranlib -TARGET = libunit.a +SRCFILES = $(SRC_DIR)/unitlib.c $(SRC_DIR)/parser.c $(SRC_DIR)/format.c +HDRFILES = $(INC_DIR)/unitlib.h $(SRC_DIR)/intern.h $(INC_DIR)/unitlib-config.h -DLL = libunit.dll -IMPLIB = libunit.lib +TARGET = $(BIN_DIR)/libunit.a -HEADER = unitlib-config.h unitlib.h +DLL = $(BIN_DIR)/libunit.dll +IMPLIB = $(BIN_DIR)/libunit.lib -SRCFILES = unitlib.c parser.c format.c -HDRFILES = unitlib.h intern.h unitlib-config.h +HEADER = $(INC_DIR)/unitlib-config.h $(INC_DIR)/unitlib.h WIN_DLL_INSTALL = /c/Windows WIN_LIB_INSTALL = /g/Programmieren/lib WIN_HDR_INSTALL = /g/Programmieren/include PREFIX = /usr INSTALL_LIB = $(PREFIX)/lib INSTALL_HDR = $(PREFIX)/include -OBJFILES = unitlib.o parser.o format.o +OBJFILES = $(INC_DIR)/unitlib.o $(INC_DIR)/parser.o $(INC_DIR)/format.o -TESTPROG = _test.exe -SMASHPROG = _smash.exe +TESTPROG = $(TST_DIR)/test.exe +SMASHPROG = $(TST_DIR)/smash.exe -UNITTEST = ultest +UNITTEST = $(TST_DIR)/ultest .PHONY: test clean allclean all: $(TARGET) dll: $(DLL) install-dll: dll cp $(DLL) $(WIN_DLL_INSTALL) cp $(DLL) $(WIN_LIB_INSTALL) cp $(IMPLIB) $(WIN_LIB_INSTALL) cp $(HEADER) $(WIN_HDR_INSTALL) - + install: cp $(TARGET) $(INSTALL_LIB) cp $(HEADER) $(INSTALL_HDR) - + uninstall: rm $(INSTALL_LIB)/$(TARGET) cd $(INSTALL_HDR) rm $(HEADER) - + test: $(TESTPROG) @./$(TESTPROG) - + utest: $(UNITTEST) @./$(UNITTEST) - + smash: $(SMASHPROG) @./$(SMASHPROG) - + $(TARGET): $(OBJFILES) @$(AR) rc $(TARGET) $(OBJFILES) @$(RANLIB) $(TARGET) - + $(DLL): $(SRCFILES) $(HDRFILES) Makefile - @$(CC) $(CFLAGS) $(MSVC_COMPAT) -shared -o $(DLL) $(SRCFILES) -Wl,--output-def,libunit.def - lib.exe /DEF:libunit.def /OUT:libunit.lib /MACHINE:X86 - -unitlib.o: unitlib.c $(HDRFILES) - @$(CC) $(CFLAGS) -o unitlib.o -c unitlib.c - -parser.o: parser.c $(HDRFILES) - @$(CC) $(CFLAGS) -o parser.o -c parser.c - -format.o: format.c $(HDRFILES) - @$(CC) $(CFLAGS) -o format.o -c format.c - -$(TESTPROG): $(TARGET) _test.c - @$(CC) -o $(TESTPROG) -g -L. _test.c -lunit - -$(SMASHPROG): $(TARGET) _test.c - @$(CC) -o $(SMASHPROG) -L. -DSMASH _test.c -lunit - -$(UNITTEST): $(TARGET) unittest.c - @$(CC) -std=gnu99 -o $(UNITTEST) -L. unittest.c -lunit - + @$(CC) $(CFLAGS) $(MSVC_COMPAT) -shared -o $(DLL) $(SRCFILES) -Wl,--output-def,$(BIN_DIR)/libunit.def + lib.exe /DEF:$(BIN_DIR)/libunit.def /OUT:$(BIN_DIR)/libunit.lib /MACHINE:X86 + +$(INC_DIR)/unitlib.o: $(SRC_DIR)/unitlib.c $(HDRFILES) + @$(CC) $(CFLAGS) -o $(INC_DIR)/unitlib.o -c $(SRC_DIR)/unitlib.c + +$(INC_DIR)/parser.o: $(SRC_DIR)/parser.c $(HDRFILES) + @$(CC) $(CFLAGS) -o $(INC_DIR)/parser.o -c $(SRC_DIR)/parser.c + +$(INC_DIR)/format.o: $(SRC_DIR)/format.c $(HDRFILES) + @$(CC) $(CFLAGS) -o $(INC_DIR)/format.o -c $(SRC_DIR)/format.c + +$(TESTPROG): $(TARGET) $(TST_DIR)/_test.c + @$(CC) -o $(TESTPROG) -g -L. $(TST_DIR)/test.c -lunit + +$(SMASHPROG): $(TARGET) $(TST_DIR)/_test.c + @$(CC) -o $(SMASHPROG) -L. -DSMASH $(TST_DIR)/test.c -lunit + +$(UNITTEST): $(TARGET) $(TST_DIR)/unittest.c + @$(CC) -std=gnu99 -I$(INC_DIR) -o $(UNITTEST) -L$(BIN_DIR) $(TST_DIR)/unittest.c -lunit + clean: @rm -f $(OBJFILES) @rm -f $(TESTPROG) @rm -f $(SMASHPROG) @rm -f $(UNITTEST) - @rm -f debug.log - + allclean: clean @rm -f $(TARGET) @rm -f $(DLL) @rm -f $(IMPLIB) @rm -f libunit.def @rm -f libunit.exp diff --git a/README b/README index 1817481..7275120 100644 --- a/README +++ b/README @@ -1,50 +1,49 @@ unitlib - README + What is unitlib? Unitlib is a programming library written in C, that handles parsing, converting and formatting of SI units (http://en.wikipedia.org/wiki/SI). + Is there any documentation? Not yet, but you may look at the unitlib.h header where each function has a short description. + Features of unitlib * Parsing of complex unit definitions like "5 kg mm / 16 ns^2". * Extensible rule system to create new units (e.g. Newton: "N = kg m s^-2"). * Support for most of the SI prefixes, like nano, kilo, etc. * Output in three different forms: Plain text, LaTeX inline defintion and LaTeX fracs. * Output as a composed unit, e.g. "5 kg m / s^2" can be printed as "5 N". + Planed features - * Parsing support for something like "N sqrt(m^2/s^2) * (A/s)^2". * Find best composed unit for unclear matches ("kg m^2 s^-2" -> "N m"). + What programs are using unitlib? At the moment unitlib is used by two programs: * slas2 for Mac OS X (http://sourceforge.net/projects/slas2/) * EinheitenRechner for Windows (http://github.com/borlox/EinheitenRechner/) + Author At the moment unitlib is developed by Jan Kuechler. Email: kuchen_ <at> gmx <dot> de (yep, that's an underscore right after 'kuchen'). + License At the moment unitlib has no license, so effectivly that says "all rights reserved". It's planned to release the library under an open source license at some point, for the meantime just send me an email. For any further questions, ideas, or anything else (except spam (-;), please send me an email. diff --git a/etc/gramma.txt b/etc/gramma.txt new file mode 100644 index 0000000..0245e4f --- /dev/null +++ b/etc/gramma.txt @@ -0,0 +1,21 @@ +Definiton = (Name) '=' (Expr) + +Expr = (Part) { ('*' | '/') (Part) } ; + +Part = ( (Function) | (Factor) | (Unit) | '(' Expr ')' [(Exponent)]); + +Function = (Name) '(' (Expr) ')'; + +Factor = ['+'|'-'] (Float); + +Unit = (Name) [(Exponent)]; + +Exponent = '^' (Int); + +Float = ['+' | '-'] (Int) ['.' (Int)]; + +Int = (Number) { (Number) }; + +Number = '0' - '9'; + +Name = ('a' - 'Z') { ('a' - 'Z') }; diff --git a/unitlib-config.h b/include/unitlib-config.h similarity index 100% rename from unitlib-config.h rename to include/unitlib-config.h diff --git a/unitlib.h b/include/unitlib.h similarity index 100% rename from unitlib.h rename to include/unitlib.h diff --git a/format.c b/src/format.c similarity index 100% rename from format.c rename to src/format.c diff --git a/intern.h b/src/intern.h similarity index 100% rename from intern.h rename to src/intern.h diff --git a/parser.c b/src/parser.c similarity index 100% rename from parser.c rename to src/parser.c diff --git a/unitlib.c b/src/unitlib.c similarity index 100% rename from unitlib.c rename to src/unitlib.c diff --git a/_test.c b/test/test.c similarity index 100% rename from _test.c rename to test/test.c diff --git a/test/ultest.exe b/test/ultest.exe new file mode 100644 index 0000000..286aa90 Binary files /dev/null and b/test/ultest.exe differ diff --git a/unittest.c b/test/unittest.c similarity index 98% rename from unittest.c rename to test/unittest.c index d0a521b..74bb358 100644 --- a/unittest.c +++ b/test/unittest.c @@ -1,646 +1,656 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> +#include <float.h> +#include <math.h> #include "unitlib.h" -#include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS +static inline int ncmp(ul_number a, ul_number b) +{ + if (_fabsn(a-b) < N_EPSILON) + return 0; + if (a < b) + return -1; + return 1; +} + static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) AUTO_FAIL printf("[%s-%d-%d] The test '%s' failed: \n[%s-%d-%d] Error message: %s\n", Suite, Test, Check, Expr, Suite, Test, Check, ul_error()); END_AUTO_FAIL TEST_SUITE(parser) GROUP("base") TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() GROUP("validation") TEST unit_t u; const char *strings[] = { "5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! "sqrt kg^2)", // missing ( after sqrt "( kg^2 m", // missing ) "((((((((((((((((((((((((((((((((((((((((((((((((", NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST TEST static char prefs[] = "YZEPTGMkh dcmunpfazy"; static ul_number factors[] = { 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1, 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, }; size_t num_prefs = strlen(prefs); FATAL((sizeof(factors) / sizeof(factors[0])) != num_prefs); for (size_t i = 0; i < num_prefs; ++i) { char expr[128] = ""; snprintf(expr, 128, "5 %cm", prefs[i]); unit_t u; CHECK(ul_parse(expr, &u)); FAIL_MSG("Failed to parse: '%s' (%s)", expr, ul_error()); CHECK(ncmp(ul_factor(&u), 5 * factors[i]) == 0); FAIL_MSG("Factor: %g instead of %g (%c)", ul_factor(&u), 5 * factors[i], prefs[i]); // check kilogram, the only base unit with a prefix snprintf(expr, 128, "%cg", prefs[i]); CHECK(ul_parse(expr, &u)); } END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -1); unit_t test; CHECK(ul_parse("kg / s", &test)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&test, &correct)); correct.factor = 2.0; CHECK(ul_parse("8 kg / 4 s", &test)); CHECK(ul_equal(&test, &correct)); END_TEST GROUP("extended") TEST unit_t kg = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t u; CHECK(ul_parse("sqrt(4 kg^2)", &u)); CHECK(ul_equal(&u, &kg)); char buffer[128]; ul_snprint(buffer, 128, &u, UL_FMT_PLAIN, 0); FAIL_MSG("Result was: %s", buffer); END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_METER, -1, U_KILOGRAM, 2); unit_t u; CHECK(ul_parse("sqrt(kg^2/m^2) kg", &u)); CHECK(ul_equal(&u, &correct)); END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_METER, 2, U_SECOND, 2); unit_t u; CHECK(ul_parse("(m s)^2", &u)); CHECK(ul_equal(&u, &correct)); END_TEST TEST unit_t u; CHECK(ul_parse("kg*m^2/(s^4 kg) sqrt(A^2 K^4)", &u)); END_TEST END_GROUP() END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t one_kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t five_kg = MAKE_UNIT(5.0, U_KILOGRAM, 1); CHECK(!ul_equal(&one_kg, &five_kg)); CHECK(ul_cmp(&one_kg, &five_kg) == UL_SAME_UNIT); unit_t five_sec = MAKE_UNIT(5.0, U_SECOND, 1); CHECK(ul_cmp(&five_kg, &five_sec) == UL_SAME_FACTOR); CHECK(ul_cmp(&one_kg, &five_sec) == UL_DIFFERENT); CHECK(ul_cmp(NULL, &one_kg) == UL_ERROR); CHECK(ul_cmp(&one_kg, NULL) == UL_ERROR); CHECK(ul_cmp(NULL, NULL) == UL_ERROR); /* UL_EQUAL result is tested by the previous test */ END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST TEST unit_t test = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, 5.0)); CHECK(ul_factor(&test) == 5.0); CHECK(ul_mult(&test, 1/5.0)); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, -1)); CHECK(ul_factor(&test) == -1.0); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_INLINE, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_FRAC, 0) == strlen(buffer)); FAIL_MSG("ul_length: %zu", ul_length(&N, UL_FMT_LATEX_FRAC, 0)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() TEST_SUITE(reduce) TEST CHECK(ul_parse_rule("N = 1 kg m s^-2")); unit_t N = MAKE_UNIT(1, U_KILOGRAM, 1, U_METER, 1, U_SECOND, -2); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "1 N") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); END_TEST END_TEST_SUITE() int main(void) { ul_debugging(true); - ul_debugout("utest-debug.log", false); + ul_debugout("test/utest-debug.log", false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); USE_AUTO_FAIL(); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); RUN_SUITE(reduce); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define FATAL(expr) \ do { \ if (expr) { \ PRINT(_o, L_RESULT, "[%s%s-%d] Fatal: %s\n", _name, _group_name, _id, #expr); \ exit(1); \ } \ } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s%s-%d-%d] (%d) Fail: '%s'\n", _name, _group_name, _id, _this, __LINE__, #expr); \ _last = false;\ if (_o->autofail) _o->autofail(_name, _id, _this, #expr); \ } \ else { \ PRINT(_o, L_VERBOSE, "[%s%s-%d-%d] Pass: '%s'\n", _name, _group_name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define AUTO_FAIL \ static inline void _auto_fail(const char *Suite, int Test, int Check, const char *Expr) { #define END_AUTO_FAIL \ } #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ const char *_group_name = ""; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } #define GROUP(name) \ do { const char *_group_name = "-" name; int _test_id = 0; #define END_GROUP() \ } while (0); #define SKIP_GROUP() PRINT(_o, L_NORMAL, "[%s%s] skipped.\n", _name, _group_name); break; // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s%s-%d] failed with %d error%s.\n", _name, _group_name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s%s-%d] passed.\n", _name, _group_name, _id); \ } \ } // OTHER typedef struct { int loglvl; void (*autofail)(const char*,int,int,const char*); } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops = {L_RESULT,NULL}; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define USE_AUTO_FAIL() \ _ops.autofail = _auto_fail; #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/ diff --git a/test/utest-debug.log b/test/utest-debug.log new file mode 100644 index 0000000..031e1b1 --- /dev/null +++ b/test/utest-debug.log @@ -0,0 +1,1036 @@ +** unitlib - debug log ** +[ul_init] Initializing unitlib.... +[_ul_init_parser] Initializing parser +[_ul_init_parser] Base rule: 0 +[_ul_init_parser] Base rule: 1 +[_ul_init_parser] Base rule: 2 +[_ul_init_parser] Base rule: 3 +[_ul_init_parser] Base rule: 4 +[_ul_init_parser] Base rule: 5 +[_ul_init_parser] Base rule: 6 +[_ul_init_parser] Base rule: 7 +[_ul_init_parser] Base rules initialized +[init_prefixes] Initializing prefixes +[init_prefixes] Prefixes initialized! +[_ul_init_parser] Parser initalized! +[ul_init] Init done! +[ul_parse] Parse unit: 'm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is 'm' +[handle_special] handle_special(m) +[handle_special] not special! +[handle_unit] Parse item: 'm' +[ul_parse] Parse unit: ' + kg^2 * m ' +[ul_parse] Start: 3 +[ul_parse] End: 7 +[ul_parse] Item is 'kg^2' +[handle_special] handle_special(kg^2) +[handle_special] not special! +[handle_unit] Parse item: 'kg^2' +[ul_parse] Start: 8 +[ul_parse] End: 8 +[ul_parse] Item is '*' +[handle_special] handle_special(*) +[ul_parse] Start: 10 +[ul_parse] End: 11 +[ul_parse] Item is 'm' +[handle_special] handle_special(m) +[handle_special] not special! +[handle_unit] Parse item: 'm' +[ul_parse] Start: 13 +[ul_parse] End: 13 +[ul_parse] Parse unit: '2 Cd 7 s^-1' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '2' +[handle_special] handle_special(2) +[handle_special] not special! +[handle_factor] '2' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'Cd' +[handle_special] handle_special(Cd) +[handle_special] not special! +[handle_unit] Parse item: 'Cd' +[ul_parse] Start: 5 +[ul_parse] End: 6 +[ul_parse] Item is '7' +[handle_special] handle_special(7) +[handle_special] not special! +[handle_factor] '7' is a factor +[ul_parse] Start: 7 +[ul_parse] End: 11 +[ul_parse] Item is 's^-1' +[handle_special] handle_special(s^-1) +[handle_special] not special! +[handle_unit] Parse item: 's^-1' +[ul_parse] Parse unit: '' +[ul_parse] Start: 0 +[ul_parse] End: 0 +[ul_parse] Parse unit: '5 ** kg^2' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 2 +[ul_parse] Item is '*' +[handle_special] handle_special(*) +[ul_parse] Start: 3 +[ul_parse] End: 3 +[ul_parse] Item is '*' +[handle_special] handle_special(*) +[ul_parse] Parse unit: '5! * kg^2' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is '5!' +[handle_special] handle_special(5!) +[handle_special] not special! +[handle_unit] Parse item: '5!' +[unit_and_prefix] Got prefix: 5 +[ul_parse] Parse unit: '5 * kg^2!' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 2 +[ul_parse] Item is '*' +[handle_special] handle_special(*) +[ul_parse] Start: 4 +[ul_parse] End: 9 +[ul_parse] Item is 'kg^2!' +[handle_special] handle_special(kg^2!) +[handle_special] not special! +[handle_unit] Parse item: 'kg^2!' +[ul_parse] Parse unit: 'sqrt kg^2)' +[ul_parse] Start: 0 +[ul_parse] End: 4 +[ul_parse] Item is 'sqrt' +[handle_special] handle_special(sqrt) +[handle_special] Found sqrt +[ul_parse] Start: 5 +[ul_parse] End: 9 +[ul_parse] Item is 'kg^2' +[handle_special] handle_special(kg^2) +[ul_parse] Parse unit: '( kg^2 m' +[ul_parse] Start: 0 +[ul_parse] End: 0 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 0 -> 1 +[ul_parse] Start: 2 +[ul_parse] End: 6 +[ul_parse] Item is 'kg^2' +[handle_special] handle_special(kg^2) +[handle_special] not special! +[handle_unit] Parse item: 'kg^2' +[ul_parse] Start: 7 +[ul_parse] End: 8 +[ul_parse] Item is 'm' +[handle_special] handle_special(m) +[handle_special] not special! +[handle_unit] Parse item: 'm' +[ul_parse] Parse unit: '((((((((((((((((((((((((((((((((((((((((((((((((' +[ul_parse] Start: 0 +[ul_parse] End: 0 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 0 -> 1 +[ul_parse] Start: 1 +[ul_parse] End: 1 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 1 -> 2 +[ul_parse] Start: 2 +[ul_parse] End: 2 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 2 -> 3 +[ul_parse] Start: 3 +[ul_parse] End: 3 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 3 -> 4 +[ul_parse] Start: 4 +[ul_parse] End: 4 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 4 -> 5 +[ul_parse] Start: 5 +[ul_parse] End: 5 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 5 -> 6 +[ul_parse] Start: 6 +[ul_parse] End: 6 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 6 -> 7 +[ul_parse] Start: 7 +[ul_parse] End: 7 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 7 -> 8 +[ul_parse] Start: 8 +[ul_parse] End: 8 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 8 -> 9 +[ul_parse] Start: 9 +[ul_parse] End: 9 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 9 -> 10 +[ul_parse] Start: 10 +[ul_parse] End: 10 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 10 -> 11 +[ul_parse] Start: 11 +[ul_parse] End: 11 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 11 -> 12 +[ul_parse] Start: 12 +[ul_parse] End: 12 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 12 -> 13 +[ul_parse] Start: 13 +[ul_parse] End: 13 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 13 -> 14 +[ul_parse] Start: 14 +[ul_parse] End: 14 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 14 -> 15 +[ul_parse] Start: 15 +[ul_parse] End: 15 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 15 -> 16 +[ul_parse_rule] Parsing rule '' +[ul_parse_rule] Parsing rule ' =' +[ul_parse_rule] Split at 1 +[ul_parse_rule] Parsing rule '16 = 16' +[ul_parse_rule] Split at 3 +[get_symbol] Allocate 3 bytes +[get_symbol] Symbol is '16' +[ul_parse_rule] Parsing rule ' a b = s ' +[ul_parse_rule] Split at 5 +[ul_parse_rule] Parsing rule ' c == kg' +[ul_parse_rule] Split at 3 +[get_symbol] Allocate 2 bytes +[get_symbol] Symbol is 'c' +[ul_parse_rule] Rest definition is '= kg' +[ul_parse] Parse unit: '= kg' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '=' +[handle_special] handle_special(=) +[handle_special] not special! +[handle_unit] Parse item: '=' +[unit_and_prefix] Got prefix: = +[ul_parse_rule] Parsing rule 'd = e' +[ul_parse_rule] Split at 2 +[get_symbol] Allocate 2 bytes +[get_symbol] Symbol is 'd' +[ul_parse_rule] Rest definition is ' e' +[ul_parse] Parse unit: ' e' +[ul_parse] Start: 1 +[ul_parse] End: 2 +[ul_parse] Item is 'e' +[handle_special] handle_special(e) +[handle_special] not special! +[handle_unit] Parse item: 'e' +[unit_and_prefix] Got prefix: e +[ul_parse_rule] Parsing rule ' = kg' +[ul_parse_rule] Split at 1 +[ul_parse_rule] Parsing rule '' +[ul_parse_rule] Parsing rule 'EmptySymbol = ' +[ul_parse_rule] Split at 12 +[get_symbol] Allocate 12 bytes +[get_symbol] Symbol is 'EmptySymbol' +[ul_parse_rule] Rest definition is ' ' +[ul_parse] Parse unit: ' ' +[ul_parse] Start: 1 +[ul_parse] End: 1 +[ul_parse] Parse unit: 'EmptySymbol' +[ul_parse] Start: 0 +[ul_parse] End: 11 +[ul_parse] Item is 'EmptySymbol' +[handle_special] handle_special(EmptySymbol) +[handle_special] not special! +[handle_unit] Parse item: 'EmptySymbol' +[ul_parse_rule] Parsing rule '!ForcedRule = kg' +[ul_parse_rule] Split at 12 +[get_symbol] Forced rule. +[get_symbol] Allocate 11 bytes +[get_symbol] Symbol is 'ForcedRule' +[ul_parse_rule] Rest definition is ' kg' +[ul_parse] Parse unit: ' kg' +[ul_parse] Start: 1 +[ul_parse] End: 3 +[ul_parse] Item is 'kg' +[handle_special] handle_special(kg) +[handle_special] not special! +[handle_unit] Parse item: 'kg' +[ul_parse] Parse unit: 'ForcedRule' +[ul_parse] Start: 0 +[ul_parse] End: 10 +[ul_parse] Item is 'ForcedRule' +[handle_special] handle_special(ForcedRule) +[handle_special] not special! +[handle_unit] Parse item: 'ForcedRule' +[ul_parse_rule] Parsing rule 'NewRule = kg' +[ul_parse_rule] Split at 8 +[get_symbol] Allocate 8 bytes +[get_symbol] Symbol is 'NewRule' +[ul_parse_rule] Rest definition is ' kg' +[ul_parse] Parse unit: ' kg' +[ul_parse] Start: 1 +[ul_parse] End: 3 +[ul_parse] Item is 'kg' +[handle_special] handle_special(kg) +[handle_special] not special! +[handle_unit] Parse item: 'kg' +[ul_parse] Parse unit: 'NewRule' +[ul_parse] Start: 0 +[ul_parse] End: 7 +[ul_parse] Item is 'NewRule' +[handle_special] handle_special(NewRule) +[handle_special] not special! +[handle_unit] Parse item: 'NewRule' +[ul_parse_rule] Parsing rule '!NewRule = s' +[ul_parse_rule] Split at 9 +[get_symbol] Forced rule. +[get_symbol] Allocate 8 bytes +[get_symbol] Symbol is 'NewRule' +[ul_parse_rule] Rest definition is ' s' +[ul_parse] Parse unit: ' s' +[ul_parse] Start: 1 +[ul_parse] End: 2 +[ul_parse] Item is 's' +[handle_special] handle_special(s) +[handle_special] not special! +[handle_unit] Parse item: 's' +[ul_parse] Parse unit: 'NewRule' +[ul_parse] Start: 0 +[ul_parse] End: 7 +[ul_parse] Item is 'NewRule' +[handle_special] handle_special(NewRule) +[handle_special] not special! +[handle_unit] Parse item: 'NewRule' +[ul_parse_rule] Parsing rule '!NewRule = m' +[ul_parse_rule] Split at 9 +[get_symbol] Forced rule. +[get_symbol] Allocate 8 bytes +[get_symbol] Symbol is 'NewRule' +[ul_parse_rule] Parsing rule '!kg = kg' +[ul_parse_rule] Split at 4 +[get_symbol] Forced rule. +[get_symbol] Allocate 3 bytes +[get_symbol] Symbol is 'kg' +[ul_parse_rule] Parsing rule ' Recurse = m' +[ul_parse_rule] Split at 9 +[get_symbol] Allocate 8 bytes +[get_symbol] Symbol is 'Recurse' +[ul_parse_rule] Rest definition is ' m' +[ul_parse] Parse unit: ' m' +[ul_parse] Start: 1 +[ul_parse] End: 2 +[ul_parse] Item is 'm' +[handle_special] handle_special(m) +[handle_special] not special! +[handle_unit] Parse item: 'm' +[ul_parse_rule] Parsing rule '!Recurse = Recurse' +[ul_parse_rule] Split at 9 +[get_symbol] Forced rule. +[get_symbol] Allocate 8 bytes +[get_symbol] Symbol is 'Recurse' +[ul_parse_rule] Rest definition is ' Recurse' +[ul_parse] Parse unit: ' Recurse' +[ul_parse] Start: 1 +[ul_parse] End: 8 +[ul_parse] Item is 'Recurse' +[handle_special] handle_special(Recurse) +[handle_special] not special! +[handle_unit] Parse item: 'Recurse' +[unit_and_prefix] Got prefix: R +[ul_parse] Parse unit: '5 Ym' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'Ym' +[handle_special] handle_special(Ym) +[handle_special] not special! +[handle_unit] Parse item: 'Ym' +[unit_and_prefix] Got prefix: Y +[ul_parse] Parse unit: 'Yg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'Yg' +[handle_special] handle_special(Yg) +[handle_special] not special! +[handle_unit] Parse item: 'Yg' +[unit_and_prefix] Got prefix: Y +[ul_parse] Parse unit: '5 Zm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'Zm' +[handle_special] handle_special(Zm) +[handle_special] not special! +[handle_unit] Parse item: 'Zm' +[unit_and_prefix] Got prefix: Z +[ul_parse] Parse unit: 'Zg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'Zg' +[handle_special] handle_special(Zg) +[handle_special] not special! +[handle_unit] Parse item: 'Zg' +[unit_and_prefix] Got prefix: Z +[ul_parse] Parse unit: '5 Em' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'Em' +[handle_special] handle_special(Em) +[handle_special] not special! +[handle_unit] Parse item: 'Em' +[unit_and_prefix] Got prefix: E +[ul_parse] Parse unit: 'Eg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'Eg' +[handle_special] handle_special(Eg) +[handle_special] not special! +[handle_unit] Parse item: 'Eg' +[unit_and_prefix] Got prefix: E +[ul_parse] Parse unit: '5 Pm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'Pm' +[handle_special] handle_special(Pm) +[handle_special] not special! +[handle_unit] Parse item: 'Pm' +[unit_and_prefix] Got prefix: P +[ul_parse] Parse unit: 'Pg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'Pg' +[handle_special] handle_special(Pg) +[handle_special] not special! +[handle_unit] Parse item: 'Pg' +[unit_and_prefix] Got prefix: P +[ul_parse] Parse unit: '5 Tm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'Tm' +[handle_special] handle_special(Tm) +[handle_special] not special! +[handle_unit] Parse item: 'Tm' +[unit_and_prefix] Got prefix: T +[ul_parse] Parse unit: 'Tg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'Tg' +[handle_special] handle_special(Tg) +[handle_special] not special! +[handle_unit] Parse item: 'Tg' +[unit_and_prefix] Got prefix: T +[ul_parse] Parse unit: '5 Gm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'Gm' +[handle_special] handle_special(Gm) +[handle_special] not special! +[handle_unit] Parse item: 'Gm' +[unit_and_prefix] Got prefix: G +[ul_parse] Parse unit: 'Gg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'Gg' +[handle_special] handle_special(Gg) +[handle_special] not special! +[handle_unit] Parse item: 'Gg' +[unit_and_prefix] Got prefix: G +[ul_parse] Parse unit: '5 Mm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'Mm' +[handle_special] handle_special(Mm) +[handle_special] not special! +[handle_unit] Parse item: 'Mm' +[unit_and_prefix] Got prefix: M +[ul_parse] Parse unit: 'Mg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'Mg' +[handle_special] handle_special(Mg) +[handle_special] not special! +[handle_unit] Parse item: 'Mg' +[unit_and_prefix] Got prefix: M +[ul_parse] Parse unit: '5 km' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'km' +[handle_special] handle_special(km) +[handle_special] not special! +[handle_unit] Parse item: 'km' +[unit_and_prefix] Got prefix: k +[ul_parse] Parse unit: 'kg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'kg' +[handle_special] handle_special(kg) +[handle_special] not special! +[handle_unit] Parse item: 'kg' +[ul_parse] Parse unit: '5 hm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'hm' +[handle_special] handle_special(hm) +[handle_special] not special! +[handle_unit] Parse item: 'hm' +[unit_and_prefix] Got prefix: h +[ul_parse] Parse unit: 'hg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'hg' +[handle_special] handle_special(hg) +[handle_special] not special! +[handle_unit] Parse item: 'hg' +[unit_and_prefix] Got prefix: h +[ul_parse] Parse unit: '5 m' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 3 +[ul_parse] End: 4 +[ul_parse] Item is 'm' +[handle_special] handle_special(m) +[handle_special] not special! +[handle_unit] Parse item: 'm' +[ul_parse] Parse unit: ' g' +[ul_parse] Start: 1 +[ul_parse] End: 2 +[ul_parse] Item is 'g' +[handle_special] handle_special(g) +[handle_special] not special! +[handle_unit] Parse item: 'g' +[ul_parse] Parse unit: '5 dm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'dm' +[handle_special] handle_special(dm) +[handle_special] not special! +[handle_unit] Parse item: 'dm' +[unit_and_prefix] Got prefix: d +[ul_parse] Parse unit: 'dg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'dg' +[handle_special] handle_special(dg) +[handle_special] not special! +[handle_unit] Parse item: 'dg' +[unit_and_prefix] Got prefix: d +[ul_parse] Parse unit: '5 cm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'cm' +[handle_special] handle_special(cm) +[handle_special] not special! +[handle_unit] Parse item: 'cm' +[unit_and_prefix] Got prefix: c +[ul_parse] Parse unit: 'cg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'cg' +[handle_special] handle_special(cg) +[handle_special] not special! +[handle_unit] Parse item: 'cg' +[unit_and_prefix] Got prefix: c +[ul_parse] Parse unit: '5 mm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'mm' +[handle_special] handle_special(mm) +[handle_special] not special! +[handle_unit] Parse item: 'mm' +[unit_and_prefix] Got prefix: m +[ul_parse] Parse unit: 'mg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'mg' +[handle_special] handle_special(mg) +[handle_special] not special! +[handle_unit] Parse item: 'mg' +[unit_and_prefix] Got prefix: m +[ul_parse] Parse unit: '5 um' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'um' +[handle_special] handle_special(um) +[handle_special] not special! +[handle_unit] Parse item: 'um' +[unit_and_prefix] Got prefix: u +[ul_parse] Parse unit: 'ug' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'ug' +[handle_special] handle_special(ug) +[handle_special] not special! +[handle_unit] Parse item: 'ug' +[unit_and_prefix] Got prefix: u +[ul_parse] Parse unit: '5 nm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'nm' +[handle_special] handle_special(nm) +[handle_special] not special! +[handle_unit] Parse item: 'nm' +[unit_and_prefix] Got prefix: n +[ul_parse] Parse unit: 'ng' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'ng' +[handle_special] handle_special(ng) +[handle_special] not special! +[handle_unit] Parse item: 'ng' +[unit_and_prefix] Got prefix: n +[ul_parse] Parse unit: '5 pm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'pm' +[handle_special] handle_special(pm) +[handle_special] not special! +[handle_unit] Parse item: 'pm' +[unit_and_prefix] Got prefix: p +[ul_parse] Parse unit: 'pg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'pg' +[handle_special] handle_special(pg) +[handle_special] not special! +[handle_unit] Parse item: 'pg' +[unit_and_prefix] Got prefix: p +[ul_parse] Parse unit: '5 fm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'fm' +[handle_special] handle_special(fm) +[handle_special] not special! +[handle_unit] Parse item: 'fm' +[unit_and_prefix] Got prefix: f +[ul_parse] Parse unit: 'fg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'fg' +[handle_special] handle_special(fg) +[handle_special] not special! +[handle_unit] Parse item: 'fg' +[unit_and_prefix] Got prefix: f +[ul_parse] Parse unit: '5 am' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'am' +[handle_special] handle_special(am) +[handle_special] not special! +[handle_unit] Parse item: 'am' +[unit_and_prefix] Got prefix: a +[ul_parse] Parse unit: 'ag' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'ag' +[handle_special] handle_special(ag) +[handle_special] not special! +[handle_unit] Parse item: 'ag' +[unit_and_prefix] Got prefix: a +[ul_parse] Parse unit: '5 zm' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'zm' +[handle_special] handle_special(zm) +[handle_special] not special! +[handle_unit] Parse item: 'zm' +[unit_and_prefix] Got prefix: z +[ul_parse] Parse unit: 'zg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'zg' +[handle_special] handle_special(zg) +[handle_special] not special! +[handle_unit] Parse item: 'zg' +[unit_and_prefix] Got prefix: z +[ul_parse] Parse unit: '5 ym' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '5' +[handle_special] handle_special(5) +[handle_special] not special! +[handle_factor] '5' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'ym' +[handle_special] handle_special(ym) +[handle_special] not special! +[handle_unit] Parse item: 'ym' +[unit_and_prefix] Got prefix: y +[ul_parse] Parse unit: 'yg' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'yg' +[handle_special] handle_special(yg) +[handle_special] not special! +[handle_unit] Parse item: 'yg' +[unit_and_prefix] Got prefix: y +[ul_parse] Parse unit: 'kg / s' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'kg' +[handle_special] handle_special(kg) +[handle_special] not special! +[handle_unit] Parse item: 'kg' +[ul_parse] Start: 3 +[ul_parse] End: 3 +[ul_parse] Item is '/' +[handle_special] handle_special(/) +[ul_parse] Start: 5 +[ul_parse] End: 6 +[ul_parse] Item is 's' +[handle_special] handle_special(s) +[handle_special] not special! +[handle_unit] Parse item: 's' +[ul_parse] Parse unit: '8 kg / 4 s' +[ul_parse] Start: 0 +[ul_parse] End: 1 +[ul_parse] Item is '8' +[handle_special] handle_special(8) +[handle_special] not special! +[handle_factor] '8' is a factor +[ul_parse] Start: 2 +[ul_parse] End: 4 +[ul_parse] Item is 'kg' +[handle_special] handle_special(kg) +[handle_special] not special! +[handle_unit] Parse item: 'kg' +[ul_parse] Start: 5 +[ul_parse] End: 5 +[ul_parse] Item is '/' +[handle_special] handle_special(/) +[ul_parse] Start: 7 +[ul_parse] End: 8 +[ul_parse] Item is '4' +[handle_special] handle_special(4) +[handle_special] not special! +[handle_factor] '4' is a factor +[ul_parse] Start: 9 +[ul_parse] End: 10 +[ul_parse] Item is 's' +[handle_special] handle_special(s) +[handle_special] not special! +[handle_unit] Parse item: 's' +[ul_parse] Parse unit: 'sqrt(4 kg^2)' +[ul_parse] Start: 0 +[ul_parse] End: 4 +[ul_parse] Item is 'sqrt' +[handle_special] handle_special(sqrt) +[handle_special] Found sqrt +[ul_parse] Start: 4 +[ul_parse] End: 4 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 0 -> 1 +[ul_parse] Start: 5 +[ul_parse] End: 6 +[ul_parse] Item is '4' +[handle_special] handle_special(4) +[handle_special] not special! +[handle_factor] '4' is a factor +[ul_parse] Start: 7 +[ul_parse] End: 11 +[ul_parse] Item is 'kg^2' +[handle_special] handle_special(kg^2) +[handle_special] not special! +[handle_unit] Parse item: 'kg^2' +[ul_parse] Start: 11 +[ul_parse] End: 11 +[ul_parse] Item is ')' +[handle_special] handle_special()) +[ul_parse] Parse unit: 'sqrt(kg^2/m^2) kg' +[ul_parse] Start: 0 +[ul_parse] End: 4 +[ul_parse] Item is 'sqrt' +[handle_special] handle_special(sqrt) +[handle_special] Found sqrt +[ul_parse] Start: 4 +[ul_parse] End: 4 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 0 -> 1 +[ul_parse] Start: 5 +[ul_parse] End: 9 +[ul_parse] Item is 'kg^2' +[handle_special] handle_special(kg^2) +[handle_special] not special! +[handle_unit] Parse item: 'kg^2' +[ul_parse] Start: 9 +[ul_parse] End: 9 +[ul_parse] Item is '/' +[handle_special] handle_special(/) +[ul_parse] Start: 10 +[ul_parse] End: 13 +[ul_parse] Item is 'm^2' +[handle_special] handle_special(m^2) +[handle_special] not special! +[handle_unit] Parse item: 'm^2' +[ul_parse] Start: 13 +[ul_parse] End: 13 +[ul_parse] Item is ')' +[handle_special] handle_special()) +[ul_parse] Start: 15 +[ul_parse] End: 17 +[ul_parse] Item is 'kg' +[handle_special] handle_special(kg) +[handle_special] not special! +[handle_unit] Parse item: 'kg' +[ul_parse] Parse unit: '(m s)^2' +[ul_parse] Start: 0 +[ul_parse] End: 0 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 0 -> 1 +[ul_parse] Start: 1 +[ul_parse] End: 2 +[ul_parse] Item is 'm' +[handle_special] handle_special(m) +[handle_special] not special! +[handle_unit] Parse item: 'm' +[ul_parse] Start: 3 +[ul_parse] End: 4 +[ul_parse] Item is 's' +[handle_special] handle_special(s) +[handle_special] not special! +[handle_unit] Parse item: 's' +[ul_parse] Exp hack! +[ul_parse] Start: 4 +[ul_parse] End: 7 +[ul_parse] Item is ')^2' +[handle_special] handle_special()^2) +[ul_parse] Parse unit: 'kg*m^2/(s^4 kg) sqrt(A^2 K^4)' +[ul_parse] Start: 0 +[ul_parse] End: 2 +[ul_parse] Item is 'kg' +[handle_special] handle_special(kg) +[handle_special] not special! +[handle_unit] Parse item: 'kg' +[ul_parse] Start: 2 +[ul_parse] End: 2 +[ul_parse] Item is '*' +[handle_special] handle_special(*) +[ul_parse] Start: 3 +[ul_parse] End: 6 +[ul_parse] Item is 'm^2' +[handle_special] handle_special(m^2) +[handle_special] not special! +[handle_unit] Parse item: 'm^2' +[ul_parse] Start: 6 +[ul_parse] End: 6 +[ul_parse] Item is '/' +[handle_special] handle_special(/) +[ul_parse] Start: 7 +[ul_parse] End: 7 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 0 -> 1 +[ul_parse] Start: 8 +[ul_parse] End: 11 +[ul_parse] Item is 's^4' +[handle_special] handle_special(s^4) +[handle_special] not special! +[handle_unit] Parse item: 's^4' +[ul_parse] Start: 12 +[ul_parse] End: 14 +[ul_parse] Item is 'kg' +[handle_special] handle_special(kg) +[handle_special] not special! +[handle_unit] Parse item: 'kg' +[ul_parse] Start: 14 +[ul_parse] End: 14 +[ul_parse] Item is ')' +[handle_special] handle_special()) +[ul_parse] Start: 16 +[ul_parse] End: 20 +[ul_parse] Item is 'sqrt' +[handle_special] handle_special(sqrt) +[handle_special] Found sqrt +[ul_parse] Start: 20 +[ul_parse] End: 20 +[ul_parse] Item is '(' +[handle_special] handle_special(() +[push_unit] Push: 0 -> 1 +[ul_parse] Start: 21 +[ul_parse] End: 24 +[ul_parse] Item is 'A^2' +[handle_special] handle_special(A^2) +[handle_special] not special! +[handle_unit] Parse item: 'A^2' +[ul_parse] Start: 25 +[ul_parse] End: 28 +[ul_parse] Item is 'K^4' +[handle_special] handle_special(K^4) +[handle_special] not special! +[handle_unit] Parse item: 'K^4' +[ul_parse] Start: 28 +[ul_parse] End: 28 +[ul_parse] Item is ')' +[handle_special] handle_special()) +[ul_parse_rule] Parsing rule 'N = 1 kg m s^-2' +[ul_parse_rule] Split at 2 +[get_symbol] Allocate 2 bytes +[get_symbol] Symbol is 'N' +[ul_parse_rule] Rest definition is ' 1 kg m s^-2' +[ul_parse] Parse unit: ' 1 kg m s^-2' +[ul_parse] Start: 1 +[ul_parse] End: 2 +[ul_parse] Item is '1' +[handle_special] handle_special(1) +[handle_special] not special! +[handle_factor] '1' is a factor +[ul_parse] Start: 3 +[ul_parse] End: 5 +[ul_parse] Item is 'kg' +[handle_special] handle_special(kg) +[handle_special] not special! +[handle_unit] Parse item: 'kg' +[ul_parse] Start: 6 +[ul_parse] End: 7 +[ul_parse] Item is 'm' +[handle_special] handle_special(m) +[handle_special] not special! +[handle_unit] Parse item: 'm' +[ul_parse] Start: 8 +[ul_parse] End: 12 +[ul_parse] Item is 's^-2' +[handle_special] handle_special(s^-2) +[handle_special] not special! +[handle_unit] Parse item: 's^-2'
jan-kuechler/unitlib
74283b995a791bd35387f320ef69432f7b559cca
Change version to 0.5
diff --git a/unitlib.h b/unitlib.h index 0a25e26..2076a81 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,251 +1,249 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" -#define UL_VERSION "0.4b5" +#define UL_VERSION "0.5" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #define UL_API UL_LINKAGE typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; -#define U_ANY -1 - typedef enum ul_format { UL_FMT_PLAIN = 0, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, UL_NUM_FORMATS, } ul_format_t; typedef enum ul_cmpres { UL_DIFFERENT = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, UL_ERROR = 0xFF, } ul_cmpres_t; enum ul_fmtop { UL_FOP_REDUCE = 0x01, }; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the full name of unitlib, including the version * @return String in the form "unitlib-x.yz" */ UL_API const char *ul_get_name(void); /** * Returns the version of unitlib * @return String in the form "x.yz" */ UL_API const char *ul_get_version(void); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Checks whether a unit is reduceable to a composed unit * @param unit The unit * @return True if the unit is reduceable, false if not or if an error occured */ UL_API bool ul_reduceable(const unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, int fops); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, int fops) { return ul_fprint(stdout, unit, format, fops); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, int fops); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option * @param fops A bitmap containing UL_FOP_* flags * @return Length of the formated string */ UL_API size_t ul_length(const unit_t *unit, ul_format_t format, int fops); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
de6fb70f9efd164c4b336b778ca6755c1c77f8a9
Changed version to 0.4b5, hopefully the last beta before 0.4.
diff --git a/unitlib.h b/unitlib.h index a35ca9b..0a25e26 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,251 +1,251 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" -#define UL_VERSION "0.4b4" +#define UL_VERSION "0.4b5" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #define UL_API UL_LINKAGE typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN = 0, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, UL_NUM_FORMATS, } ul_format_t; typedef enum ul_cmpres { UL_DIFFERENT = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, UL_ERROR = 0xFF, } ul_cmpres_t; enum ul_fmtop { UL_FOP_REDUCE = 0x01, }; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the full name of unitlib, including the version * @return String in the form "unitlib-x.yz" */ UL_API const char *ul_get_name(void); /** * Returns the version of unitlib * @return String in the form "x.yz" */ UL_API const char *ul_get_version(void); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Checks whether a unit is reduceable to a composed unit * @param unit The unit * @return True if the unit is reduceable, false if not or if an error occured */ UL_API bool ul_reduceable(const unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, int fops); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, int fops) { return ul_fprint(stdout, unit, format, fops); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, int fops); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option * @param fops A bitmap containing UL_FOP_* flags * @return Length of the formated string */ UL_API size_t ul_length(const unit_t *unit, ul_format_t format, int fops); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
8e44cd0fee058dd1ebfc257fb1d8e28add48ee53
Added an ugly hack to parse "(kg m)^2".
diff --git a/parser.c b/parser.c index ec0f054..644ff08 100644 --- a/parser.c +++ b/parser.c @@ -1,771 +1,799 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" // My string.h is missing strdup so place it here. char *strdup(const char *s1); // A unit conversion rule typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; // A unit prefix (like mili) typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; // A list of all prefixes static prefix_t *prefixes = NULL; // Symbolic definition for the first dynamic allocated rule // valid after _ul_init_parser() ist called #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) enum { STACK_SIZE = 16, // Size of the parser state stack MAX_SYM_SIZE = 128, // Maximal size of a symbol MAX_ITEM_SIZE = 1024, // Maximal size of a composed item }; // State in () struct substate { unit_t unit; bool sqrt; int sign; }; // The state of an ongoing parse struct parser_state { // state stack and current position size_t spos; struct substate stack[STACK_SIZE]; bool brkt; // true if the next item has to be an opening bracket char wasop; // true if the last item was an operator ('*' or '/') bool nextsqrt; // true if the next substate is in sqrt }; #define CURRENT(what,state) (state)->stack[(state)->spos].what // Result of a handle_* call enum result { RS_ERROR, // Something was wrong RS_HANDLED, // The job is done RS_NOT_MINE, // Not my business }; #define HANDLE_RESULT(marg_rs) \ do { \ enum result macro_rs = marg_rs; \ if (macro_rs == RS_ERROR) { \ return false; \ } \ if (macro_rs == RS_HANDLED) { \ return true; \ } \ assert(macro_rs == RS_NOT_MINE); \ } while (0); // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } // Returns the rule to a symbol static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } // Returns the last prefix in the list static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } // Returns the prefix definition to a character static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } // Skips all spaces at the beginning of the string static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } // Returns the position of the next space in the string static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool splitchars[256] = { ['*'] = true, ['/'] = true, ['('] = true, [')'] = true, }; static inline bool issplit(char c) { return splitchars[(int)c]; } // Returns the position of the next split character or space in the string static size_t nextsplit(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !(isspace(text[i]) || issplit(text[i]))) i++; return i; } static void init_substate(struct substate *sst) { sst->sign = 1; init_unit(&sst->unit); sst->sqrt = false; } static bool push_unit(struct parser_state *state) { state->spos++; debug("Push: %u -> %u", state->spos-1, state->spos); if (state->spos >= STACK_SIZE) { ERROR("Maximal nesting level exceeded."); return false; } init_substate(&state->stack[state->spos]); if (state->nextsqrt) { CURRENT(sqrt,state) = true; state->nextsqrt = false; } return true; } -static bool pop_unit(struct parser_state *state) +static bool pop_unit(struct parser_state *state, int exp) { if (state->spos == 0) { ERROR("Internal error: Stack missmatch!"); return false; } bool sqrt = CURRENT(sqrt, state); CURRENT(sqrt, state) = false; unit_t *top = &CURRENT(unit, state); state->spos--; if (sqrt && !ul_sqrt(top)) return false; - add_unit(&CURRENT(unit,state), top, 1); + exp *= CURRENT(sign,state); + + add_unit(&CURRENT(unit,state), top, exp); return true; } +static enum result sym_and_exp(const char *str, char *sym, int *exp) +{ + assert(str); assert(sym); assert(exp); + + size_t symend = 0; + + while (str[symend] && str[symend] != '^') + symend++; + + if (symend >= MAX_SYM_SIZE) { + ERROR("Symbol to long"); + return RS_ERROR; + } + strncpy(sym, str, symend); + sym[symend] = '\0'; + + *exp = 1; + enum result rs = RS_NOT_MINE; + + if (str[symend]) { + // The '^' should not be the last value of the string + if (!str[symend+1]) { + ERROR("Missing exponent after '^' while parsing '%s'", str); + return RS_ERROR; + } + + // Parse the exponent + char *endptr = NULL; + *exp = strtol(str+symend+1, &endptr, 10); + + // the whole exp string was valid only if *endptr is '\0' + if (endptr && *endptr) { + ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); + return RS_ERROR; + } + rs = RS_HANDLED; + } + return rs; +} + static enum result handle_bracket_end(const char *str, struct parser_state *state) { - (void)str; - // TODO: add exp support - if (!pop_unit(state)) + char sym[MAX_SYM_SIZE]; + int exp = 1; + + if (sym_and_exp(str, sym, &exp) == RS_ERROR) { + return RS_ERROR; + } + + if (!pop_unit(state, exp)) return RS_ERROR; return RS_HANDLED; } static enum result handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); debug("handle_special(%s)", str); size_t len = strlen(str); if (state->brkt && (len > 1 || str[0] != '(')) { ERROR("Opening bracket expected after sqrt!"); return false; } - if (len == 1) { + if (len == 1 || str[0] == ')') { switch (str[0]) { case '/': CURRENT(sign, state) *= -1; // big bad fallthrough // * has no effect, and so the error handling // code is not doubled case '*': if (state->wasop) { ERROR("Cannot have %c right after %c.", str[0], state->wasop); return RS_ERROR; } state->wasop = str[0]; return RS_HANDLED; case '(': state->wasop = '\0'; state->brkt = false; if (!push_unit(state)) return RS_ERROR; return RS_HANDLED; case ')': state->wasop = '\0'; return handle_bracket_end(str, state); } } state->wasop = '\0'; if (strcmp(str, "sqrt") == 0) { debug("Found sqrt"); if (state->spos + 1 < STACK_SIZE) state->nextsqrt = true; state->brkt = true; return RS_HANDLED; } debug("not special!"); return RS_NOT_MINE; } static enum result handle_factor(const char *str, struct parser_state *state) { assert(str); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { return RS_NOT_MINE; } debug("'%s' is a factor", str); CURRENT(unit,state).factor *= _pown(f, CURRENT(sign,state)); return RS_HANDLED; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static enum result handle_unit(const char *str, struct parser_state *state) { assert(str); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; - size_t symend = 0; - while (str[symend] && str[symend] != '^') - symend++; - - if (symend >= MAX_SYM_SIZE) { - ERROR("Symbol to long"); + if (sym_and_exp(str, symbol, &exp) == RS_ERROR) { return RS_ERROR; } - strncpy(symbol, str, symend); - symbol[symend] = '\0'; - - if (str[symend]) { - // The '^' should not be the last value of the string - if (!str[symend+1]) { - ERROR("Missing exponent after '^' while parsing '%s'", str); - return RS_ERROR; - } - - // Parse the exponent - char *endptr = NULL; - exp = strtol(str+symend+1, &endptr, 10); - - // the whole exp string was valid only if *endptr is '\0' - if (endptr && *endptr) { - ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); - return RS_ERROR; - } - } - debug("Exponent is %d", exp); - exp *= CURRENT(sign,state); + exp *= CURRENT(sign, state); unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return RS_ERROR; // And add the definitions add_unit(&CURRENT(unit,state), rule, exp); CURRENT(unit,state).factor *= _pown(prefix, exp); return RS_HANDLED; } static bool handle_item(const char *item, struct parser_state *state) { HANDLE_RESULT(handle_special(item, state)); // special has to be the first one! HANDLE_RESULT(handle_factor(item, state)); HANDLE_RESULT(handle_unit(item, state)); ERROR("Unknown item type for item '%s'", item); return false; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state = { .spos = 0, .brkt = false, .wasop = '\0', .nextsqrt = false, }; init_substate(&state.stack[0]); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextsplit(str, start); + // HACK + if ((str[start] == ')') && (str[start+1] == '^')) { + debug("Exp hack!"); + end = nextsplit(str, start+1); + } + debug("Start: %d", start); debug("End: %d", end); if (end == start) { if (end == len) // end of string break; end++; // this one is a single splitchar } + // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; debug("Item is '%s'", this_item); // and handle it if (!handle_item(this_item, &state)) return false; start = end; } while (start < len); if (state.spos != 0) { ERROR("Bracket missmatch"); return false; } copy_unit(&state.stack[0].unit, unit); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } UL_LINKAGE const char *_ul_reduce(const unit_t *unit) { for (rule_t *cur = rules; cur; cur = cur->next) { if (ul_cmp(&cur->unit, unit) & UL_SAME_UNIT) return cur->symbol; } return NULL; } static bool kilogram_hack(void) { // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule(strdup("g"), &gram, true)) // strdup because add_rule expects malloc'd memory (it gets free'd at ul_quit) return false; return true; } static void free_rules(void) { rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } dynamic_rules = NULL; } static void free_prefixes(void) { prefix_t *pref = prefixes; while (pref) { prefix_t *next = pref->next; free(pref); pref = next; } prefixes = NULL; } UL_API bool ul_reset_rules(void) { free_rules(); kilogram_hack(); return true; } static bool init_prefixes(void) { debug("Initializing prefixes"); if (!add_prefix('Y', 1e24)) return false; if (!add_prefix('Z', 1e21)) return false; // zetta if (!add_prefix('E', 1e18)) return false; // exa if (!add_prefix('P', 1e15)) return false; // peta if (!add_prefix('T', 1e12)) return false; // tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca if (!add_prefix('d', 1e-1)) return false; // deci if (!add_prefix('c', 1e-2)) return false; // centi if (!add_prefix('m', 1e-3)) return false; // milli if (!add_prefix('u', 1e-6)) return false; // micro if (!add_prefix('n', 1e-9)) return false; // nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto debug("Prefixes initialized!"); return true; } UL_LINKAGE bool _ul_init_parser(void) { debug("Initializing parser"); for (int i=0; i < NUM_BASE_UNITS; ++i) { debug("Base rule: %d", i); base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; debug("Base rules initialized"); if (!kilogram_hack()) return false; if (!init_prefixes()) return false; debug("Parser initalized!"); return true; } UL_LINKAGE void _ul_free_rules(void) { free_rules(); free_prefixes(); } \ No newline at end of file diff --git a/unittest.c b/unittest.c index a4b854a..d0a521b 100644 --- a/unittest.c +++ b/unittest.c @@ -1,638 +1,646 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) AUTO_FAIL printf("[%s-%d-%d] The test '%s' failed: \n[%s-%d-%d] Error message: %s\n", Suite, Test, Check, Expr, Suite, Test, Check, ul_error()); END_AUTO_FAIL TEST_SUITE(parser) GROUP("base") TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() GROUP("validation") TEST unit_t u; const char *strings[] = { "5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! "sqrt kg^2)", // missing ( after sqrt "( kg^2 m", // missing ) "((((((((((((((((((((((((((((((((((((((((((((((((", NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST TEST static char prefs[] = "YZEPTGMkh dcmunpfazy"; static ul_number factors[] = { 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1, 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, }; size_t num_prefs = strlen(prefs); FATAL((sizeof(factors) / sizeof(factors[0])) != num_prefs); for (size_t i = 0; i < num_prefs; ++i) { char expr[128] = ""; snprintf(expr, 128, "5 %cm", prefs[i]); unit_t u; CHECK(ul_parse(expr, &u)); FAIL_MSG("Failed to parse: '%s' (%s)", expr, ul_error()); CHECK(ncmp(ul_factor(&u), 5 * factors[i]) == 0); FAIL_MSG("Factor: %g instead of %g (%c)", ul_factor(&u), 5 * factors[i], prefs[i]); // check kilogram, the only base unit with a prefix snprintf(expr, 128, "%cg", prefs[i]); CHECK(ul_parse(expr, &u)); } END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -1); unit_t test; CHECK(ul_parse("kg / s", &test)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&test, &correct)); correct.factor = 2.0; CHECK(ul_parse("8 kg / 4 s", &test)); CHECK(ul_equal(&test, &correct)); END_TEST GROUP("extended") TEST unit_t kg = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t u; CHECK(ul_parse("sqrt(4 kg^2)", &u)); CHECK(ul_equal(&u, &kg)); char buffer[128]; ul_snprint(buffer, 128, &u, UL_FMT_PLAIN, 0); FAIL_MSG("Result was: %s", buffer); END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_METER, -1, U_KILOGRAM, 2); unit_t u; CHECK(ul_parse("sqrt(kg^2/m^2) kg", &u)); CHECK(ul_equal(&u, &correct)); END_TEST + TEST + unit_t correct = MAKE_UNIT(1.0, U_METER, 2, U_SECOND, 2); + unit_t u; + + CHECK(ul_parse("(m s)^2", &u)); + CHECK(ul_equal(&u, &correct)); + END_TEST + TEST unit_t u; CHECK(ul_parse("kg*m^2/(s^4 kg) sqrt(A^2 K^4)", &u)); END_TEST END_GROUP() END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t one_kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t five_kg = MAKE_UNIT(5.0, U_KILOGRAM, 1); CHECK(!ul_equal(&one_kg, &five_kg)); CHECK(ul_cmp(&one_kg, &five_kg) == UL_SAME_UNIT); unit_t five_sec = MAKE_UNIT(5.0, U_SECOND, 1); CHECK(ul_cmp(&five_kg, &five_sec) == UL_SAME_FACTOR); CHECK(ul_cmp(&one_kg, &five_sec) == UL_DIFFERENT); CHECK(ul_cmp(NULL, &one_kg) == UL_ERROR); CHECK(ul_cmp(&one_kg, NULL) == UL_ERROR); CHECK(ul_cmp(NULL, NULL) == UL_ERROR); /* UL_EQUAL result is tested by the previous test */ END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST TEST unit_t test = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, 5.0)); CHECK(ul_factor(&test) == 5.0); CHECK(ul_mult(&test, 1/5.0)); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, -1)); CHECK(ul_factor(&test) == -1.0); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_INLINE, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_FRAC, 0) == strlen(buffer)); FAIL_MSG("ul_length: %zu", ul_length(&N, UL_FMT_LATEX_FRAC, 0)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() TEST_SUITE(reduce) TEST CHECK(ul_parse_rule("N = 1 kg m s^-2")); unit_t N = MAKE_UNIT(1, U_KILOGRAM, 1, U_METER, 1, U_SECOND, -2); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "1 N") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); END_TEST END_TEST_SUITE() int main(void) { ul_debugging(true); ul_debugout("utest-debug.log", false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); USE_AUTO_FAIL(); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); RUN_SUITE(reduce); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define FATAL(expr) \ do { \ if (expr) { \ PRINT(_o, L_RESULT, "[%s%s-%d] Fatal: %s\n", _name, _group_name, _id, #expr); \ exit(1); \ } \ } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s%s-%d-%d] (%d) Fail: '%s'\n", _name, _group_name, _id, _this, __LINE__, #expr); \ _last = false;\ if (_o->autofail) _o->autofail(_name, _id, _this, #expr); \ } \ else { \ PRINT(_o, L_VERBOSE, "[%s%s-%d-%d] Pass: '%s'\n", _name, _group_name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define AUTO_FAIL \ static inline void _auto_fail(const char *Suite, int Test, int Check, const char *Expr) { #define END_AUTO_FAIL \ } #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ const char *_group_name = ""; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } #define GROUP(name) \ do { const char *_group_name = "-" name; int _test_id = 0; #define END_GROUP() \ } while (0); #define SKIP_GROUP() PRINT(_o, L_NORMAL, "[%s%s] skipped.\n", _name, _group_name); break; // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s%s-%d] failed with %d error%s.\n", _name, _group_name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s%s-%d] passed.\n", _name, _group_name, _id); \ } \ } // OTHER typedef struct { int loglvl; void (*autofail)(const char*,int,int,const char*); } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops = {L_RESULT,NULL}; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define USE_AUTO_FAIL() \ _ops.autofail = _auto_fail; #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
82411b89941acde4af3791a77a70a2994acc633f
Fixed bug with '/' in sqrt expressions.
diff --git a/parser.c b/parser.c index 448229c..ec0f054 100644 --- a/parser.c +++ b/parser.c @@ -1,761 +1,771 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" // My string.h is missing strdup so place it here. char *strdup(const char *s1); // A unit conversion rule typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; // A unit prefix (like mili) typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; // A list of all prefixes static prefix_t *prefixes = NULL; // Symbolic definition for the first dynamic allocated rule // valid after _ul_init_parser() ist called #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) enum { - USTACK_SIZE = 16, // Size of the parser state stack + STACK_SIZE = 16, // Size of the parser state stack MAX_SYM_SIZE = 128, // Maximal size of a symbol MAX_ITEM_SIZE = 1024, // Maximal size of a composed item }; +// State in () +struct substate +{ + unit_t unit; + bool sqrt; + int sign; +}; + // The state of an ongoing parse struct parser_state { - int sign; // Exp sign - unit_t *unit; // Current unit - unit_t ustack[USTACK_SIZE]; // Stack of units - size_t spos; // Stackpos - bool is_sqrt[USTACK_SIZE]; // Sqrt flags - bool need_bracket; // true if the next item has to be an opening bracket - char was_operator; // true if the last item was an operator ('*' or '/') + // state stack and current position + size_t spos; + struct substate stack[STACK_SIZE]; + + bool brkt; // true if the next item has to be an opening bracket + char wasop; // true if the last item was an operator ('*' or '/') + bool nextsqrt; // true if the next substate is in sqrt }; +#define CURRENT(what,state) (state)->stack[(state)->spos].what // Result of a handle_* call enum result { RS_ERROR, // Something was wrong RS_HANDLED, // The job is done RS_NOT_MINE, // Not my business }; #define HANDLE_RESULT(marg_rs) \ do { \ enum result macro_rs = marg_rs; \ if (macro_rs == RS_ERROR) { \ return false; \ } \ if (macro_rs == RS_HANDLED) { \ return true; \ } \ assert(macro_rs == RS_NOT_MINE); \ } while (0); // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } // Returns the rule to a symbol static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } // Returns the last prefix in the list static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } // Returns the prefix definition to a character static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } // Skips all spaces at the beginning of the string static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } // Returns the position of the next space in the string static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool splitchars[256] = { ['*'] = true, ['/'] = true, ['('] = true, [')'] = true, }; static inline bool issplit(char c) { return splitchars[(int)c]; } // Returns the position of the next split character or space in the string static size_t nextsplit(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !(isspace(text[i]) || issplit(text[i]))) i++; return i; } -static enum result handle_factor(const char *str, struct parser_state *state) +static void init_substate(struct substate *sst) { - assert(str); assert(state); - char *endptr; - ul_number f = _strton(str, &endptr); - if (endptr && *endptr) { - return RS_NOT_MINE; - } - debug("'%s' is a factor", str); - state->unit->factor *= _pown(f, state->sign); - return RS_HANDLED; + sst->sign = 1; + init_unit(&sst->unit); + sst->sqrt = false; } static bool push_unit(struct parser_state *state) { state->spos++; debug("Push: %u -> %u", state->spos-1, state->spos); - if (state->spos >= USTACK_SIZE) { + if (state->spos >= STACK_SIZE) { ERROR("Maximal nesting level exceeded."); return false; } - state->unit = &state->ustack[state->spos]; - init_unit(state->unit); + init_substate(&state->stack[state->spos]); + + if (state->nextsqrt) { + CURRENT(sqrt,state) = true; + state->nextsqrt = false; + } return true; } static bool pop_unit(struct parser_state *state) { if (state->spos == 0) { ERROR("Internal error: Stack missmatch!"); return false; } - bool sqrt = state->is_sqrt[state->spos]; - state->is_sqrt[state->spos] = false; + bool sqrt = CURRENT(sqrt, state); + CURRENT(sqrt, state) = false; - unit_t *top = state->unit; + unit_t *top = &CURRENT(unit, state); state->spos--; if (sqrt && !ul_sqrt(top)) return false; - //debug("Pop: %u -> %u", state->spos+1, state->spos); - //debug("Pop: %p -> %p (%p)", top, &state->ustack[state->spos], state->unit); - debug("is_sqrt flag is set."); - //debug("Units: top, top-1, result"); - //debug(DBG_UNIT_HDR); - //debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(top)); - state->unit = &state->ustack[state->spos]; - //debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(state->unit)); - add_unit(state->unit, top, 1); - //debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(state->unit)); + add_unit(&CURRENT(unit,state), top, 1); return true; } static enum result handle_bracket_end(const char *str, struct parser_state *state) { (void)str; - // TODO: add exp and sqrt support + // TODO: add exp support if (!pop_unit(state)) return RS_ERROR; return RS_HANDLED; } static enum result handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); debug("handle_special(%s)", str); size_t len = strlen(str); - if (state->need_bracket && (len > 1 || str[0] != '(')) { + if (state->brkt && (len > 1 || str[0] != '(')) { ERROR("Opening bracket expected after sqrt!"); return false; } if (len == 1) { switch (str[0]) { case '/': - state->sign *= -1; + CURRENT(sign, state) *= -1; // big bad fallthrough // * has no effect, and so the error handling // code is not doubled case '*': - if (state->was_operator) { - ERROR("Cannot have %c right after %c.", str[0], state->was_operator); + if (state->wasop) { + ERROR("Cannot have %c right after %c.", str[0], state->wasop); return RS_ERROR; } - state->was_operator = str[0]; + state->wasop = str[0]; return RS_HANDLED; case '(': - state->was_operator = '\0'; - state->need_bracket = false; + state->wasop = '\0'; + state->brkt = false; if (!push_unit(state)) return RS_ERROR; return RS_HANDLED; case ')': - state->was_operator = '\0'; + state->wasop = '\0'; return handle_bracket_end(str, state); } } - state->was_operator = '\0'; + state->wasop = '\0'; if (strcmp(str, "sqrt") == 0) { debug("Found sqrt"); - if (state->spos + 1 < USTACK_SIZE) - state->is_sqrt[state->spos+1] = true; - state->need_bracket = true; + if (state->spos + 1 < STACK_SIZE) + state->nextsqrt = true; + state->brkt = true; return RS_HANDLED; } debug("not special!"); return RS_NOT_MINE; } +static enum result handle_factor(const char *str, struct parser_state *state) +{ + assert(str); assert(state); + char *endptr; + ul_number f = _strton(str, &endptr); + if (endptr && *endptr) { + return RS_NOT_MINE; + } + debug("'%s' is a factor", str); + + CURRENT(unit,state).factor *= _pown(f, CURRENT(sign,state)); + + return RS_HANDLED; +} + static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static enum result handle_unit(const char *str, struct parser_state *state) { assert(str); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return RS_ERROR; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return RS_ERROR; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return RS_ERROR; } } debug("Exponent is %d", exp); - exp *= state->sign; + exp *= CURRENT(sign,state); unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return RS_ERROR; // And add the definitions - add_unit(state->unit, rule, exp); - state->unit->factor *= _pown(prefix, exp); + add_unit(&CURRENT(unit,state), rule, exp); + CURRENT(unit,state).factor *= _pown(prefix, exp); return RS_HANDLED; } static bool handle_item(const char *item, struct parser_state *state) { HANDLE_RESULT(handle_special(item, state)); // special has to be the first one! HANDLE_RESULT(handle_factor(item, state)); HANDLE_RESULT(handle_unit(item, state)); ERROR("Unknown item type for item '%s'", item); return false; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state = { - .sign = 1, - .is_sqrt = {false}, - .need_bracket = false, - .was_operator = '\0', - .spos = 0, + .spos = 0, + .brkt = false, + .wasop = '\0', + .nextsqrt = false, }; - state.unit = &state.ustack[0]; - - init_unit(state.unit); + init_substate(&state.stack[0]); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextsplit(str, start); debug("Start: %d", start); debug("End: %d", end); if (end == start) { if (end == len) // end of string break; end++; // this one is a single splitchar } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; debug("Item is '%s'", this_item); // and handle it if (!handle_item(this_item, &state)) return false; start = end; } while (start < len); if (state.spos != 0) { ERROR("Bracket missmatch"); return false; } - copy_unit(&state.ustack[0], unit); + copy_unit(&state.stack[0].unit, unit); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } UL_LINKAGE const char *_ul_reduce(const unit_t *unit) { for (rule_t *cur = rules; cur; cur = cur->next) { if (ul_cmp(&cur->unit, unit) & UL_SAME_UNIT) return cur->symbol; } return NULL; } static bool kilogram_hack(void) { // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule(strdup("g"), &gram, true)) // strdup because add_rule expects malloc'd memory (it gets free'd at ul_quit) return false; return true; } static void free_rules(void) { rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } dynamic_rules = NULL; } static void free_prefixes(void) { prefix_t *pref = prefixes; while (pref) { prefix_t *next = pref->next; free(pref); pref = next; } prefixes = NULL; } UL_API bool ul_reset_rules(void) { free_rules(); kilogram_hack(); return true; } static bool init_prefixes(void) { debug("Initializing prefixes"); if (!add_prefix('Y', 1e24)) return false; if (!add_prefix('Z', 1e21)) return false; // zetta if (!add_prefix('E', 1e18)) return false; // exa if (!add_prefix('P', 1e15)) return false; // peta if (!add_prefix('T', 1e12)) return false; // tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca if (!add_prefix('d', 1e-1)) return false; // deci if (!add_prefix('c', 1e-2)) return false; // centi if (!add_prefix('m', 1e-3)) return false; // milli if (!add_prefix('u', 1e-6)) return false; // micro if (!add_prefix('n', 1e-9)) return false; // nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto debug("Prefixes initialized!"); return true; } UL_LINKAGE bool _ul_init_parser(void) { debug("Initializing parser"); for (int i=0; i < NUM_BASE_UNITS; ++i) { debug("Base rule: %d", i); base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; debug("Base rules initialized"); if (!kilogram_hack()) return false; if (!init_prefixes()) return false; debug("Parser initalized!"); return true; } UL_LINKAGE void _ul_free_rules(void) { free_rules(); free_prefixes(); } \ No newline at end of file diff --git a/unittest.c b/unittest.c index e69df31..a4b854a 100644 --- a/unittest.c +++ b/unittest.c @@ -1,630 +1,638 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) AUTO_FAIL printf("[%s-%d-%d] The test '%s' failed: \n[%s-%d-%d] Error message: %s\n", Suite, Test, Check, Expr, Suite, Test, Check, ul_error()); END_AUTO_FAIL TEST_SUITE(parser) GROUP("base") TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() GROUP("validation") TEST unit_t u; const char *strings[] = { "5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! "sqrt kg^2)", // missing ( after sqrt "( kg^2 m", // missing ) "((((((((((((((((((((((((((((((((((((((((((((((((", NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST TEST static char prefs[] = "YZEPTGMkh dcmunpfazy"; static ul_number factors[] = { 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1, 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, }; size_t num_prefs = strlen(prefs); FATAL((sizeof(factors) / sizeof(factors[0])) != num_prefs); for (size_t i = 0; i < num_prefs; ++i) { char expr[128] = ""; snprintf(expr, 128, "5 %cm", prefs[i]); unit_t u; CHECK(ul_parse(expr, &u)); FAIL_MSG("Failed to parse: '%s' (%s)", expr, ul_error()); CHECK(ncmp(ul_factor(&u), 5 * factors[i]) == 0); FAIL_MSG("Factor: %g instead of %g (%c)", ul_factor(&u), 5 * factors[i], prefs[i]); // check kilogram, the only base unit with a prefix snprintf(expr, 128, "%cg", prefs[i]); CHECK(ul_parse(expr, &u)); } END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -1); unit_t test; CHECK(ul_parse("kg / s", &test)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&test, &correct)); correct.factor = 2.0; CHECK(ul_parse("8 kg / 4 s", &test)); CHECK(ul_equal(&test, &correct)); END_TEST GROUP("extended") TEST unit_t kg = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t u; CHECK(ul_parse("sqrt(4 kg^2)", &u)); CHECK(ul_equal(&u, &kg)); char buffer[128]; ul_snprint(buffer, 128, &u, UL_FMT_PLAIN, 0); FAIL_MSG("Result was: %s", buffer); END_TEST + TEST + unit_t correct = MAKE_UNIT(1.0, U_METER, -1, U_KILOGRAM, 2); + unit_t u; + + CHECK(ul_parse("sqrt(kg^2/m^2) kg", &u)); + CHECK(ul_equal(&u, &correct)); + END_TEST + TEST unit_t u; CHECK(ul_parse("kg*m^2/(s^4 kg) sqrt(A^2 K^4)", &u)); END_TEST END_GROUP() END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t one_kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t five_kg = MAKE_UNIT(5.0, U_KILOGRAM, 1); CHECK(!ul_equal(&one_kg, &five_kg)); CHECK(ul_cmp(&one_kg, &five_kg) == UL_SAME_UNIT); unit_t five_sec = MAKE_UNIT(5.0, U_SECOND, 1); CHECK(ul_cmp(&five_kg, &five_sec) == UL_SAME_FACTOR); CHECK(ul_cmp(&one_kg, &five_sec) == UL_DIFFERENT); CHECK(ul_cmp(NULL, &one_kg) == UL_ERROR); CHECK(ul_cmp(&one_kg, NULL) == UL_ERROR); CHECK(ul_cmp(NULL, NULL) == UL_ERROR); /* UL_EQUAL result is tested by the previous test */ END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST TEST unit_t test = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, 5.0)); CHECK(ul_factor(&test) == 5.0); CHECK(ul_mult(&test, 1/5.0)); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, -1)); CHECK(ul_factor(&test) == -1.0); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_INLINE, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_FRAC, 0) == strlen(buffer)); FAIL_MSG("ul_length: %zu", ul_length(&N, UL_FMT_LATEX_FRAC, 0)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() TEST_SUITE(reduce) TEST CHECK(ul_parse_rule("N = 1 kg m s^-2")); unit_t N = MAKE_UNIT(1, U_KILOGRAM, 1, U_METER, 1, U_SECOND, -2); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "1 N") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); END_TEST END_TEST_SUITE() int main(void) { ul_debugging(true); ul_debugout("utest-debug.log", false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); USE_AUTO_FAIL(); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); RUN_SUITE(reduce); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define FATAL(expr) \ do { \ if (expr) { \ PRINT(_o, L_RESULT, "[%s%s-%d] Fatal: %s\n", _name, _group_name, _id, #expr); \ exit(1); \ } \ } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s%s-%d-%d] (%d) Fail: '%s'\n", _name, _group_name, _id, _this, __LINE__, #expr); \ _last = false;\ if (_o->autofail) _o->autofail(_name, _id, _this, #expr); \ } \ else { \ PRINT(_o, L_VERBOSE, "[%s%s-%d-%d] Pass: '%s'\n", _name, _group_name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define AUTO_FAIL \ static inline void _auto_fail(const char *Suite, int Test, int Check, const char *Expr) { #define END_AUTO_FAIL \ } #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ const char *_group_name = ""; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } #define GROUP(name) \ do { const char *_group_name = "-" name; int _test_id = 0; #define END_GROUP() \ } while (0); #define SKIP_GROUP() PRINT(_o, L_NORMAL, "[%s%s] skipped.\n", _name, _group_name); break; // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s%s-%d] failed with %d error%s.\n", _name, _group_name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s%s-%d] passed.\n", _name, _group_name, _id); \ } \ } // OTHER typedef struct { int loglvl; void (*autofail)(const char*,int,int,const char*); } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops = {L_RESULT,NULL}; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define USE_AUTO_FAIL() \ _ops.autofail = _auto_fail; #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
ad66e68cfcde398c3dfbefb847d8d8b2fbb7a73f
Added comments
diff --git a/parser.c b/parser.c index 1b49efa..448229c 100644 --- a/parser.c +++ b/parser.c @@ -1,656 +1,667 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" // My string.h is missing strdup so place it here. char *strdup(const char *s1); +// A unit conversion rule typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; +// A unit prefix (like mili) typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; - +// A list of all prefixes static prefix_t *prefixes = NULL; +// Symbolic definition for the first dynamic allocated rule +// valid after _ul_init_parser() ist called #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) -enum { USTACK_SIZE = 16, }; +enum { + USTACK_SIZE = 16, // Size of the parser state stack + MAX_SYM_SIZE = 128, // Maximal size of a symbol + MAX_ITEM_SIZE = 1024, // Maximal size of a composed item +}; +// The state of an ongoing parse struct parser_state { - int sign; - unit_t *unit; - unit_t ustack[USTACK_SIZE]; - size_t spos; - bool is_sqrt[USTACK_SIZE]; - bool need_bracket; - char was_operator; -}; - -enum { - MAX_SYM_SIZE = 128, - MAX_ITEM_SIZE = 1024, + int sign; // Exp sign + unit_t *unit; // Current unit + unit_t ustack[USTACK_SIZE]; // Stack of units + size_t spos; // Stackpos + bool is_sqrt[USTACK_SIZE]; // Sqrt flags + bool need_bracket; // true if the next item has to be an opening bracket + char was_operator; // true if the last item was an operator ('*' or '/') }; +// Result of a handle_* call enum result { - RS_ERROR, - RS_HANDLED, - RS_NOT_MINE, + RS_ERROR, // Something was wrong + RS_HANDLED, // The job is done + RS_NOT_MINE, // Not my business }; #define HANDLE_RESULT(marg_rs) \ do { \ enum result macro_rs = marg_rs; \ if (macro_rs == RS_ERROR) { \ return false; \ } \ if (macro_rs == RS_HANDLED) { \ return true; \ } \ assert(macro_rs == RS_NOT_MINE); \ } while (0); // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } +// Returns the rule to a symbol static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } +// Returns the last prefix in the list static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } +// Returns the prefix definition to a character static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } +// Skips all spaces at the beginning of the string static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } +// Returns the position of the next space in the string static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool splitchars[256] = { ['*'] = true, ['/'] = true, ['('] = true, [')'] = true, }; static inline bool issplit(char c) { return splitchars[(int)c]; } +// Returns the position of the next split character or space in the string static size_t nextsplit(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !(isspace(text[i]) || issplit(text[i]))) i++; return i; } static enum result handle_factor(const char *str, struct parser_state *state) { assert(str); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { return RS_NOT_MINE; } debug("'%s' is a factor", str); state->unit->factor *= _pown(f, state->sign); return RS_HANDLED; } static bool push_unit(struct parser_state *state) { state->spos++; debug("Push: %u -> %u", state->spos-1, state->spos); if (state->spos >= USTACK_SIZE) { ERROR("Maximal nesting level exceeded."); return false; } state->unit = &state->ustack[state->spos]; init_unit(state->unit); return true; } static bool pop_unit(struct parser_state *state) { if (state->spos == 0) { ERROR("Internal error: Stack missmatch!"); return false; } bool sqrt = state->is_sqrt[state->spos]; state->is_sqrt[state->spos] = false; unit_t *top = state->unit; state->spos--; if (sqrt && !ul_sqrt(top)) return false; //debug("Pop: %u -> %u", state->spos+1, state->spos); //debug("Pop: %p -> %p (%p)", top, &state->ustack[state->spos], state->unit); debug("is_sqrt flag is set."); //debug("Units: top, top-1, result"); //debug(DBG_UNIT_HDR); //debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(top)); state->unit = &state->ustack[state->spos]; //debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(state->unit)); add_unit(state->unit, top, 1); //debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(state->unit)); return true; } static enum result handle_bracket_end(const char *str, struct parser_state *state) { (void)str; // TODO: add exp and sqrt support if (!pop_unit(state)) return RS_ERROR; return RS_HANDLED; } static enum result handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); debug("handle_special(%s)", str); size_t len = strlen(str); if (state->need_bracket && (len > 1 || str[0] != '(')) { ERROR("Opening bracket expected after sqrt!"); return false; } if (len == 1) { switch (str[0]) { case '/': state->sign *= -1; // big bad fallthrough // * has no effect, and so the error handling // code is not doubled case '*': if (state->was_operator) { ERROR("Cannot have %c right after %c.", str[0], state->was_operator); return RS_ERROR; } state->was_operator = str[0]; return RS_HANDLED; case '(': state->was_operator = '\0'; state->need_bracket = false; if (!push_unit(state)) return RS_ERROR; return RS_HANDLED; case ')': state->was_operator = '\0'; return handle_bracket_end(str, state); } } state->was_operator = '\0'; if (strcmp(str, "sqrt") == 0) { debug("Found sqrt"); if (state->spos + 1 < USTACK_SIZE) state->is_sqrt[state->spos+1] = true; state->need_bracket = true; return RS_HANDLED; } debug("not special!"); return RS_NOT_MINE; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static enum result handle_unit(const char *str, struct parser_state *state) { assert(str); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return RS_ERROR; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return RS_ERROR; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return RS_ERROR; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return RS_ERROR; // And add the definitions add_unit(state->unit, rule, exp); state->unit->factor *= _pown(prefix, exp); return RS_HANDLED; } static bool handle_item(const char *item, struct parser_state *state) { HANDLE_RESULT(handle_special(item, state)); // special has to be the first one! HANDLE_RESULT(handle_factor(item, state)); HANDLE_RESULT(handle_unit(item, state)); ERROR("Unknown item type for item '%s'", item); return false; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state = { .sign = 1, .is_sqrt = {false}, .need_bracket = false, .was_operator = '\0', .spos = 0, }; state.unit = &state.ustack[0]; init_unit(state.unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextsplit(str, start); debug("Start: %d", start); debug("End: %d", end); if (end == start) { if (end == len) // end of string break; end++; // this one is a single splitchar } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; debug("Item is '%s'", this_item); // and handle it if (!handle_item(this_item, &state)) return false; start = end; } while (start < len); if (state.spos != 0) { ERROR("Bracket missmatch"); return false; } copy_unit(&state.ustack[0], unit); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } UL_LINKAGE const char *_ul_reduce(const unit_t *unit) { for (rule_t *cur = rules; cur; cur = cur->next) { if (ul_cmp(&cur->unit, unit) & UL_SAME_UNIT) return cur->symbol; } return NULL; } static bool kilogram_hack(void) { // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule(strdup("g"), &gram, true)) // strdup because add_rule expects malloc'd memory (it gets free'd at ul_quit)
jan-kuechler/unitlib
14b971b12f0a377177f83ff72a5a4a26b97c61c9
Changed version to 0.4b4
diff --git a/unitlib.h b/unitlib.h index e605171..a35ca9b 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,258 +1,251 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" -#define UL_VERSION "0.4a4" +#define UL_VERSION "0.4b4" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif - -//#if defined(UL_EXPORT_DLL) -//#define UL_API UL_LINKAGE __declspec(dllexport) __stdcall -//#elif defined(UL_IMPORT_DLL) -//#define UL_API UL_LINKAGE __declspec(dllimport) __stdcall -//#else #define UL_API UL_LINKAGE -//#endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN = 0, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, UL_NUM_FORMATS, } ul_format_t; typedef enum ul_cmpres { UL_DIFFERENT = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, UL_ERROR = 0xFF, } ul_cmpres_t; enum ul_fmtop { UL_FOP_REDUCE = 0x01, }; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the full name of unitlib, including the version * @return String in the form "unitlib-x.yz" */ UL_API const char *ul_get_name(void); /** * Returns the version of unitlib * @return String in the form "x.yz" */ UL_API const char *ul_get_version(void); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Checks whether a unit is reduceable to a composed unit * @param unit The unit * @return True if the unit is reduceable, false if not or if an error occured */ UL_API bool ul_reduceable(const unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, int fops); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, int fops) { return ul_fprint(stdout, unit, format, fops); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, int fops); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option * @param fops A bitmap containing UL_FOP_* flags * @return Length of the formated string */ UL_API size_t ul_length(const unit_t *unit, ul_format_t format, int fops); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
a720db234acbe698335de22a6a8ae48880928dd6
Added sqrt and some diagnostics (like operator right after operator).
diff --git a/parser.c b/parser.c index a53aa20..1b49efa 100644 --- a/parser.c +++ b/parser.c @@ -1,717 +1,750 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" // My string.h is missing strdup so place it here. char *strdup(const char *s1); typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static prefix_t *prefixes = NULL; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) enum { USTACK_SIZE = 16, }; struct parser_state { int sign; unit_t *unit; unit_t ustack[USTACK_SIZE]; size_t spos; - size_t in_sqrt; + bool is_sqrt[USTACK_SIZE]; + bool need_bracket; + char was_operator; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; enum result { RS_ERROR, RS_HANDLED, RS_NOT_MINE, }; #define HANDLE_RESULT(marg_rs) \ do { \ enum result macro_rs = marg_rs; \ - debug("rs: %d", macro_rs); \ if (macro_rs == RS_ERROR) { \ - debug("%s == RS_ERROR", #marg_rs); \ return false; \ } \ if (macro_rs == RS_HANDLED) { \ - debug("%s == RS_HANDLED", #marg_rs); \ return true; \ } \ assert(macro_rs == RS_NOT_MINE); \ - debug("%s == RS_NOT_MINE", #marg_rs); \ } while (0); // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool splitchars[256] = { ['*'] = true, ['/'] = true, ['('] = true, [')'] = true, }; static inline bool issplit(char c) { return splitchars[(int)c]; } static size_t nextsplit(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !(isspace(text[i]) || issplit(text[i]))) i++; return i; } static enum result handle_factor(const char *str, struct parser_state *state) { assert(str); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { return RS_NOT_MINE; } debug("'%s' is a factor", str); state->unit->factor *= _pown(f, state->sign); return RS_HANDLED; } static bool push_unit(struct parser_state *state) { state->spos++; debug("Push: %u -> %u", state->spos-1, state->spos); if (state->spos >= USTACK_SIZE) { ERROR("Maximal nesting level exceeded."); return false; } - unit_t *prev = state->unit; - state->unit = &state->unit[state->spos]; - debug("Push: %p -> %p", prev, state->unit); + + state->unit = &state->ustack[state->spos]; init_unit(state->unit); return true; } static bool pop_unit(struct parser_state *state) { if (state->spos == 0) { ERROR("Internal error: Stack missmatch!"); return false; } + bool sqrt = state->is_sqrt[state->spos]; + state->is_sqrt[state->spos] = false; + unit_t *top = state->unit; state->spos--; - debug("Pop: %u -> %u", state->spos+1, state->spos); - debug("Units: top, top-1, result"); - debug(DBG_UNIT_HDR); - debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(top)); - state->unit = &state->unit[state->spos]; - debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(state->unit)); + if (sqrt && !ul_sqrt(top)) + return false; + + //debug("Pop: %u -> %u", state->spos+1, state->spos); + //debug("Pop: %p -> %p (%p)", top, &state->ustack[state->spos], state->unit); + debug("is_sqrt flag is set."); + //debug("Units: top, top-1, result"); + //debug(DBG_UNIT_HDR); + //debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(top)); + state->unit = &state->ustack[state->spos]; + //debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(state->unit)); add_unit(state->unit, top, 1); - debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(state->unit)); + //debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(state->unit)); return true; } static enum result handle_bracket_end(const char *str, struct parser_state *state) { (void)str; // TODO: add exp and sqrt support if (!pop_unit(state)) return RS_ERROR; return RS_HANDLED; } static enum result handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); debug("handle_special(%s)", str); - switch (str[0]) { - case '*': - // ignore - return RS_HANDLED; - case '/': - state->sign *= -1; - return RS_HANDLED; + size_t len = strlen(str); - case '(': - if (!push_unit(state)) - return RS_ERROR; - return RS_HANDLED; + if (state->need_bracket && (len > 1 || str[0] != '(')) { + ERROR("Opening bracket expected after sqrt!"); + return false; + } + + if (len == 1) { + switch (str[0]) { - case ')': - return handle_bracket_end(str, state); + case '/': + state->sign *= -1; + // big bad fallthrough + // * has no effect, and so the error handling + // code is not doubled + case '*': + if (state->was_operator) { + ERROR("Cannot have %c right after %c.", str[0], state->was_operator); + return RS_ERROR; + } + state->was_operator = str[0]; + return RS_HANDLED; + + case '(': + state->was_operator = '\0'; + state->need_bracket = false; + if (!push_unit(state)) + return RS_ERROR; + return RS_HANDLED; + + case ')': + state->was_operator = '\0'; + return handle_bracket_end(str, state); + } } + state->was_operator = '\0'; if (strcmp(str, "sqrt") == 0) { debug("Found sqrt"); - state->in_sqrt++; - //if (!push_unit(state)) - // return RS_ERROR; + if (state->spos + 1 < USTACK_SIZE) + state->is_sqrt[state->spos+1] = true; + state->need_bracket = true; return RS_HANDLED; } debug("not special!"); return RS_NOT_MINE; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static enum result handle_unit(const char *str, struct parser_state *state) { assert(str); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return RS_ERROR; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return RS_ERROR; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return RS_ERROR; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return RS_ERROR; // And add the definitions add_unit(state->unit, rule, exp); state->unit->factor *= _pown(prefix, exp); return RS_HANDLED; } static bool handle_item(const char *item, struct parser_state *state) { - HANDLE_RESULT(handle_special(item, state)); + HANDLE_RESULT(handle_special(item, state)); // special has to be the first one! HANDLE_RESULT(handle_factor(item, state)); HANDLE_RESULT(handle_unit(item, state)); ERROR("Unknown item type for item '%s'", item); return false; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); - struct parser_state state; - state.sign = 1; - state.in_sqrt = 0; + struct parser_state state = { + .sign = 1, + .is_sqrt = {false}, + .need_bracket = false, + .was_operator = '\0', + .spos = 0, + }; state.unit = &state.ustack[0]; - state.spos = 0; init_unit(state.unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextsplit(str, start); debug("Start: %d", start); debug("End: %d", end); - if (end == start) {// End of string - if (end == len) + if (end == start) { + if (end == len) // end of string break; - end++; // this one is a split character + end++; // this one is a single splitchar } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; debug("Item is '%s'", this_item); // and handle it if (!handle_item(this_item, &state)) return false; start = end; } while (start < len); + if (state.spos != 0) { + ERROR("Bracket missmatch"); + return false; + } + copy_unit(&state.ustack[0], unit); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } UL_LINKAGE const char *_ul_reduce(const unit_t *unit) { for (rule_t *cur = rules; cur; cur = cur->next) { if (ul_cmp(&cur->unit, unit) & UL_SAME_UNIT) return cur->symbol; } return NULL; } static bool kilogram_hack(void) { // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule(strdup("g"), &gram, true)) // strdup because add_rule expects malloc'd memory (it gets free'd at ul_quit) return false; return true; } static void free_rules(void) { rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } dynamic_rules = NULL; } static void free_prefixes(void) { prefix_t *pref = prefixes; while (pref) { prefix_t *next = pref->next; free(pref); pref = next; } prefixes = NULL; } UL_API bool ul_reset_rules(void) { free_rules(); kilogram_hack(); return true; } static bool init_prefixes(void) { debug("Initializing prefixes"); if (!add_prefix('Y', 1e24)) return false; if (!add_prefix('Z', 1e21)) return false; // zetta if (!add_prefix('E', 1e18)) return false; // exa if (!add_prefix('P', 1e15)) return false; // peta if (!add_prefix('T', 1e12)) return false; // tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca if (!add_prefix('d', 1e-1)) return false; // deci if (!add_prefix('c', 1e-2)) return false; // centi if (!add_prefix('m', 1e-3)) return false; // milli if (!add_prefix('u', 1e-6)) return false; // micro if (!add_prefix('n', 1e-9)) return false; // nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto debug("Prefixes initialized!"); return true; } UL_LINKAGE bool _ul_init_parser(void) { debug("Initializing parser"); for (int i=0; i < NUM_BASE_UNITS; ++i) { debug("Base rule: %d", i); base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; debug("Base rules initialized"); if (!kilogram_hack()) return false; if (!init_prefixes()) return false; debug("Parser initalized!"); return true; } UL_LINKAGE void _ul_free_rules(void) { free_rules(); free_prefixes(); } \ No newline at end of file diff --git a/unitlib.h b/unitlib.h index 0dff234..e605171 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,258 +1,258 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" -#define UL_VERSION "0.4b3" +#define UL_VERSION "0.4a4" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif //#if defined(UL_EXPORT_DLL) //#define UL_API UL_LINKAGE __declspec(dllexport) __stdcall //#elif defined(UL_IMPORT_DLL) //#define UL_API UL_LINKAGE __declspec(dllimport) __stdcall //#else #define UL_API UL_LINKAGE //#endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN = 0, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, UL_NUM_FORMATS, } ul_format_t; typedef enum ul_cmpres { UL_DIFFERENT = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, UL_ERROR = 0xFF, } ul_cmpres_t; enum ul_fmtop { UL_FOP_REDUCE = 0x01, }; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the full name of unitlib, including the version * @return String in the form "unitlib-x.yz" */ UL_API const char *ul_get_name(void); /** * Returns the version of unitlib * @return String in the form "x.yz" */ UL_API const char *ul_get_version(void); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Checks whether a unit is reduceable to a composed unit * @param unit The unit * @return True if the unit is reduceable, false if not or if an error occured */ UL_API bool ul_reduceable(const unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, int fops); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, int fops) { return ul_fprint(stdout, unit, format, fops); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, int fops); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option * @param fops A bitmap containing UL_FOP_* flags * @return Length of the formated string */ UL_API size_t ul_length(const unit_t *unit, ul_format_t format, int fops); #endif /*UNITLIB_H*/ diff --git a/unittest.c b/unittest.c index 9ef58ce..e69df31 100644 --- a/unittest.c +++ b/unittest.c @@ -1,630 +1,630 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) AUTO_FAIL printf("[%s-%d-%d] The test '%s' failed: \n[%s-%d-%d] Error message: %s\n", Suite, Test, Check, Expr, Suite, Test, Check, ul_error()); END_AUTO_FAIL TEST_SUITE(parser) GROUP("base") TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() GROUP("validation") TEST unit_t u; const char *strings[] = { - //"5*kg^2", // need whitespace - //"5 ** kg^2", // double * + "5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! + "sqrt kg^2)", // missing ( after sqrt + "( kg^2 m", // missing ) + "((((((((((((((((((((((((((((((((((((((((((((((((", NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST TEST static char prefs[] = "YZEPTGMkh dcmunpfazy"; static ul_number factors[] = { 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1, 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, }; size_t num_prefs = strlen(prefs); FATAL((sizeof(factors) / sizeof(factors[0])) != num_prefs); for (size_t i = 0; i < num_prefs; ++i) { char expr[128] = ""; snprintf(expr, 128, "5 %cm", prefs[i]); unit_t u; CHECK(ul_parse(expr, &u)); FAIL_MSG("Failed to parse: '%s' (%s)", expr, ul_error()); CHECK(ncmp(ul_factor(&u), 5 * factors[i]) == 0); FAIL_MSG("Factor: %g instead of %g (%c)", ul_factor(&u), 5 * factors[i], prefs[i]); // check kilogram, the only base unit with a prefix snprintf(expr, 128, "%cg", prefs[i]); CHECK(ul_parse(expr, &u)); } END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -1); unit_t test; CHECK(ul_parse("kg / s", &test)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&test, &correct)); correct.factor = 2.0; CHECK(ul_parse("8 kg / 4 s", &test)); CHECK(ul_equal(&test, &correct)); END_TEST GROUP("extended") - TEST - unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); - unit_t u; - - CHECK(ul_parse("sqrt(kg^2)", &u)); - CHECK(ul_equal(&u, &kg)); - char buffer[128]; - ul_snprint(buffer, 128, &u, UL_FMT_PLAIN, 0); - FAIL_MSG("Result was: %s", buffer); - END_TEST + TEST + unit_t kg = MAKE_UNIT(2.0, U_KILOGRAM, 1); + unit_t u; - SKIP_GROUP() + CHECK(ul_parse("sqrt(4 kg^2)", &u)); + CHECK(ul_equal(&u, &kg)); + char buffer[128]; + ul_snprint(buffer, 128, &u, UL_FMT_PLAIN, 0); + FAIL_MSG("Result was: %s", buffer); + END_TEST TEST unit_t u; CHECK(ul_parse("kg*m^2/(s^4 kg) sqrt(A^2 K^4)", &u)); END_TEST END_GROUP() END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t one_kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t five_kg = MAKE_UNIT(5.0, U_KILOGRAM, 1); CHECK(!ul_equal(&one_kg, &five_kg)); CHECK(ul_cmp(&one_kg, &five_kg) == UL_SAME_UNIT); unit_t five_sec = MAKE_UNIT(5.0, U_SECOND, 1); CHECK(ul_cmp(&five_kg, &five_sec) == UL_SAME_FACTOR); CHECK(ul_cmp(&one_kg, &five_sec) == UL_DIFFERENT); CHECK(ul_cmp(NULL, &one_kg) == UL_ERROR); CHECK(ul_cmp(&one_kg, NULL) == UL_ERROR); CHECK(ul_cmp(NULL, NULL) == UL_ERROR); /* UL_EQUAL result is tested by the previous test */ END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST TEST unit_t test = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, 5.0)); CHECK(ul_factor(&test) == 5.0); CHECK(ul_mult(&test, 1/5.0)); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, -1)); CHECK(ul_factor(&test) == -1.0); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_INLINE, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_FRAC, 0) == strlen(buffer)); FAIL_MSG("ul_length: %zu", ul_length(&N, UL_FMT_LATEX_FRAC, 0)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() TEST_SUITE(reduce) TEST CHECK(ul_parse_rule("N = 1 kg m s^-2")); unit_t N = MAKE_UNIT(1, U_KILOGRAM, 1, U_METER, 1, U_SECOND, -2); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "1 N") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); END_TEST END_TEST_SUITE() int main(void) { ul_debugging(true); ul_debugout("utest-debug.log", false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); USE_AUTO_FAIL(); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); RUN_SUITE(reduce); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define FATAL(expr) \ do { \ if (expr) { \ PRINT(_o, L_RESULT, "[%s%s-%d] Fatal: %s\n", _name, _group_name, _id, #expr); \ exit(1); \ } \ } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s%s-%d-%d] (%d) Fail: '%s'\n", _name, _group_name, _id, _this, __LINE__, #expr); \ _last = false;\ if (_o->autofail) _o->autofail(_name, _id, _this, #expr); \ } \ else { \ PRINT(_o, L_VERBOSE, "[%s%s-%d-%d] Pass: '%s'\n", _name, _group_name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define AUTO_FAIL \ static inline void _auto_fail(const char *Suite, int Test, int Check, const char *Expr) { #define END_AUTO_FAIL \ } #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ const char *_group_name = ""; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } #define GROUP(name) \ do { const char *_group_name = "-" name; int _test_id = 0; #define END_GROUP() \ } while (0); #define SKIP_GROUP() PRINT(_o, L_NORMAL, "[%s%s] skipped.\n", _name, _group_name); break; // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s%s-%d] failed with %d error%s.\n", _name, _group_name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s%s-%d] passed.\n", _name, _group_name, _id); \ } \ } // OTHER typedef struct { int loglvl; void (*autofail)(const char*,int,int,const char*); } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops = {L_RESULT,NULL}; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define USE_AUTO_FAIL() \ _ops.autofail = _auto_fail; #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
bd1c8771c915f1c5c3eb5425f70d5d7443b2ff9c
Started stack based parsing.
diff --git a/intern.h b/intern.h index c86c757..0b94cb1 100644 --- a/intern.h +++ b/intern.h @@ -1,59 +1,67 @@ #ifndef UL_INTERN_H #define UL_INTERN_H #include <float.h> #include <math.h> #include "unitlib.h" extern const char *_ul_symbols[]; extern size_t _ul_symlens[]; extern bool _ul_debugging; UL_LINKAGE void _ul_debug(const char *fmt, ...); #define debug(fmt,...) \ do { \ if (_ul_debugging) _ul_debug("[%s] " fmt "\n",\ __func__, ##__VA_ARGS__);\ } while(0) UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...); #define ERROR(msg, ...) _ul_set_error(__func__, __LINE__, msg, ##__VA_ARGS__) +#define DBG_UNIT_HDR " m kg s A K M Cd (L) - Factor" + +#define DBG_UNIT_FMT \ + "%3d %3d %3d %3d %3d %3d %3d %3d - " N_FMT + +#define DBG_UNIT_ARGS(u) \ + (u)->exps[0], (u)->exps[1], (u)->exps[2], (u)->exps[3], (u)->exps[4], (u)->exps[5], (u)->exps[6], (u)->exps[7], (u)->factor + UL_LINKAGE const char *_ul_reduce(const unit_t *unit); UL_LINKAGE bool _ul_init_parser(void); UL_LINKAGE void _ul_free_rules(void); #define EXPS_SIZE(unit) (sizeof((unit)->exps[0]) * NUM_BASE_UNITS) static inline void init_unit(unit_t *unit) { memset(unit->exps, 0, EXPS_SIZE(unit)); unit->factor = 1.0; } static inline void copy_unit(const unit_t *restrict src, unit_t *restrict dst) { memcpy(dst->exps, src->exps, EXPS_SIZE(dst)); dst->factor = src->factor; } static inline void add_unit(unit_t *restrict to, const unit_t *restrict other, int times) { for (int i=0; i < NUM_BASE_UNITS; ++i) { to->exps[i] += (times * other->exps[i]); } to->factor *= _pown(other->factor, times); } static inline int ncmp(ul_number a, ul_number b) { if (_fabsn(a-b) < N_EPSILON) return 0; if (a < b) return -1; return 1; } #endif /*UL_INTERN_H*/ \ No newline at end of file diff --git a/parser.c b/parser.c index 14a9396..a53aa20 100644 --- a/parser.c +++ b/parser.c @@ -1,650 +1,717 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" // My string.h is missing strdup so place it here. char *strdup(const char *s1); typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static prefix_t *prefixes = NULL; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) +enum { USTACK_SIZE = 16, }; + struct parser_state { int sign; + unit_t *unit; + unit_t ustack[USTACK_SIZE]; + size_t spos; + size_t in_sqrt; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; enum result { RS_ERROR, RS_HANDLED, RS_NOT_MINE, }; #define HANDLE_RESULT(marg_rs) \ do { \ enum result macro_rs = marg_rs; \ debug("rs: %d", macro_rs); \ if (macro_rs == RS_ERROR) { \ debug("%s == RS_ERROR", #marg_rs); \ return false; \ } \ if (macro_rs == RS_HANDLED) { \ debug("%s == RS_HANDLED", #marg_rs); \ return true; \ } \ assert(macro_rs == RS_NOT_MINE); \ debug("%s == RS_NOT_MINE", #marg_rs); \ } while (0); // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool splitchars[256] = { ['*'] = true, ['/'] = true, ['('] = true, [')'] = true, }; static inline bool issplit(char c) { return splitchars[(int)c]; } static size_t nextsplit(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !(isspace(text[i]) || issplit(text[i]))) i++; return i; } -static enum result handle_factor(const char *str, unit_t *unit, struct parser_state *state) +static enum result handle_factor(const char *str, struct parser_state *state) { - assert(str); assert(unit); assert(state); + assert(str); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { return RS_NOT_MINE; } debug("'%s' is a factor", str); - unit->factor *= _pown(f, state->sign); + state->unit->factor *= _pown(f, state->sign); + return RS_HANDLED; +} + +static bool push_unit(struct parser_state *state) +{ + state->spos++; + debug("Push: %u -> %u", state->spos-1, state->spos); + if (state->spos >= USTACK_SIZE) { + ERROR("Maximal nesting level exceeded."); + return false; + } + unit_t *prev = state->unit; + state->unit = &state->unit[state->spos]; + debug("Push: %p -> %p", prev, state->unit); + init_unit(state->unit); + return true; +} + +static bool pop_unit(struct parser_state *state) +{ + if (state->spos == 0) { + ERROR("Internal error: Stack missmatch!"); + return false; + } + unit_t *top = state->unit; + state->spos--; + + debug("Pop: %u -> %u", state->spos+1, state->spos); + debug("Units: top, top-1, result"); + debug(DBG_UNIT_HDR); + debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(top)); + state->unit = &state->unit[state->spos]; + debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(state->unit)); + add_unit(state->unit, top, 1); + debug(DBG_UNIT_FMT, DBG_UNIT_ARGS(state->unit)); + return true; +} + +static enum result handle_bracket_end(const char *str, struct parser_state *state) +{ + (void)str; + // TODO: add exp and sqrt support + if (!pop_unit(state)) + return RS_ERROR; return RS_HANDLED; } static enum result handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); debug("handle_special(%s)", str); switch (str[0]) { case '*': - case '(': - case ')': // ignore return RS_HANDLED; case '/': state->sign *= -1; return RS_HANDLED; - default: - return RS_NOT_MINE; + case '(': + if (!push_unit(state)) + return RS_ERROR; + return RS_HANDLED; + + case ')': + return handle_bracket_end(str, state); + } + + if (strcmp(str, "sqrt") == 0) { + debug("Found sqrt"); + state->in_sqrt++; + //if (!push_unit(state)) + // return RS_ERROR; + return RS_HANDLED; } + debug("not special!"); return RS_NOT_MINE; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } -static enum result handle_unit(const char *str, unit_t *unit, struct parser_state *state) +static enum result handle_unit(const char *str, struct parser_state *state) { - assert(str); assert(unit); assert(state); + assert(str); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return RS_ERROR; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return RS_ERROR; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return RS_ERROR; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return RS_ERROR; // And add the definitions - add_unit(unit, rule, exp); - unit->factor *= _pown(prefix, exp); + add_unit(state->unit, rule, exp); + state->unit->factor *= _pown(prefix, exp); return RS_HANDLED; } -static bool handle_item(const char *item, unit_t *unit, struct parser_state *state) +static bool handle_item(const char *item, struct parser_state *state) { HANDLE_RESULT(handle_special(item, state)); - HANDLE_RESULT(handle_factor(item, unit, state)); - HANDLE_RESULT(handle_unit(item, unit, state)); + HANDLE_RESULT(handle_factor(item, state)); + HANDLE_RESULT(handle_unit(item, state)); ERROR("Unknown item type for item '%s'", item); return false; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; + state.in_sqrt = 0; + state.unit = &state.ustack[0]; + state.spos = 0; - init_unit(unit); + init_unit(state.unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextsplit(str, start); debug("Start: %d", start); debug("End: %d", end); if (end == start) {// End of string if (end == len) break; end++; // this one is a split character } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; debug("Item is '%s'", this_item); // and handle it - if (!handle_item(this_item, unit, &state)) + if (!handle_item(this_item, &state)) return false; start = end; } while (start < len); + copy_unit(&state.ustack[0], unit); + return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } UL_LINKAGE const char *_ul_reduce(const unit_t *unit) { for (rule_t *cur = rules; cur; cur = cur->next) { if (ul_cmp(&cur->unit, unit) & UL_SAME_UNIT) return cur->symbol; } return NULL; } static bool kilogram_hack(void) { // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule(strdup("g"), &gram, true)) // strdup because add_rule expects malloc'd memory (it gets free'd at ul_quit) return false; return true; } static void free_rules(void) { rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } dynamic_rules = NULL; } static void free_prefixes(void) { prefix_t *pref = prefixes; while (pref) { prefix_t *next = pref->next; free(pref); pref = next; } prefixes = NULL; } UL_API bool ul_reset_rules(void) { free_rules(); kilogram_hack(); return true; } static bool init_prefixes(void) { debug("Initializing prefixes"); if (!add_prefix('Y', 1e24)) return false; if (!add_prefix('Z', 1e21)) return false; // zetta if (!add_prefix('E', 1e18)) return false; // exa if (!add_prefix('P', 1e15)) return false; // peta if (!add_prefix('T', 1e12)) return false; // tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca if (!add_prefix('d', 1e-1)) return false; // deci if (!add_prefix('c', 1e-2)) return false; // centi if (!add_prefix('m', 1e-3)) return false; // milli if (!add_prefix('u', 1e-6)) return false; // micro if (!add_prefix('n', 1e-9)) return false; // nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto debug("Prefixes initialized!"); return true; } UL_LINKAGE bool _ul_init_parser(void) { debug("Initializing parser"); for (int i=0; i < NUM_BASE_UNITS; ++i) { debug("Base rule: %d", i); base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; debug("Base rules initialized"); if (!kilogram_hack()) return false; if (!init_prefixes()) return false; debug("Parser initalized!"); return true; } UL_LINKAGE void _ul_free_rules(void) { free_rules(); free_prefixes(); } \ No newline at end of file diff --git a/unittest.c b/unittest.c index 8dcfb98..9ef58ce 100644 --- a/unittest.c +++ b/unittest.c @@ -1,615 +1,630 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) AUTO_FAIL printf("[%s-%d-%d] The test '%s' failed: \n[%s-%d-%d] Error message: %s\n", Suite, Test, Check, Expr, Suite, Test, Check, ul_error()); END_AUTO_FAIL TEST_SUITE(parser) GROUP("base") TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() GROUP("validation") TEST unit_t u; const char *strings[] = { //"5*kg^2", // need whitespace //"5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST TEST static char prefs[] = "YZEPTGMkh dcmunpfazy"; static ul_number factors[] = { 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1, 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, }; size_t num_prefs = strlen(prefs); FATAL((sizeof(factors) / sizeof(factors[0])) != num_prefs); for (size_t i = 0; i < num_prefs; ++i) { char expr[128] = ""; snprintf(expr, 128, "5 %cm", prefs[i]); unit_t u; CHECK(ul_parse(expr, &u)); FAIL_MSG("Failed to parse: '%s' (%s)", expr, ul_error()); CHECK(ncmp(ul_factor(&u), 5 * factors[i]) == 0); FAIL_MSG("Factor: %g instead of %g (%c)", ul_factor(&u), 5 * factors[i], prefs[i]); // check kilogram, the only base unit with a prefix snprintf(expr, 128, "%cg", prefs[i]); CHECK(ul_parse(expr, &u)); } END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -1); unit_t test; CHECK(ul_parse("kg / s", &test)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&test, &correct)); correct.factor = 2.0; CHECK(ul_parse("8 kg / 4 s", &test)); CHECK(ul_equal(&test, &correct)); END_TEST - //GROUP("extended") - // TEST - // unit_t u; - // CHECK(ul_parse("kg*m^2/(s^4 kg) sqrt(A^2 K^4)", &u)); - // END_TEST - //END_GROUP() + GROUP("extended") + TEST + unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); + unit_t u; + + CHECK(ul_parse("sqrt(kg^2)", &u)); + CHECK(ul_equal(&u, &kg)); + char buffer[128]; + ul_snprint(buffer, 128, &u, UL_FMT_PLAIN, 0); + FAIL_MSG("Result was: %s", buffer); + END_TEST + + SKIP_GROUP() + + TEST + unit_t u; + CHECK(ul_parse("kg*m^2/(s^4 kg) sqrt(A^2 K^4)", &u)); + END_TEST + END_GROUP() END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t one_kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t five_kg = MAKE_UNIT(5.0, U_KILOGRAM, 1); CHECK(!ul_equal(&one_kg, &five_kg)); CHECK(ul_cmp(&one_kg, &five_kg) == UL_SAME_UNIT); unit_t five_sec = MAKE_UNIT(5.0, U_SECOND, 1); CHECK(ul_cmp(&five_kg, &five_sec) == UL_SAME_FACTOR); CHECK(ul_cmp(&one_kg, &five_sec) == UL_DIFFERENT); CHECK(ul_cmp(NULL, &one_kg) == UL_ERROR); CHECK(ul_cmp(&one_kg, NULL) == UL_ERROR); CHECK(ul_cmp(NULL, NULL) == UL_ERROR); /* UL_EQUAL result is tested by the previous test */ END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST TEST unit_t test = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, 5.0)); CHECK(ul_factor(&test) == 5.0); CHECK(ul_mult(&test, 1/5.0)); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, -1)); CHECK(ul_factor(&test) == -1.0); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_INLINE, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_FRAC, 0) == strlen(buffer)); FAIL_MSG("ul_length: %zu", ul_length(&N, UL_FMT_LATEX_FRAC, 0)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() TEST_SUITE(reduce) TEST CHECK(ul_parse_rule("N = 1 kg m s^-2")); unit_t N = MAKE_UNIT(1, U_KILOGRAM, 1, U_METER, 1, U_SECOND, -2); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "1 N") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); END_TEST END_TEST_SUITE() int main(void) { ul_debugging(true); ul_debugout("utest-debug.log", false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); USE_AUTO_FAIL(); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); RUN_SUITE(reduce); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define FATAL(expr) \ do { \ if (expr) { \ PRINT(_o, L_RESULT, "[%s%s-%d] Fatal: %s\n", _name, _group_name, _id, #expr); \ exit(1); \ } \ } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s%s-%d-%d] (%d) Fail: '%s'\n", _name, _group_name, _id, _this, __LINE__, #expr); \ _last = false;\ if (_o->autofail) _o->autofail(_name, _id, _this, #expr); \ } \ else { \ PRINT(_o, L_VERBOSE, "[%s%s-%d-%d] Pass: '%s'\n", _name, _group_name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define AUTO_FAIL \ static inline void _auto_fail(const char *Suite, int Test, int Check, const char *Expr) { #define END_AUTO_FAIL \ } #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ const char *_group_name = ""; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } #define GROUP(name) \ - { const char *_group_name = "-" name; int _test_id = 0; + do { const char *_group_name = "-" name; int _test_id = 0; #define END_GROUP() \ - } + } while (0); + +#define SKIP_GROUP() PRINT(_o, L_NORMAL, "[%s%s] skipped.\n", _name, _group_name); break; // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s%s-%d] failed with %d error%s.\n", _name, _group_name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s%s-%d] passed.\n", _name, _group_name, _id); \ } \ } // OTHER typedef struct { int loglvl; void (*autofail)(const char*,int,int,const char*); } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops = {L_RESULT,NULL}; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define USE_AUTO_FAIL() \ _ops.autofail = _auto_fail; #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
0fef02a133ac7e632b72d3b175b29641193bc11d
More preparation, still passes most unittests. Failed tests: - [intentionally] No longer fails to parse "kg*m^2". This test will be removed. - [bug/feature?] No longer fails to parse "kg ** m^2". It's not yet decided, whether this effect is ok.
diff --git a/_test.c b/_test.c index 0b33dd2..0351092 100644 --- a/_test.c +++ b/_test.c @@ -1,147 +1,147 @@ #include <stdio.h> #include "unitlib.h" #ifndef SMASH int main(void) { printf("Testing %s\n", UL_FULL_NAME); ul_debugging(true); - ul_debugout("debug.log", false); + //ul_debugout("debug.log", false); if (!ul_init()) { printf("init failed"); } if (!ul_parse_rule(" N= 1 kg m s^-2 ")) { printf("Error: %s\n", ul_error()); } unit_t unit; if (!ul_parse("( 0.2 N^2 ) * 0.75 m^-1", &unit)) { printf("Error: %s\n", ul_error()); } printf("0.2 N^2 * 0.75 m^-1 = "); if (!ul_fprint(stdout, &unit, UL_FMT_PLAIN, 0)) { printf("Error: %s\n", ul_error()); } printf("\n"); char buffer[1024]; if (!ul_snprint(buffer, 1024, &unit, UL_FMT_PLAIN, 0)) { printf("Error: %s\n", ul_error()); } printf("snprint => '%s'\n", buffer); { printf("\n----------\n"); unit_t n; ul_parse("N", &n); printf("1 N = "); ul_print(&n, UL_FMT_PLAIN, UL_FOP_REDUCE); printf("\n----------\n\n"); } ul_print( &unit, UL_FMT_LATEX_FRAC, 0); printf("\n"); ul_print(&unit, UL_FMT_LATEX_INLINE, 0); printf("\n"); { unit_t unit; ul_parse("s^-1", &unit); printf("LaTeX: "); ul_print(&unit, UL_FMT_LATEX_FRAC, 0); printf("\n"); } { const char *u = "1 mg"; unit_t unit; if (!ul_parse(u, &unit)) printf("%s\n", ul_error()); printf("%s = ", u); ul_print(&unit, UL_FMT_PLAIN, 0); printf("\n"); } ul_quit(); return 0; } #else void smashit(const char *str, bool asRule) { bool ok = true; if (asRule) { ok = ul_parse_rule(str); } else { unit_t u; ok = ul_parse(str, &u); } if (ok) { fprintf(stderr, "successfull?\n"); } else { fprintf(stderr, "error: %s\n", ul_error()); } } int main(void) { ul_init(); srand(time(NULL)); { fprintf(stderr, "Smash 1: "); char test[] = "dil^aöjf lkfjda gäklj#ä#jadf klnhöklj213jl^^- kjäjre"; smashit(test, false); fprintf(stderr, "Smash 2: "); smashit(test, true); } { size_t size = 4096; int *_test = malloc(size); int i=0; for (; i < size / sizeof(int); ++i) { _test[i] = rand(); } char *test = (char*)_test; for (i=0; i < size; ++i) { if (!test[i]) test[i] = 42; } fprintf(stderr, "%4d bytes garbage: ", size ); smashit(test, false); fprintf(stderr, "as rule: "); smashit(test, true); } { char test[] = " \t\t\n\n\r kg = "; printf("Evil: "); smashit(test, true); } { char test[] = "kg^2!"; printf("test: "); ul_debugging(true); smashit(test, false); } return 0; } #endif diff --git a/parser.c b/parser.c index 1ac4b12..14a9396 100644 --- a/parser.c +++ b/parser.c @@ -1,620 +1,650 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" // My string.h is missing strdup so place it here. char *strdup(const char *s1); typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static prefix_t *prefixes = NULL; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; +enum result { + RS_ERROR, + RS_HANDLED, + RS_NOT_MINE, +}; +#define HANDLE_RESULT(marg_rs) \ + do { \ + enum result macro_rs = marg_rs; \ + debug("rs: %d", macro_rs); \ + if (macro_rs == RS_ERROR) { \ + debug("%s == RS_ERROR", #marg_rs); \ + return false; \ + } \ + if (macro_rs == RS_HANDLED) { \ + debug("%s == RS_HANDLED", #marg_rs); \ + return true; \ + } \ + assert(macro_rs == RS_NOT_MINE); \ + debug("%s == RS_NOT_MINE", #marg_rs); \ + } while (0); + // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } +static bool splitchars[256] = { + ['*'] = true, + ['/'] = true, + ['('] = true, + [')'] = true, +}; +static inline bool issplit(char c) +{ + return splitchars[(int)c]; +} + static size_t nextsplit(const char *text, size_t start) { assert(text); size_t i = start; - while (text[i] && !(isspace(text[i]) || text[i] == '*')) + while (text[i] && !(isspace(text[i]) || issplit(text[i]))) i++; return i; } -static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) +static enum result handle_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { - debug("'%s' is not a factor", str); - return false; + return RS_NOT_MINE; } + debug("'%s' is a factor", str); unit->factor *= _pown(f, state->sign); - return true; -} - -static bool is_special(const char *str) -{ - assert(str); - if (strlen(str) == 1) { - switch (str[0]) { - case '*': - // shall be ignored - return true; - case '/': - // change sign - return true; - } - } - return false; + return RS_HANDLED; } -static bool handle_special(const char *str, struct parser_state *state) +static enum result handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); + + debug("handle_special(%s)", str); switch (str[0]) { case '*': + case '(': + case ')': // ignore - return true; + return RS_HANDLED; case '/': state->sign *= -1; - return true; + return RS_HANDLED; + + default: + return RS_NOT_MINE; } - ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); - return false; + debug("not special!"); + return RS_NOT_MINE; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } -static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) +static enum result handle_unit(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); - return false; + return RS_ERROR; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); - return false; + return RS_ERROR; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); - return false; + return RS_ERROR; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) - return false; + return RS_ERROR; // And add the definitions add_unit(unit, rule, exp); unit->factor *= _pown(prefix, exp); - return true; + return RS_HANDLED; +} + +static bool handle_item(const char *item, unit_t *unit, struct parser_state *state) +{ + HANDLE_RESULT(handle_special(item, state)); + HANDLE_RESULT(handle_factor(item, unit, state)); + HANDLE_RESULT(handle_unit(item, unit, state)); + ERROR("Unknown item type for item '%s'", item); + return false; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace - size_t end = nextspace(str, start); + size_t end = nextsplit(str, start); + + debug("Start: %d", start); + debug("End: %d", end); if (end == start) {// End of string - break; + if (end == len) + break; + end++; // this one is a split character } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; - // and parse it - if (is_special(this_item)) { - if (!handle_special(this_item, &state)) - return false; - } - else if (try_parse_factor(this_item, unit, &state)) { - // nothing todo - } - else { - if (!parse_item(this_item, unit, &state)) - return false; - } + debug("Item is '%s'", this_item); + + // and handle it + if (!handle_item(this_item, unit, &state)) + return false; - start = end + 1; + start = end; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } UL_LINKAGE const char *_ul_reduce(const unit_t *unit) { for (rule_t *cur = rules; cur; cur = cur->next) { if (ul_cmp(&cur->unit, unit) & UL_SAME_UNIT) return cur->symbol; } return NULL; } static bool kilogram_hack(void) { // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule(strdup("g"), &gram, true)) // strdup because add_rule expects malloc'd memory (it gets free'd at ul_quit) return false; return true; } static void free_rules(void) { rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } dynamic_rules = NULL; } static void free_prefixes(void) { prefix_t *pref = prefixes; while (pref) { prefix_t *next = pref->next; free(pref); pref = next; } prefixes = NULL; } UL_API bool ul_reset_rules(void) { free_rules(); kilogram_hack(); return true; } static bool init_prefixes(void) { debug("Initializing prefixes"); if (!add_prefix('Y', 1e24)) return false; if (!add_prefix('Z', 1e21)) return false; // zetta if (!add_prefix('E', 1e18)) return false; // exa if (!add_prefix('P', 1e15)) return false; // peta if (!add_prefix('T', 1e12)) return false; // tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca if (!add_prefix('d', 1e-1)) return false; // deci if (!add_prefix('c', 1e-2)) return false; // centi if (!add_prefix('m', 1e-3)) return false; // milli if (!add_prefix('u', 1e-6)) return false; // micro if (!add_prefix('n', 1e-9)) return false; // nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto debug("Prefixes initialized!"); return true; } UL_LINKAGE bool _ul_init_parser(void) { debug("Initializing parser"); for (int i=0; i < NUM_BASE_UNITS; ++i) { debug("Base rule: %d", i); base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; debug("Base rules initialized"); if (!kilogram_hack()) return false; if (!init_prefixes()) return false; debug("Parser initalized!"); return true; } UL_LINKAGE void _ul_free_rules(void) { free_rules(); free_prefixes(); } \ No newline at end of file diff --git a/unittest.c b/unittest.c index daec2da..8dcfb98 100644 --- a/unittest.c +++ b/unittest.c @@ -1,607 +1,615 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) AUTO_FAIL printf("[%s-%d-%d] The test '%s' failed: \n[%s-%d-%d] Error message: %s\n", Suite, Test, Check, Expr, Suite, Test, Check, ul_error()); END_AUTO_FAIL TEST_SUITE(parser) GROUP("base") TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() GROUP("validation") TEST unit_t u; const char *strings[] = { - "5*kg^2", // need whitespace - "5 ** kg^2", // double * + //"5*kg^2", // need whitespace + //"5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST TEST static char prefs[] = "YZEPTGMkh dcmunpfazy"; static ul_number factors[] = { 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1, 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, }; size_t num_prefs = strlen(prefs); FATAL((sizeof(factors) / sizeof(factors[0])) != num_prefs); for (size_t i = 0; i < num_prefs; ++i) { char expr[128] = ""; snprintf(expr, 128, "5 %cm", prefs[i]); unit_t u; CHECK(ul_parse(expr, &u)); FAIL_MSG("Failed to parse: '%s' (%s)", expr, ul_error()); CHECK(ncmp(ul_factor(&u), 5 * factors[i]) == 0); FAIL_MSG("Factor: %g instead of %g (%c)", ul_factor(&u), 5 * factors[i], prefs[i]); // check kilogram, the only base unit with a prefix snprintf(expr, 128, "%cg", prefs[i]); CHECK(ul_parse(expr, &u)); } END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -1); unit_t test; CHECK(ul_parse("kg / s", &test)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&test, &correct)); correct.factor = 2.0; CHECK(ul_parse("8 kg / 4 s", &test)); CHECK(ul_equal(&test, &correct)); END_TEST + + //GROUP("extended") + // TEST + // unit_t u; + // CHECK(ul_parse("kg*m^2/(s^4 kg) sqrt(A^2 K^4)", &u)); + // END_TEST + //END_GROUP() END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t one_kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t five_kg = MAKE_UNIT(5.0, U_KILOGRAM, 1); CHECK(!ul_equal(&one_kg, &five_kg)); CHECK(ul_cmp(&one_kg, &five_kg) == UL_SAME_UNIT); unit_t five_sec = MAKE_UNIT(5.0, U_SECOND, 1); CHECK(ul_cmp(&five_kg, &five_sec) == UL_SAME_FACTOR); CHECK(ul_cmp(&one_kg, &five_sec) == UL_DIFFERENT); CHECK(ul_cmp(NULL, &one_kg) == UL_ERROR); CHECK(ul_cmp(&one_kg, NULL) == UL_ERROR); CHECK(ul_cmp(NULL, NULL) == UL_ERROR); /* UL_EQUAL result is tested by the previous test */ END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST TEST unit_t test = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, 5.0)); CHECK(ul_factor(&test) == 5.0); CHECK(ul_mult(&test, 1/5.0)); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, -1)); CHECK(ul_factor(&test) == -1.0); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_INLINE, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_FRAC, 0) == strlen(buffer)); FAIL_MSG("ul_length: %zu", ul_length(&N, UL_FMT_LATEX_FRAC, 0)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() TEST_SUITE(reduce) TEST CHECK(ul_parse_rule("N = 1 kg m s^-2")); unit_t N = MAKE_UNIT(1, U_KILOGRAM, 1, U_METER, 1, U_SECOND, -2); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "1 N") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); END_TEST END_TEST_SUITE() int main(void) { - ul_debugging(false); + ul_debugging(true); + ul_debugout("utest-debug.log", false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); USE_AUTO_FAIL(); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); RUN_SUITE(reduce); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define FATAL(expr) \ do { \ if (expr) { \ PRINT(_o, L_RESULT, "[%s%s-%d] Fatal: %s\n", _name, _group_name, _id, #expr); \ exit(1); \ } \ } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ - PRINT(_o, L_NORMAL, "[%s%s-%d-%d] Fail: '%s'\n", _name, _group_name, _id, _this, #expr); \ + PRINT(_o, L_NORMAL, "[%s%s-%d-%d] (%d) Fail: '%s'\n", _name, _group_name, _id, _this, __LINE__, #expr); \ _last = false;\ if (_o->autofail) _o->autofail(_name, _id, _this, #expr); \ } \ else { \ PRINT(_o, L_VERBOSE, "[%s%s-%d-%d] Pass: '%s'\n", _name, _group_name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define AUTO_FAIL \ static inline void _auto_fail(const char *Suite, int Test, int Check, const char *Expr) { #define END_AUTO_FAIL \ } #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ const char *_group_name = ""; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } #define GROUP(name) \ { const char *_group_name = "-" name; int _test_id = 0; #define END_GROUP() \ } // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s%s-%d] failed with %d error%s.\n", _name, _group_name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s%s-%d] passed.\n", _name, _group_name, _id); \ } \ } // OTHER typedef struct { int loglvl; void (*autofail)(const char*,int,int,const char*); } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops = {L_RESULT,NULL}; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define USE_AUTO_FAIL() \ _ops.autofail = _auto_fail; #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
99491632379577ac70a70b3e51f2121bb7e7f02e
Added nextsplit function, to find the next place to split.
diff --git a/parser.c b/parser.c index 0cc5923..1ac4b12 100644 --- a/parser.c +++ b/parser.c @@ -1,611 +1,620 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" // My string.h is missing strdup so place it here. char *strdup(const char *s1); typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static prefix_t *prefixes = NULL; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } +static size_t nextsplit(const char *text, size_t start) +{ + assert(text); + size_t i = start; + while (text[i] && !(isspace(text[i]) || text[i] == '*')) + i++; + return i; +} + static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= _pown(f, state->sign); return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': // shall be ignored return true; case '/': // change sign return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; // And add the definitions add_unit(unit, rule, exp); unit->factor *= _pown(prefix, exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } UL_LINKAGE const char *_ul_reduce(const unit_t *unit) { for (rule_t *cur = rules; cur; cur = cur->next) { if (ul_cmp(&cur->unit, unit) & UL_SAME_UNIT) return cur->symbol; } return NULL; } static bool kilogram_hack(void) { // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; if (!add_rule(strdup("g"), &gram, true)) // strdup because add_rule expects malloc'd memory (it gets free'd at ul_quit) return false; return true; } static void free_rules(void) { rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } dynamic_rules = NULL; } static void free_prefixes(void) { prefix_t *pref = prefixes; while (pref) { prefix_t *next = pref->next; free(pref); pref = next; } prefixes = NULL; } UL_API bool ul_reset_rules(void) { free_rules(); kilogram_hack(); return true; } static bool init_prefixes(void) { debug("Initializing prefixes"); if (!add_prefix('Y', 1e24)) return false; if (!add_prefix('Z', 1e21)) return false; // zetta if (!add_prefix('E', 1e18)) return false; // exa if (!add_prefix('P', 1e15)) return false; // peta if (!add_prefix('T', 1e12)) return false; // tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca if (!add_prefix('d', 1e-1)) return false; // deci if (!add_prefix('c', 1e-2)) return false; // centi if (!add_prefix('m', 1e-3)) return false; // milli if (!add_prefix('u', 1e-6)) return false; // micro if (!add_prefix('n', 1e-9)) return false; // nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto debug("Prefixes initialized!"); return true; } UL_LINKAGE bool _ul_init_parser(void) { debug("Initializing parser"); for (int i=0; i < NUM_BASE_UNITS; ++i) { debug("Base rule: %d", i); base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; debug("Base rules initialized"); if (!kilogram_hack()) return false; if (!init_prefixes()) return false; debug("Parser initalized!"); return true; } UL_LINKAGE void _ul_free_rules(void) { free_rules(); free_prefixes(); } \ No newline at end of file
jan-kuechler/unitlib
2bb2626553ce2084d8a12ce238bcf7b11c710c37
Just some comment cleanups
diff --git a/parser.c b/parser.c index 23f49dc..0cc5923 100644 --- a/parser.c +++ b/parser.c @@ -5,607 +5,607 @@ #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" // My string.h is missing strdup so place it here. char *strdup(const char *s1); typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static prefix_t *prefixes = NULL; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= _pown(f, state->sign); return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': // shall be ignored return true; case '/': // change sign return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; // And add the definitions add_unit(unit, rule, exp); unit->factor *= _pown(prefix, exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } UL_LINKAGE const char *_ul_reduce(const unit_t *unit) { for (rule_t *cur = rules; cur; cur = cur->next) { if (ul_cmp(&cur->unit, unit) & UL_SAME_UNIT) return cur->symbol; } return NULL; } static bool kilogram_hack(void) { // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; - if (!add_rule(strdup("g"), &gram, true)) // strdup because add_rule expects malloc'd memory (it gets free'd at ul_quit). + if (!add_rule(strdup("g"), &gram, true)) // strdup because add_rule expects malloc'd memory (it gets free'd at ul_quit) return false; return true; } static void free_rules(void) { rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } dynamic_rules = NULL; } static void free_prefixes(void) { prefix_t *pref = prefixes; while (pref) { prefix_t *next = pref->next; free(pref); pref = next; } prefixes = NULL; } UL_API bool ul_reset_rules(void) { free_rules(); kilogram_hack(); return true; } static bool init_prefixes(void) { debug("Initializing prefixes"); if (!add_prefix('Y', 1e24)) return false; - if (!add_prefix('Z', 1e21)) return false; //zetta - if (!add_prefix('E', 1e18)) return false; //exa - if (!add_prefix('P', 1e15)) return false; //peta - if (!add_prefix('T', 1e12)) return false; //tera + if (!add_prefix('Z', 1e21)) return false; // zetta + if (!add_prefix('E', 1e18)) return false; // exa + if (!add_prefix('P', 1e15)) return false; // peta + if (!add_prefix('T', 1e12)) return false; // tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca - if (!add_prefix('d', 1e-1)) return false; //deci - if (!add_prefix('c', 1e-2)) return false; //centi - if (!add_prefix('m', 1e-3)) return false; //milli - if (!add_prefix('u', 1e-6)) return false; //micro - if (!add_prefix('n', 1e-9)) return false; //nano + if (!add_prefix('d', 1e-1)) return false; // deci + if (!add_prefix('c', 1e-2)) return false; // centi + if (!add_prefix('m', 1e-3)) return false; // milli + if (!add_prefix('u', 1e-6)) return false; // micro + if (!add_prefix('n', 1e-9)) return false; // nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto debug("Prefixes initialized!"); return true; } UL_LINKAGE bool _ul_init_parser(void) { debug("Initializing parser"); for (int i=0; i < NUM_BASE_UNITS; ++i) { debug("Base rule: %d", i); base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; debug("Base rules initialized"); if (!kilogram_hack()) return false; if (!init_prefixes()) return false; debug("Parser initalized!"); return true; } UL_LINKAGE void _ul_free_rules(void) { free_rules(); free_prefixes(); } \ No newline at end of file
jan-kuechler/unitlib
7e13bb72854e9bd0f41f8339171a0bec6b995474
Don't display file and line in error messages if not debugging.
diff --git a/unitlib.c b/unitlib.c index 386d9f7..854305a 100644 --- a/unitlib.c +++ b/unitlib.c @@ -1,201 +1,204 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" #define static_assert(e) extern char (*STATIC_ASSERT(void))[sizeof(char[1 - 2*!(e)])] #define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) static FILE *dbg_out = NULL; bool _ul_debugging = false; UL_LINKAGE void _ul_debug(const char *fmt, ...) { assert(dbg_out); va_list ap; va_start(ap, fmt); vfprintf(dbg_out, fmt, ap); va_end(ap); } const char *_ul_symbols[] = { "m", "kg", "s", "A", "K", "mol", "Cd", "L", }; static_assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); // The last error message static char errmsg[1024]; UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) { - snprintf(errmsg, 1024, "[%s:%d] ", func, line); - size_t len = strlen(errmsg); + size_t len = 0; + if (_ul_debugging) { + snprintf(errmsg, 1024, "[%s:%d] ", func, line); + len = strlen(errmsg); + } va_list ap; va_start(ap, fmt); vsnprintf(errmsg + len, 1024 - len, fmt, ap); va_end(ap); } UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b) { if (!a || !b) { ERROR("Invalid parameters"); return UL_ERROR; } int res = UL_SAME_UNIT; for (int i=0; i < NUM_BASE_UNITS; ++i) { if (a->exps[i] != b->exps[i]) { res = 0; break; } } if (ncmp(a->factor, b->factor) == 0) { res |= UL_SAME_FACTOR; } return res; } UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with) { if (!unit || !with) { ERROR("Invalid parameter"); return false; } add_unit(unit, with, 1); return true; } UL_API bool ul_mult(unit_t *unit, ul_number factor) { if (!unit) { ERROR("Invalid parameter"); return false; } unit->factor *= factor; return true; } UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src) { if (!dst || !src) { ERROR("Invalid parameter"); return false; } copy_unit(src, dst); return true; } UL_API bool ul_inverse(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } if (ncmp(unit->factor, 0.0) == 0) { ERROR("Cannot inverse 0.0"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] = -unit->exps[i]; } unit->factor = 1/unit->factor; return true; } UL_API bool ul_sqrt(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { if ((unit->exps[i] % 2) != 0) { ERROR("Cannot take root of an odd exponent"); return false; } } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] /= 2; } unit->factor = _sqrtn(unit->factor); return true; } UL_API bool ul_reduceable(const unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } return _ul_reduce(unit) != NULL; } UL_API void ul_debugging(bool flag) { _ul_debugging = flag; } UL_API void ul_debugout(const char *path, bool append) { if (dbg_out && dbg_out != stderr) { debug("New debug file: %s", path ? path : "stderr"); fclose(dbg_out); } if (!path) { dbg_out = stderr; } else { dbg_out = fopen(path, append ? "a" : "w"); if (!dbg_out) { dbg_out = stderr; debug("Failed to open '%s' as debugout, using stderr.", path); } setvbuf(dbg_out, NULL, _IONBF, 0); } fprintf(dbg_out, "** unitlib - debug log **\n"); } UL_API const char *ul_error(void) { return errmsg; } UL_API const char *ul_get_name(void) { return UL_FULL_NAME; } UL_API const char *ul_get_version(void) { return UL_VERSION; } UL_API bool ul_init(void) { if(!dbg_out) dbg_out = stderr; debug("Initializing unitlib...."); if (!_ul_init_parser()) { return false; } debug("Init done!"); return true; } UL_API void ul_quit(void) { _ul_free_rules(); if (dbg_out && dbg_out != stderr) fclose(dbg_out); }
jan-kuechler/unitlib
63fd2a772c8b711b108c0adbdd9af32f59229edf
Fixed bug in ul_sqrt, return value is now true for success.
diff --git a/unitlib.c b/unitlib.c index 8ed3ed4..386d9f7 100644 --- a/unitlib.c +++ b/unitlib.c @@ -1,201 +1,201 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" #define static_assert(e) extern char (*STATIC_ASSERT(void))[sizeof(char[1 - 2*!(e)])] #define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) static FILE *dbg_out = NULL; bool _ul_debugging = false; UL_LINKAGE void _ul_debug(const char *fmt, ...) { assert(dbg_out); va_list ap; va_start(ap, fmt); vfprintf(dbg_out, fmt, ap); va_end(ap); } const char *_ul_symbols[] = { "m", "kg", "s", "A", "K", "mol", "Cd", "L", }; static_assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); // The last error message static char errmsg[1024]; UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) { snprintf(errmsg, 1024, "[%s:%d] ", func, line); size_t len = strlen(errmsg); va_list ap; va_start(ap, fmt); vsnprintf(errmsg + len, 1024 - len, fmt, ap); va_end(ap); } UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b) { if (!a || !b) { ERROR("Invalid parameters"); return UL_ERROR; } int res = UL_SAME_UNIT; for (int i=0; i < NUM_BASE_UNITS; ++i) { if (a->exps[i] != b->exps[i]) { res = 0; break; } } if (ncmp(a->factor, b->factor) == 0) { res |= UL_SAME_FACTOR; } return res; } UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with) { if (!unit || !with) { ERROR("Invalid parameter"); return false; } add_unit(unit, with, 1); return true; } UL_API bool ul_mult(unit_t *unit, ul_number factor) { if (!unit) { ERROR("Invalid parameter"); return false; } unit->factor *= factor; return true; } UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src) { if (!dst || !src) { ERROR("Invalid parameter"); return false; } copy_unit(src, dst); return true; } UL_API bool ul_inverse(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } if (ncmp(unit->factor, 0.0) == 0) { ERROR("Cannot inverse 0.0"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] = -unit->exps[i]; } unit->factor = 1/unit->factor; return true; } UL_API bool ul_sqrt(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { if ((unit->exps[i] % 2) != 0) { ERROR("Cannot take root of an odd exponent"); return false; } } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] /= 2; } unit->factor = _sqrtn(unit->factor); - return false; + return true; } UL_API bool ul_reduceable(const unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } return _ul_reduce(unit) != NULL; } UL_API void ul_debugging(bool flag) { _ul_debugging = flag; } UL_API void ul_debugout(const char *path, bool append) { if (dbg_out && dbg_out != stderr) { debug("New debug file: %s", path ? path : "stderr"); fclose(dbg_out); } if (!path) { dbg_out = stderr; } else { dbg_out = fopen(path, append ? "a" : "w"); if (!dbg_out) { dbg_out = stderr; debug("Failed to open '%s' as debugout, using stderr.", path); } setvbuf(dbg_out, NULL, _IONBF, 0); } fprintf(dbg_out, "** unitlib - debug log **\n"); } UL_API const char *ul_error(void) { return errmsg; } UL_API const char *ul_get_name(void) { return UL_FULL_NAME; } UL_API const char *ul_get_version(void) { return UL_VERSION; } UL_API bool ul_init(void) { if(!dbg_out) dbg_out = stderr; debug("Initializing unitlib...."); if (!_ul_init_parser()) { return false; } debug("Init done!"); return true; } UL_API void ul_quit(void) { _ul_free_rules(); if (dbg_out && dbg_out != stderr) fclose(dbg_out); }
jan-kuechler/unitlib
e4b7feb1fb12922ed8d6e142059e52a5fc293cb1
Some README corrections.
diff --git a/README b/README index 605d53d..1817481 100644 --- a/README +++ b/README @@ -1,50 +1,50 @@ unitlib - README + What is unitlib? Unitlib is a programming library written in C, that handles parsing, converting and formatting of SI units (http://en.wikipedia.org/wiki/SI). + Is there any documentation? Not yet, but you may look at the unitlib.h header where each function has a short description. + Features of unitlib * Parsing of complex unit definitions like "5 kg mm / 16 ns^2". * Extensible rule system to create new units (e.g. Newton: "N = kg m s^-2"). * Support for most of the SI prefixes, like nano, kilo, etc. * Output in three different forms: Plain text, LaTeX inline defintion and LaTeX fracs. * Output as a composed unit, e.g. "5 kg m / s^2" can be printed as "5 N". + Planed features * Parsing support for something like "N sqrt(m^2/s^2) * (A/s)^2". * Find best composed unit for unclear matches ("kg m^2 s^-2" -> "N m"). + What programs are using unitlib? At the moment unitlib is used by two programs: * slas2 for Mac OS X (http://sourceforge.net/projects/slas2/) * EinheitenRechner for Windows (http://github.com/borlox/EinheitenRechner/) + Author -At the moment unitlib is developed by Jan Küchler. +At the moment unitlib is developed by Jan Kuechler. Email: kuchen_ <at> gmx <dot> de (yep, that's an underscore right after 'kuchen'). + License At the moment unitlib has no license, so effectivly that says "all rights reserved". -It's planned to release the library under a open source license at some point, +It's planned to release the library under an open source license at some point, for the meantime just send me an email. For any further questions, ideas, or anything else (except spam (-;), please send me an email. diff --git a/unittest.c b/unittest.c index cf66efc..daec2da 100644 --- a/unittest.c +++ b/unittest.c @@ -1,607 +1,607 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) AUTO_FAIL printf("[%s-%d-%d] The test '%s' failed: \n[%s-%d-%d] Error message: %s\n", Suite, Test, Check, Expr, Suite, Test, Check, ul_error()); END_AUTO_FAIL TEST_SUITE(parser) GROUP("base") TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() GROUP("validation") TEST unit_t u; const char *strings[] = { "5*kg^2", // need whitespace "5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST END_GROUP() TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST TEST static char prefs[] = "YZEPTGMkh dcmunpfazy"; static ul_number factors[] = { 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1, 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, }; size_t num_prefs = strlen(prefs); FATAL((sizeof(factors) / sizeof(factors[0])) != num_prefs); for (size_t i = 0; i < num_prefs; ++i) { char expr[128] = ""; snprintf(expr, 128, "5 %cm", prefs[i]); unit_t u; CHECK(ul_parse(expr, &u)); FAIL_MSG("Failed to parse: '%s' (%s)", expr, ul_error()); CHECK(ncmp(ul_factor(&u), 5 * factors[i]) == 0); FAIL_MSG("Factor: %g instead of %g (%c)", ul_factor(&u), 5 * factors[i], prefs[i]); // check kilogram, the only base unit with a prefix snprintf(expr, 128, "%cg", prefs[i]); CHECK(ul_parse(expr, &u)); } END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -1); unit_t test; CHECK(ul_parse("kg / s", &test)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&test, &correct)); correct.factor = 2.0; CHECK(ul_parse("8 kg / 4 s", &test)); CHECK(ul_equal(&test, &correct)); END_TEST END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t one_kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t five_kg = MAKE_UNIT(5.0, U_KILOGRAM, 1); CHECK(!ul_equal(&one_kg, &five_kg)); CHECK(ul_cmp(&one_kg, &five_kg) == UL_SAME_UNIT); unit_t five_sec = MAKE_UNIT(5.0, U_SECOND, 1); CHECK(ul_cmp(&five_kg, &five_sec) == UL_SAME_FACTOR); CHECK(ul_cmp(&one_kg, &five_sec) == UL_DIFFERENT); CHECK(ul_cmp(NULL, &one_kg) == UL_ERROR); CHECK(ul_cmp(&one_kg, NULL) == UL_ERROR); CHECK(ul_cmp(NULL, NULL) == UL_ERROR); /* UL_EQUAL result is tested by the previous test */ END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST TEST unit_t test = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, 5.0)); CHECK(ul_factor(&test) == 5.0); CHECK(ul_mult(&test, 1/5.0)); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, -1)); CHECK(ul_factor(&test) == -1.0); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_INLINE, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_FRAC, 0) == strlen(buffer)); - FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_FRAC, 0)); + FAIL_MSG("ul_length: %zu", ul_length(&N, UL_FMT_LATEX_FRAC, 0)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() TEST_SUITE(reduce) TEST CHECK(ul_parse_rule("N = 1 kg m s^-2")); unit_t N = MAKE_UNIT(1, U_KILOGRAM, 1, U_METER, 1, U_SECOND, -2); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "1 N") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, UL_FOP_REDUCE)); CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); END_TEST END_TEST_SUITE() int main(void) { ul_debugging(false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); USE_AUTO_FAIL(); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); RUN_SUITE(reduce); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define FATAL(expr) \ do { \ if (expr) { \ PRINT(_o, L_RESULT, "[%s%s-%d] Fatal: %s\n", _name, _group_name, _id, #expr); \ exit(1); \ } \ } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s%s-%d-%d] Fail: '%s'\n", _name, _group_name, _id, _this, #expr); \ _last = false;\ if (_o->autofail) _o->autofail(_name, _id, _this, #expr); \ } \ else { \ PRINT(_o, L_VERBOSE, "[%s%s-%d-%d] Pass: '%s'\n", _name, _group_name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define AUTO_FAIL \ static inline void _auto_fail(const char *Suite, int Test, int Check, const char *Expr) { #define END_AUTO_FAIL \ } #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ const char *_group_name = ""; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } #define GROUP(name) \ { const char *_group_name = "-" name; int _test_id = 0; #define END_GROUP() \ } // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s%s-%d] failed with %d error%s.\n", _name, _group_name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s%s-%d] passed.\n", _name, _group_name, _id); \ } \ } // OTHER typedef struct { int loglvl; void (*autofail)(const char*,int,int,const char*); } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops = {L_RESULT,NULL}; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define USE_AUTO_FAIL() \ _ops.autofail = _auto_fail; #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
80685ce0ad6b05e721778734f51c64cc2ee5845e
Added README file.
diff --git a/README b/README new file mode 100644 index 0000000..605d53d --- /dev/null +++ b/README @@ -0,0 +1,50 @@ + + unitlib - README + ++ What is unitlib? + +Unitlib is a programming library written in C, that handles parsing, converting +and formatting of SI units (http://en.wikipedia.org/wiki/SI). + ++ Is there any documentation? + +Not yet, but you may look at the unitlib.h header where each function has a +short description. + ++ Features of unitlib + + * Parsing of complex unit definitions like "5 kg mm / 16 ns^2". + * Extensible rule system to create new units (e.g. Newton: "N = kg m s^-2"). + * Support for most of the SI prefixes, like nano, kilo, etc. + * Output in three different forms: Plain text, LaTeX inline defintion and + LaTeX fracs. + * Output as a composed unit, e.g. "5 kg m / s^2" can be printed as "5 N". + ++ Planed features + + * Parsing support for something like "N sqrt(m^2/s^2) * (A/s)^2". + * Find best composed unit for unclear matches ("kg m^2 s^-2" -> "N m"). + ++ What programs are using unitlib? + +At the moment unitlib is used by two programs: + * slas2 for Mac OS X (http://sourceforge.net/projects/slas2/) + * EinheitenRechner for Windows (http://github.com/borlox/EinheitenRechner/) + ++ Author + +At the moment unitlib is developed by Jan Küchler. +Email: kuchen_ <at> gmx <dot> de +(yep, that's an underscore right after 'kuchen'). + ++ License + +At the moment unitlib has no license, so effectivly that says "all rights +reserved". +It's planned to release the library under a open source license at some point, +for the meantime just send me an email. + + + +For any further questions, ideas, or anything else (except spam (-;), please +send me an email.
jan-kuechler/unitlib
030f3841f32557759a65802db514cd46d1f71370
Fixed a (sometimes) crashing bug in parser.c.
diff --git a/parser.c b/parser.c index f1ab52d..23f49dc 100644 --- a/parser.c +++ b/parser.c @@ -1,608 +1,611 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" +// My string.h is missing strdup so place it here. +char *strdup(const char *s1); + typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static prefix_t *prefixes = NULL; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= _pown(f, state->sign); return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': // shall be ignored return true; case '/': // change sign return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; // And add the definitions add_unit(unit, rule, exp); unit->factor *= _pown(prefix, exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } UL_LINKAGE const char *_ul_reduce(const unit_t *unit) { for (rule_t *cur = rules; cur; cur = cur->next) { if (ul_cmp(&cur->unit, unit) & UL_SAME_UNIT) return cur->symbol; } return NULL; } static bool kilogram_hack(void) { // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; - if (!add_rule("g", &gram, true)) + if (!add_rule(strdup("g"), &gram, true)) // strdup because add_rule expects malloc'd memory (it gets free'd at ul_quit). return false; return true; } static void free_rules(void) { rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } dynamic_rules = NULL; } static void free_prefixes(void) { prefix_t *pref = prefixes; while (pref) { prefix_t *next = pref->next; free(pref); pref = next; } prefixes = NULL; } UL_API bool ul_reset_rules(void) { free_rules(); kilogram_hack(); return true; } static bool init_prefixes(void) { debug("Initializing prefixes"); if (!add_prefix('Y', 1e24)) return false; if (!add_prefix('Z', 1e21)) return false; //zetta if (!add_prefix('E', 1e18)) return false; //exa if (!add_prefix('P', 1e15)) return false; //peta if (!add_prefix('T', 1e12)) return false; //tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca if (!add_prefix('d', 1e-1)) return false; //deci if (!add_prefix('c', 1e-2)) return false; //centi if (!add_prefix('m', 1e-3)) return false; //milli if (!add_prefix('u', 1e-6)) return false; //micro if (!add_prefix('n', 1e-9)) return false; //nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto debug("Prefixes initialized!"); return true; } UL_LINKAGE bool _ul_init_parser(void) { debug("Initializing parser"); for (int i=0; i < NUM_BASE_UNITS; ++i) { debug("Base rule: %d", i); base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; debug("Base rules initialized"); if (!kilogram_hack()) return false; if (!init_prefixes()) return false; debug("Parser initalized!"); return true; } UL_LINKAGE void _ul_free_rules(void) { free_rules(); free_prefixes(); } \ No newline at end of file
jan-kuechler/unitlib
02336116b86154c9f5ee12aae701a461a8714d24
Renamed R_* to RES_* to avoid naming conflics with unistd.h's R_OK.
diff --git a/format.c b/format.c index 379e8f5..e5394fb 100644 --- a/format.c +++ b/format.c @@ -1,389 +1,389 @@ #include <assert.h> #include <stdio.h> #include <string.h> #include "intern.h" #include "unitlib.h" struct status { bool (*put_char)(char c, void *info); void *info; const unit_t *unit; ul_format_t format; void *extra; }; enum result { - R_ERROR = 0, - R_FAIL, - R_OK, + RES_ERROR = 0, + RES_FAIL, + RES_OK, }; struct printer; typedef enum result (*print_all_f)(struct printer* p, struct status *stat); typedef bool (*print_fac_f)(struct status *stat, ul_number factor, bool *first); typedef bool (*print_sym_f)(struct status *stat, const char *sym, int exp, bool *first); struct printer { print_sym_f sym; print_fac_f fac; print_all_f normal; print_all_f reduce; const char *prefix; const char *postfix; }; struct f_info { FILE *out; }; static bool f_putc(char c, void *i) { struct f_info *info = i; return fputc(c, info->out) == c; } struct sn_info { char *buffer; int idx; int size; }; static bool sn_putc(char c, void *i) { struct sn_info *info = i; if (info->idx >= info->size) { return false; } info->buffer[info->idx++] = c; return true; } struct cnt_info { size_t count; }; static bool cnt_putc(char c, void *i) { (void)c; struct cnt_info *info = i; info->count++; return true; } #define _putc(s,c) (s)->put_char((c),(s)->info) #define CHECK(x) do { if (!(x)) return false; } while (0) -#define CHECK_R(x) do { if (!(x)) return R_ERROR; } while (0) +#define CHECK_R(x) do { if (!(x)) return RES_ERROR; } while (0) static bool _puts(struct status *s, const char *str) { while (*str) { char c = *str++; if (!_putc(s, c)) return false; } return true; } static bool _putd(struct status *stat, int n) { char buffer[1024]; snprintf(buffer, 1024, "%d", n); return _puts(stat, buffer); } static bool _putn(struct status *stat, ul_number n) { char buffer[1024]; snprintf(buffer, 1024, N_FMT, n); return _puts(stat, buffer); } static void getnexp(ul_number n, ul_number *mantissa, int *exp) { bool neg = false; if (n < 0) { neg = true; n = -n; } if ((ncmp(n, 10.0) == -1) && (ncmp(n, 1.0) == 1)) { *mantissa = neg ? -n : n; *exp = 0; return; } else if (ncmp(n, 10.0) > -1) { int e = 0; do { e++; n /= 10; } while (ncmp(n, 10.0) == 1); *exp = e; *mantissa = neg ? -n : n; } else if (ncmp(n, 1.0) < 1) { int e = 0; while (ncmp(n, 1.0) == -1) { e--; n *= 10; } *exp = e; *mantissa = neg ? -n : n; } } // global for testing purpose, it's not declared in the header void _ul_getnexp(ul_number n, ul_number *m, int *e) { getnexp(n, m, e); } static enum result p_lfrac(struct printer *p, struct status *stat) { if (p->prefix) CHECK_R(_puts(stat, p->prefix)); bool first = true; CHECK_R(_puts(stat, "\\frac{")); if (_fabsn(stat->unit->factor) >= 1) CHECK_R(p->fac(stat, stat->unit->factor, &first)); for (int i=0; i < NUM_BASE_UNITS; ++i) { if (stat->unit->exps[i] > 0) CHECK_R(p->sym(stat, _ul_symbols[i], stat->unit->exps[i], &first)); } if (first) CHECK_R(p->fac(stat, 1.0, &first)); CHECK_R(_puts(stat, "}{")); first = true; if (_fabsn(stat->unit->factor) < 1) CHECK_R(p->fac(stat, stat->unit->factor, &first)); for (int i=0; i < NUM_BASE_UNITS; ++i) { if (stat->unit->exps[i] < 0) CHECK_R(p->sym(stat, _ul_symbols[i], -stat->unit->exps[i], &first)); } if (first) CHECK_R(p->fac(stat, 1.0, &first)); CHECK_R(_putc(stat, '}')); if (p->postfix) CHECK_R(_puts(stat, p->postfix)); - return R_OK; + return RES_OK; } static bool p_plain_fac(struct status *stat, ul_number fac, bool *first) { if (!*first) CHECK(_putc(stat, ' ')); CHECK(_putn(stat, fac)); *first = false; return true; } static bool p_plain_sym(struct status *stat, const char *sym, int exp, bool *first) { if (!exp) return true; if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, sym)); if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putd(stat, exp)); } *first = false; return true; } static bool p_latex_fac(struct status *stat, ul_number fac, bool *first) { ul_number m; int e; getnexp(fac, &m, &e); if (!*first) CHECK(_putc(stat, ' ')); CHECK(_putn(stat, m)); if (e != 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } *first = false; return true; } static bool p_latex_sym(struct status *stat, const char *sym, int exp, bool *first) { if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, "\\text{")); if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, sym)); CHECK(_puts(stat, "}")); if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putc(stat, '{')); CHECK(_putd(stat, exp)); CHECK(_putc(stat, '}')); } if (first) *first = false; return true; } static enum result def_normal(struct printer *p, struct status *stat) { if (p->prefix) CHECK_R(_puts(stat, p->prefix)); bool first = true; CHECK_R(p->fac(stat, stat->unit->factor, &first)); for (int i=0; i < NUM_BASE_UNITS; ++i) { if (stat->unit->exps[i] != 0) CHECK_R(p->sym(stat, _ul_symbols[i], stat->unit->exps[i], &first)); } if (p->postfix) CHECK_R(_puts(stat, p->postfix)); - return R_OK; + return RES_OK; } static enum result def_reduce(struct printer *p, struct status *stat) { const char *sym = _ul_reduce(stat->unit); if (!sym) - return R_FAIL; + return RES_FAIL; if (p->prefix) CHECK_R(_puts(stat, p->prefix)); bool first = true; CHECK_R(p->fac(stat, stat->unit->factor, &first)); CHECK_R(p->sym(stat, sym, 1, &first)); if (p->postfix) CHECK_R(_puts(stat, p->postfix)); - return R_OK; + return RES_OK; } static struct printer printer[UL_NUM_FORMATS] = { [UL_FMT_PLAIN] = { .sym = p_plain_sym, .fac = p_plain_fac, .normal = def_normal, .reduce = def_reduce, .prefix = NULL, .postfix = NULL, }, [UL_FMT_LATEX_INLINE] = { .sym = p_latex_sym, .fac = p_latex_fac, .normal = def_normal, .reduce = def_reduce, .prefix = "$", .postfix = "$", }, [UL_FMT_LATEX_FRAC] = { .sym = p_latex_sym, .fac = p_latex_fac, .normal = p_lfrac, .reduce = def_reduce, .prefix = "$", .postfix = "$", }, }; static bool _print(struct status *stat, int opts) { if (stat->format >= UL_NUM_FORMATS) { ERROR("Invalid format: %d\n", stat->format); return false; } struct printer *p = &printer[stat->format]; print_all_f f = p->normal; if (opts & UL_FOP_REDUCE) { f = p->reduce; } enum result res = f(p, stat); - if (res == R_FAIL) + if (res == RES_FAIL) res = p->normal(p, stat); - return res == R_OK; + return res == RES_OK; } UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, int fops) { struct f_info info = { .out = f, }; struct status status = { .put_char = f_putc, .info = &info, .unit = unit, .format = format, .extra = NULL, }; return _print(&status, fops); } UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, int fops) { struct sn_info info = { .buffer = buffer, .size = buflen, .idx = 0, }; struct status status = { .put_char = sn_putc, .info = &info, .unit = unit, .format = format, .extra = NULL, }; memset(buffer, 0, buflen); return _print(&status, fops); } UL_API size_t ul_length(const unit_t *unit, ul_format_t format, int fops) { struct cnt_info info = {0}; struct status status = { .put_char = cnt_putc, .info = &info, .unit = unit, .format = format, .extra = NULL, }; _print(&status, fops); return info.count; }
jan-kuechler/unitlib
5bfe20c7421e4857134864acdb76a52bc872b42b
Extended test framework.
diff --git a/unittest.c b/unittest.c index ed12728..cf66efc 100644 --- a/unittest.c +++ b/unittest.c @@ -1,560 +1,607 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) +AUTO_FAIL + printf("[%s-%d-%d] The test '%s' failed: \n[%s-%d-%d] Error message: %s\n", Suite, Test, Check, Expr, Suite, Test, Check, ul_error()); +END_AUTO_FAIL + TEST_SUITE(parser) - TEST - unit_t u; - CHECK(ul_parse("m", &u)); - FAIL_MSG("Error: %s", ul_error()); - CHECK(u.exps[U_METER] == 1); - int i=0; - for (; i < NUM_BASE_UNITS; ++i) { - if (i != U_METER) { - CHECK(u.exps[i] == 0); + GROUP("base") + TEST + unit_t u; + CHECK(ul_parse("m", &u)); + FAIL_MSG("Error: %s", ul_error()); + CHECK(u.exps[U_METER] == 1); + + int i=0; + for (; i < NUM_BASE_UNITS; ++i) { + if (i != U_METER) { + CHECK(u.exps[i] == 0); + } } - } - - CHECK(ncmp(u.factor, 1.0) == 0); - END_TEST - - TEST - unit_t u; - CHECK(ul_parse(" \n kg^2 * m ", &u)); - FAIL_MSG("Error: %s", ul_error()); - CHECK(u.exps[U_KILOGRAM] == 2); - CHECK(u.exps[U_METER] == 1); - CHECK(u.exps[U_SECOND] == 0); - CHECK(ncmp(u.factor, 1.0) == 0); + CHECK(ncmp(u.factor, 1.0) == 0); + END_TEST - CHECK(ul_parse("2 Cd 7 s^-1", &u)); - FAIL_MSG("Error: %s", ul_error()); - CHECK(u.exps[U_CANDELA] == 1); - CHECK(u.exps[U_SECOND] == -1); - CHECK(ncmp(u.factor, 14.0) == 0); - - CHECK(ul_parse("", &u)); - int i=0; - for (; i < NUM_BASE_UNITS; ++i) { - CHECK(u.exps[i] == 0); - } - CHECK(ncmp(u.factor, 1.0) == 0); - END_TEST - - TEST - unit_t u; - - const char *strings[] = { - "5*kg^2", // need whitespace - "5 ** kg^2", // double * - "5! * kg^2", // ! - "5 * kg^2!", // ! - NULL - }; + TEST + unit_t u; - int i = 0; - while (strings[i]) { - CHECK(ul_parse(strings[i], &u) == false); - PASS_MSG("Error message: %s", ul_error()); - FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); - i++; - } - END_TEST + CHECK(ul_parse(" \n kg^2 * m ", &u)); + FAIL_MSG("Error: %s", ul_error()); + CHECK(u.exps[U_KILOGRAM] == 2); + CHECK(u.exps[U_METER] == 1); + CHECK(u.exps[U_SECOND] == 0); + CHECK(ncmp(u.factor, 1.0) == 0); + + CHECK(ul_parse("2 Cd 7 s^-1", &u)); + FAIL_MSG("Error: %s", ul_error()); + CHECK(u.exps[U_CANDELA] == 1); + CHECK(u.exps[U_SECOND] == -1); + CHECK(ncmp(u.factor, 14.0) == 0); + + CHECK(ul_parse("", &u)); + int i=0; + for (; i < NUM_BASE_UNITS; ++i) { + CHECK(u.exps[i] == 0); + } + CHECK(ncmp(u.factor, 1.0) == 0); + END_TEST + END_GROUP() - TEST - const char *strings[] = { - "", // empty rule - " =", // empty symbol - "16 = 16", // invalid rule - " a b = s ", // invalid symbol - " c == kg", // double = - "d = e", // unknown 'e' - " = kg", // empty symbol - NULL, - }; + GROUP("validation") + TEST + unit_t u; - int i=0; - while (strings[i]) { - CHECK(ul_parse_rule(strings[i]) == false); - PASS_MSG("Error message: %s", ul_error()); - FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); - i++; - } - END_TEST + const char *strings[] = { + "5*kg^2", // need whitespace + "5 ** kg^2", // double * + "5! * kg^2", // ! + "5 * kg^2!", // ! + NULL + }; + + int i = 0; + while (strings[i]) { + CHECK(ul_parse(strings[i], &u) == false); + PASS_MSG("Error message: %s", ul_error()); + FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); + i++; + } + END_TEST + + TEST + const char *strings[] = { + "", // empty rule + " =", // empty symbol + "16 = 16", // invalid rule + " a b = s ", // invalid symbol + " c == kg", // double = + "d = e", // unknown 'e' + " = kg", // empty symbol + NULL, + }; + + int i=0; + while (strings[i]) { + CHECK(ul_parse_rule(strings[i]) == false); + PASS_MSG("Error message: %s", ul_error()); + FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); + i++; + } + END_TEST - TEST - // Empty rules are allowed - CHECK(ul_parse_rule("EmptySymbol = ")); - FAIL_MSG("Error: %s", ul_error()); + TEST + unit_t u; - unit_t u; - CHECK(ul_parse("EmptySymbol", &u)); - FAIL_MSG("Error: %s", ul_error()); + CHECK(ul_parse(NULL, NULL) == false); + CHECK(ul_parse(NULL, &u) == false); + CHECK(ul_parse("kg", NULL) == false); - int i=0; - for (; i < NUM_BASE_UNITS; ++i) { - CHECK(u.exps[i] == 0); - } - CHECK(ncmp(u.factor, 1.0) == 0); - END_TEST + CHECK(ul_parse_rule(NULL) == false); + CHECK(ul_parse_rule("") == false); + END_TEST - TEST - unit_t u; + TEST + // Empty rules are allowed + CHECK(ul_parse_rule("EmptySymbol = ")); + FAIL_MSG("Error: %s", ul_error()); - CHECK(ul_parse(NULL, NULL) == false); - CHECK(ul_parse(NULL, &u) == false); - CHECK(ul_parse("kg", NULL) == false); + unit_t u; + CHECK(ul_parse("EmptySymbol", &u)); + FAIL_MSG("Error: %s", ul_error()); - CHECK(ul_parse_rule(NULL) == false); - CHECK(ul_parse_rule("") == false); - END_TEST + int i=0; + for (; i < NUM_BASE_UNITS; ++i) { + CHECK(u.exps[i] == 0); + } + CHECK(ncmp(u.factor, 1.0) == 0); + END_TEST + END_GROUP() TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST TEST static char prefs[] = "YZEPTGMkh dcmunpfazy"; static ul_number factors[] = { 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1, 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, }; size_t num_prefs = strlen(prefs); FATAL((sizeof(factors) / sizeof(factors[0])) != num_prefs); for (size_t i = 0; i < num_prefs; ++i) { char expr[128] = ""; snprintf(expr, 128, "5 %cm", prefs[i]); unit_t u; CHECK(ul_parse(expr, &u)); FAIL_MSG("Failed to parse: '%s' (%s)", expr, ul_error()); CHECK(ncmp(ul_factor(&u), 5 * factors[i]) == 0); FAIL_MSG("Factor: %g instead of %g (%c)", ul_factor(&u), 5 * factors[i], prefs[i]); // check kilogram, the only base unit with a prefix snprintf(expr, 128, "%cg", prefs[i]); CHECK(ul_parse(expr, &u)); } END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -1); unit_t test; CHECK(ul_parse("kg / s", &test)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&test, &correct)); correct.factor = 2.0; CHECK(ul_parse("8 kg / 4 s", &test)); CHECK(ul_equal(&test, &correct)); END_TEST END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t one_kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t five_kg = MAKE_UNIT(5.0, U_KILOGRAM, 1); CHECK(!ul_equal(&one_kg, &five_kg)); CHECK(ul_cmp(&one_kg, &five_kg) == UL_SAME_UNIT); unit_t five_sec = MAKE_UNIT(5.0, U_SECOND, 1); CHECK(ul_cmp(&five_kg, &five_sec) == UL_SAME_FACTOR); CHECK(ul_cmp(&one_kg, &five_sec) == UL_DIFFERENT); CHECK(ul_cmp(NULL, &one_kg) == UL_ERROR); CHECK(ul_cmp(&one_kg, NULL) == UL_ERROR); CHECK(ul_cmp(NULL, NULL) == UL_ERROR); /* UL_EQUAL result is tested by the previous test */ END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST TEST unit_t test = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, 5.0)); CHECK(ul_factor(&test) == 5.0); CHECK(ul_mult(&test, 1/5.0)); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, -1)); CHECK(ul_factor(&test) == -1.0); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_PLAIN, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_INLINE, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_FRAC, 0) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_FRAC, 0)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() +TEST_SUITE(reduce) + TEST + CHECK(ul_parse_rule("N = 1 kg m s^-2")); + + unit_t N = MAKE_UNIT(1, U_KILOGRAM, 1, U_METER, 1, U_SECOND, -2); + + char buffer[128]; + CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, UL_FOP_REDUCE)); + CHECK(strcmp(buffer, "1 N") == 0); + + CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, UL_FOP_REDUCE)); + CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); + + CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, UL_FOP_REDUCE)); + CHECK(strcmp(buffer, "$1 \\text{ N}$") == 0); + END_TEST +END_TEST_SUITE() + int main(void) { ul_debugging(false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); + USE_AUTO_FAIL(); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); + RUN_SUITE(reduce); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define FATAL(expr) \ do { \ if (expr) { \ - PRINT(_o, L_RESULT, "[%s-%d] Fatal: %s\n", _name, _id, #expr); \ + PRINT(_o, L_RESULT, "[%s%s-%d] Fatal: %s\n", _name, _group_name, _id, #expr); \ exit(1); \ } \ } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ - PRINT(_o, L_NORMAL, "[%s-%d-%d] Fail: '%s'\n", _name, _id, _this, #expr); \ + PRINT(_o, L_NORMAL, "[%s%s-%d-%d] Fail: '%s'\n", _name, _group_name, _id, _this, #expr); \ _last = false;\ + if (_o->autofail) _o->autofail(_name, _id, _this, #expr); \ } \ else { \ - PRINT(_o, L_VERBOSE, "[%s-%d-%d] Pass: '%s'\n", _name, _id, _this, #expr); \ + PRINT(_o, L_VERBOSE, "[%s%s-%d-%d] Pass: '%s'\n", _name, _group_name, _id, _this, #expr); \ _last = true; \ } \ } while (0) +#define AUTO_FAIL \ + static inline void _auto_fail(const char *Suite, int Test, int Check, const char *Expr) { + +#define END_AUTO_FAIL \ + } + #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE -#define TEST_SUITE(name) \ - int _test_##name(_tops *_o) { \ - const char *_name = #name; \ - int _fail = 0; \ - int _test_id = 0; \ +#define TEST_SUITE(name) \ + int _test_##name(_tops *_o) { \ + const char *_name = #name; \ + const char *_group_name = ""; \ + int _fail = 0; \ + int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } +#define GROUP(name) \ + { const char *_group_name = "-" name; int _test_id = 0; + +#define END_GROUP() \ + } + // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ - PRINT(_o, L_NORMAL, "[%s-%d] failed with %d error%s.\n", _name, _id, _err, _err > 1 ? "s" : ""); \ + PRINT(_o, L_NORMAL, "[%s%s-%d] failed with %d error%s.\n", _name, _group_name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ - PRINT(_o, L_NORMAL, "[%s-%d] passed.\n", _name, _id); \ + PRINT(_o, L_NORMAL, "[%s%s-%d] passed.\n", _name, _group_name, _id); \ } \ } // OTHER typedef struct { int loglvl; + void (*autofail)(const char*,int,int,const char*); } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ - _tops _ops; int _tres = 0; + _tops _ops = {L_RESULT,NULL}; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); +#define USE_AUTO_FAIL() \ + _ops.autofail = _auto_fail; + #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
8dd5042c2fbe11afb22a37cba22ddb88102defe0
Changed version to 0.4b3.
diff --git a/unitlib.h b/unitlib.h index 4ab5484..0dff234 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,258 +1,258 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" -#define UL_VERSION "0.4b2" +#define UL_VERSION "0.4b3" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif -#if defined(UL_EXPORT_DLL) -#define UL_API UL_LINKAGE __declspec(dllexport) __stdcall -#elif defined(UL_IMPORT_DLL) -#define UL_API UL_LINKAGE __declspec(dllimport) __stdcall -#else +//#if defined(UL_EXPORT_DLL) +//#define UL_API UL_LINKAGE __declspec(dllexport) __stdcall +//#elif defined(UL_IMPORT_DLL) +//#define UL_API UL_LINKAGE __declspec(dllimport) __stdcall +//#else #define UL_API UL_LINKAGE -#endif +//#endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN = 0, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, UL_NUM_FORMATS, } ul_format_t; typedef enum ul_cmpres { UL_DIFFERENT = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, UL_ERROR = 0xFF, } ul_cmpres_t; enum ul_fmtop { UL_FOP_REDUCE = 0x01, }; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the full name of unitlib, including the version * @return String in the form "unitlib-x.yz" */ UL_API const char *ul_get_name(void); /** * Returns the version of unitlib * @return String in the form "x.yz" */ UL_API const char *ul_get_version(void); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Checks whether a unit is reduceable to a composed unit * @param unit The unit * @return True if the unit is reduceable, false if not or if an error occured */ UL_API bool ul_reduceable(const unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, int fops); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, int fops) { return ul_fprint(stdout, unit, format, fops); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, int fops); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option * @param fops A bitmap containing UL_FOP_* flags * @return Length of the formated string */ UL_API size_t ul_length(const unit_t *unit, ul_format_t format, int fops); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
8395ec934271c7e379373bc5362bdae07f06043e
Added ul_reset_rules (not yet in the header).
diff --git a/parser.c b/parser.c index 5ec88b7..f1ab52d 100644 --- a/parser.c +++ b/parser.c @@ -1,585 +1,608 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static prefix_t *prefixes = NULL; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= _pown(f, state->sign); return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': // shall be ignored return true; case '/': // change sign return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; // And add the definitions add_unit(unit, rule, exp); unit->factor *= _pown(prefix, exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } UL_LINKAGE const char *_ul_reduce(const unit_t *unit) { for (rule_t *cur = rules; cur; cur = cur->next) { if (ul_cmp(&cur->unit, unit) & UL_SAME_UNIT) return cur->symbol; } return NULL; } +static bool kilogram_hack(void) +{ + // stupid inconsistend SI system... + unit_t gram = { + {[U_KILOGRAM] = 1}, + 1e-3, + }; + if (!add_rule("g", &gram, true)) + return false; + return true; +} + +static void free_rules(void) +{ + rule_t *cur = dynamic_rules; + while (cur) { + rule_t *next = cur->next; + free((char*)cur->symbol); + free(cur); + cur = next; + } + dynamic_rules = NULL; +} + +static void free_prefixes(void) +{ + prefix_t *pref = prefixes; + while (pref) { + prefix_t *next = pref->next; + free(pref); + pref = next; + } + prefixes = NULL; +} + +UL_API bool ul_reset_rules(void) +{ + free_rules(); + kilogram_hack(); + return true; +} + static bool init_prefixes(void) { debug("Initializing prefixes"); if (!add_prefix('Y', 1e24)) return false; if (!add_prefix('Z', 1e21)) return false; //zetta if (!add_prefix('E', 1e18)) return false; //exa if (!add_prefix('P', 1e15)) return false; //peta if (!add_prefix('T', 1e12)) return false; //tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca if (!add_prefix('d', 1e-1)) return false; //deci if (!add_prefix('c', 1e-2)) return false; //centi if (!add_prefix('m', 1e-3)) return false; //milli if (!add_prefix('u', 1e-6)) return false; //micro if (!add_prefix('n', 1e-9)) return false; //nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto debug("Prefixes initialized!"); return true; } UL_LINKAGE bool _ul_init_parser(void) { debug("Initializing parser"); for (int i=0; i < NUM_BASE_UNITS; ++i) { debug("Base rule: %d", i); base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; debug("Base rules initialized"); - // stupid inconsistend SI system... - unit_t gram = { - {[U_KILOGRAM] = 1}, - 1e-3, - }; - debug("Adding gram"); - if (!add_rule("g", &gram, true)) + if (!kilogram_hack()) return false; if (!init_prefixes()) return false; debug("Parser initalized!"); return true; } UL_LINKAGE void _ul_free_rules(void) { - debug("Freeing rule list"); - rule_t *cur = dynamic_rules; - while (cur) { - rule_t *next = cur->next; - free((char*)cur->symbol); - free(cur); - cur = next; - } - - prefix_t *pref = prefixes; - while (pref) { - prefix_t *next = pref->next; - free(pref); - pref = next; - } -} + free_rules(); + free_prefixes(); +} \ No newline at end of file diff --git a/unitlib.c b/unitlib.c index 40419a7..8ed3ed4 100644 --- a/unitlib.c +++ b/unitlib.c @@ -1,192 +1,201 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" #define static_assert(e) extern char (*STATIC_ASSERT(void))[sizeof(char[1 - 2*!(e)])] #define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) static FILE *dbg_out = NULL; bool _ul_debugging = false; UL_LINKAGE void _ul_debug(const char *fmt, ...) { assert(dbg_out); va_list ap; va_start(ap, fmt); vfprintf(dbg_out, fmt, ap); va_end(ap); } const char *_ul_symbols[] = { "m", "kg", "s", "A", "K", "mol", "Cd", "L", }; static_assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); // The last error message static char errmsg[1024]; UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) { snprintf(errmsg, 1024, "[%s:%d] ", func, line); size_t len = strlen(errmsg); va_list ap; va_start(ap, fmt); vsnprintf(errmsg + len, 1024 - len, fmt, ap); va_end(ap); } UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b) { if (!a || !b) { ERROR("Invalid parameters"); return UL_ERROR; } int res = UL_SAME_UNIT; for (int i=0; i < NUM_BASE_UNITS; ++i) { if (a->exps[i] != b->exps[i]) { res = 0; break; } } if (ncmp(a->factor, b->factor) == 0) { res |= UL_SAME_FACTOR; } return res; } UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with) { if (!unit || !with) { ERROR("Invalid parameter"); return false; } add_unit(unit, with, 1); return true; } UL_API bool ul_mult(unit_t *unit, ul_number factor) { if (!unit) { ERROR("Invalid parameter"); return false; } unit->factor *= factor; return true; } UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src) { if (!dst || !src) { ERROR("Invalid parameter"); return false; } copy_unit(src, dst); return true; } UL_API bool ul_inverse(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } if (ncmp(unit->factor, 0.0) == 0) { ERROR("Cannot inverse 0.0"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] = -unit->exps[i]; } unit->factor = 1/unit->factor; return true; } UL_API bool ul_sqrt(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { if ((unit->exps[i] % 2) != 0) { ERROR("Cannot take root of an odd exponent"); return false; } } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] /= 2; } unit->factor = _sqrtn(unit->factor); return false; } +UL_API bool ul_reduceable(const unit_t *unit) +{ + if (!unit) { + ERROR("Invalid parameter"); + return false; + } + return _ul_reduce(unit) != NULL; +} + UL_API void ul_debugging(bool flag) { _ul_debugging = flag; } UL_API void ul_debugout(const char *path, bool append) { if (dbg_out && dbg_out != stderr) { debug("New debug file: %s", path ? path : "stderr"); fclose(dbg_out); } if (!path) { dbg_out = stderr; } else { dbg_out = fopen(path, append ? "a" : "w"); if (!dbg_out) { dbg_out = stderr; debug("Failed to open '%s' as debugout, using stderr.", path); } setvbuf(dbg_out, NULL, _IONBF, 0); } fprintf(dbg_out, "** unitlib - debug log **\n"); } UL_API const char *ul_error(void) { return errmsg; } UL_API const char *ul_get_name(void) { return UL_FULL_NAME; } UL_API const char *ul_get_version(void) { return UL_VERSION; } UL_API bool ul_init(void) { if(!dbg_out) dbg_out = stderr; debug("Initializing unitlib...."); if (!_ul_init_parser()) { return false; } debug("Init done!"); return true; } UL_API void ul_quit(void) { _ul_free_rules(); if (dbg_out && dbg_out != stderr) fclose(dbg_out); } diff --git a/unitlib.h b/unitlib.h index 6f7162d..4ab5484 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,251 +1,258 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" #define UL_VERSION "0.4b2" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) __stdcall #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) __stdcall #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN = 0, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, UL_NUM_FORMATS, } ul_format_t; typedef enum ul_cmpres { UL_DIFFERENT = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, UL_ERROR = 0xFF, } ul_cmpres_t; enum ul_fmtop { UL_FOP_REDUCE = 0x01, }; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the full name of unitlib, including the version * @return String in the form "unitlib-x.yz" */ UL_API const char *ul_get_name(void); /** * Returns the version of unitlib * @return String in the form "x.yz" */ UL_API const char *ul_get_version(void); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); +/** + * Checks whether a unit is reduceable to a composed unit + * @param unit The unit + * @return True if the unit is reduceable, false if not or if an error occured + */ +UL_API bool ul_reduceable(const unit_t *unit); + /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, int fops); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, int fops) { return ul_fprint(stdout, unit, format, fops); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fops A bitmap containing UL_FOP_* flags * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, int fops); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option * @param fops A bitmap containing UL_FOP_* flags * @return Length of the formated string */ UL_API size_t ul_length(const unit_t *unit, ul_format_t format, int fops); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
8fedf109bf5413925c9437c3ca768fac57b7d99c
Added one parameter to the ul_*print function family: fop. Added UL_FOP_REDUCE flag, to reduce a unit to the smallest form.
diff --git a/_test.c b/_test.c index 27cf78e..0b33dd2 100644 --- a/_test.c +++ b/_test.c @@ -1,156 +1,147 @@ #include <stdio.h> #include "unitlib.h" #ifndef SMASH int main(void) { printf("Testing %s\n", UL_FULL_NAME); ul_debugging(true); ul_debugout("debug.log", false); if (!ul_init()) { printf("init failed"); } if (!ul_parse_rule(" N= 1 kg m s^-2 ")) { printf("Error: %s\n", ul_error()); } unit_t unit; if (!ul_parse("( 0.2 N^2 ) * 0.75 m^-1", &unit)) { printf("Error: %s\n", ul_error()); } - - ul_fmtops_t fmtop; - fmtop.sort = true; - fmtop.order[0] = U_LEMMING; - fmtop.order[1] = U_KILOGRAM; - fmtop.order[2] = U_METER; - fmtop.order[3] = U_ANY; - printf("0.2 N^2 * 0.75 m^-1 = "); - if (!ul_fprint(stdout, &unit, UL_FMT_PLAIN, &fmtop)) { + if (!ul_fprint(stdout, &unit, UL_FMT_PLAIN, 0)) { printf("Error: %s\n", ul_error()); } printf("\n"); char buffer[1024]; - if (!ul_snprint(buffer, 1024, &unit, UL_FMT_PLAIN, NULL)) { + if (!ul_snprint(buffer, 1024, &unit, UL_FMT_PLAIN, 0)) { printf("Error: %s\n", ul_error()); } printf("snprint => '%s'\n", buffer); { printf("\n----------\n"); - fmtop.order[2] = U_ANY; unit_t n; ul_parse("N", &n); printf("1 N = "); - ul_print(&n, UL_FMT_PLAIN, &fmtop); + ul_print(&n, UL_FMT_PLAIN, UL_FOP_REDUCE); printf("\n----------\n\n"); } - ul_print( &unit, UL_FMT_LATEX_FRAC, &fmtop); + ul_print( &unit, UL_FMT_LATEX_FRAC, 0); printf("\n"); - ul_print(&unit, UL_FMT_LATEX_INLINE, NULL); + ul_print(&unit, UL_FMT_LATEX_INLINE, 0); printf("\n"); { unit_t unit; ul_parse("s^-1", &unit); printf("LaTeX: "); - ul_print(&unit, UL_FMT_LATEX_FRAC, NULL); + ul_print(&unit, UL_FMT_LATEX_FRAC, 0); printf("\n"); } { const char *u = "1 mg"; unit_t unit; if (!ul_parse(u, &unit)) printf("%s\n", ul_error()); printf("%s = ", u); - ul_print(&unit, UL_FMT_PLAIN, NULL); + ul_print(&unit, UL_FMT_PLAIN, 0); printf("\n"); } ul_quit(); return 0; } #else void smashit(const char *str, bool asRule) { bool ok = true; if (asRule) { ok = ul_parse_rule(str); } else { unit_t u; ok = ul_parse(str, &u); } if (ok) { fprintf(stderr, "successfull?\n"); } else { fprintf(stderr, "error: %s\n", ul_error()); } } int main(void) { ul_init(); srand(time(NULL)); { fprintf(stderr, "Smash 1: "); char test[] = "dil^aöjf lkfjda gäklj#ä#jadf klnhöklj213jl^^- kjäjre"; smashit(test, false); fprintf(stderr, "Smash 2: "); smashit(test, true); } { size_t size = 4096; int *_test = malloc(size); int i=0; for (; i < size / sizeof(int); ++i) { _test[i] = rand(); } char *test = (char*)_test; for (i=0; i < size; ++i) { if (!test[i]) test[i] = 42; } fprintf(stderr, "%4d bytes garbage: ", size ); smashit(test, false); fprintf(stderr, "as rule: "); smashit(test, true); } { char test[] = " \t\t\n\n\r kg = "; printf("Evil: "); smashit(test, true); } { char test[] = "kg^2!"; printf("test: "); ul_debugging(true); smashit(test, false); } return 0; } #endif diff --git a/format.c b/format.c index 81af6df..379e8f5 100644 --- a/format.c +++ b/format.c @@ -1,357 +1,389 @@ #include <assert.h> #include <stdio.h> #include <string.h> #include "intern.h" #include "unitlib.h" struct status { bool (*put_char)(char c, void *info); void *info; const unit_t *unit; ul_format_t format; void *extra; }; +enum result +{ + R_ERROR = 0, + R_FAIL, + R_OK, +}; + struct printer; -typedef bool (*print_all_f)(struct printer* p, struct status *stat); +typedef enum result (*print_all_f)(struct printer* p, struct status *stat); typedef bool (*print_fac_f)(struct status *stat, ul_number factor, bool *first); typedef bool (*print_sym_f)(struct status *stat, const char *sym, int exp, bool *first); struct printer { print_sym_f sym; print_fac_f fac; print_all_f normal; print_all_f reduce; const char *prefix; const char *postfix; }; struct f_info { FILE *out; }; static bool f_putc(char c, void *i) { struct f_info *info = i; return fputc(c, info->out) == c; } struct sn_info { char *buffer; int idx; int size; }; static bool sn_putc(char c, void *i) { struct sn_info *info = i; if (info->idx >= info->size) { return false; } info->buffer[info->idx++] = c; return true; } struct cnt_info { size_t count; }; static bool cnt_putc(char c, void *i) { (void)c; struct cnt_info *info = i; info->count++; return true; } #define _putc(s,c) (s)->put_char((c),(s)->info) #define CHECK(x) do { if (!(x)) return false; } while (0) +#define CHECK_R(x) do { if (!(x)) return R_ERROR; } while (0) + static bool _puts(struct status *s, const char *str) { while (*str) { char c = *str++; if (!_putc(s, c)) return false; } return true; } static bool _putd(struct status *stat, int n) { char buffer[1024]; snprintf(buffer, 1024, "%d", n); return _puts(stat, buffer); } static bool _putn(struct status *stat, ul_number n) { char buffer[1024]; snprintf(buffer, 1024, N_FMT, n); return _puts(stat, buffer); } static void getnexp(ul_number n, ul_number *mantissa, int *exp) { bool neg = false; if (n < 0) { neg = true; n = -n; } if ((ncmp(n, 10.0) == -1) && (ncmp(n, 1.0) == 1)) { *mantissa = neg ? -n : n; *exp = 0; return; } else if (ncmp(n, 10.0) > -1) { int e = 0; do { e++; n /= 10; } while (ncmp(n, 10.0) == 1); *exp = e; *mantissa = neg ? -n : n; } else if (ncmp(n, 1.0) < 1) { int e = 0; while (ncmp(n, 1.0) == -1) { e--; n *= 10; } *exp = e; *mantissa = neg ? -n : n; } } // global for testing purpose, it's not declared in the header void _ul_getnexp(ul_number n, ul_number *m, int *e) { getnexp(n, m, e); } -static bool p_lfrac(struct printer *p, struct status *stat) +static enum result p_lfrac(struct printer *p, struct status *stat) { if (p->prefix) - CHECK(_puts(stat, p->prefix)); + CHECK_R(_puts(stat, p->prefix)); bool first = true; - CHECK(_puts(stat, "\\frac{")); + CHECK_R(_puts(stat, "\\frac{")); if (_fabsn(stat->unit->factor) >= 1) - CHECK(p->fac(stat, stat->unit->factor, &first)); + CHECK_R(p->fac(stat, stat->unit->factor, &first)); for (int i=0; i < NUM_BASE_UNITS; ++i) { if (stat->unit->exps[i] > 0) - CHECK(p->sym(stat, _ul_symbols[i], stat->unit->exps[i], &first)); + CHECK_R(p->sym(stat, _ul_symbols[i], stat->unit->exps[i], &first)); } if (first) - CHECK(p->fac(stat, 1.0, &first)); + CHECK_R(p->fac(stat, 1.0, &first)); - CHECK(_puts(stat, "}{")); + CHECK_R(_puts(stat, "}{")); first = true; if (_fabsn(stat->unit->factor) < 1) - CHECK(p->fac(stat, stat->unit->factor, &first)); + CHECK_R(p->fac(stat, stat->unit->factor, &first)); for (int i=0; i < NUM_BASE_UNITS; ++i) { if (stat->unit->exps[i] < 0) - CHECK(p->sym(stat, _ul_symbols[i], -stat->unit->exps[i], &first)); + CHECK_R(p->sym(stat, _ul_symbols[i], -stat->unit->exps[i], &first)); } if (first) - CHECK(p->fac(stat, 1.0, &first)); + CHECK_R(p->fac(stat, 1.0, &first)); - CHECK(_putc(stat, '}')); + CHECK_R(_putc(stat, '}')); if (p->postfix) - CHECK(_puts(stat, p->postfix)); + CHECK_R(_puts(stat, p->postfix)); - return true; + return R_OK; } static bool p_plain_fac(struct status *stat, ul_number fac, bool *first) { if (!*first) CHECK(_putc(stat, ' ')); CHECK(_putn(stat, fac)); *first = false; return true; } static bool p_plain_sym(struct status *stat, const char *sym, int exp, bool *first) { if (!exp) return true; if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, sym)); if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putd(stat, exp)); } *first = false; return true; } static bool p_latex_fac(struct status *stat, ul_number fac, bool *first) { ul_number m; int e; getnexp(fac, &m, &e); if (!*first) CHECK(_putc(stat, ' ')); CHECK(_putn(stat, m)); if (e != 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } *first = false; return true; } static bool p_latex_sym(struct status *stat, const char *sym, int exp, bool *first) { if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, "\\text{")); if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, sym)); CHECK(_puts(stat, "}")); if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putc(stat, '{')); CHECK(_putd(stat, exp)); CHECK(_putc(stat, '}')); } if (first) *first = false; return true; } -static bool def_normal(struct printer *p, struct status *stat) +static enum result def_normal(struct printer *p, struct status *stat) { if (p->prefix) - CHECK(_puts(stat, p->prefix)); + CHECK_R(_puts(stat, p->prefix)); bool first = true; - CHECK(p->fac(stat, stat->unit->factor, &first)); + CHECK_R(p->fac(stat, stat->unit->factor, &first)); for (int i=0; i < NUM_BASE_UNITS; ++i) { if (stat->unit->exps[i] != 0) - CHECK(p->sym(stat, _ul_symbols[i], stat->unit->exps[i], &first)); + CHECK_R(p->sym(stat, _ul_symbols[i], stat->unit->exps[i], &first)); } if (p->postfix) - CHECK(_puts(stat, p->postfix)); + CHECK_R(_puts(stat, p->postfix)); - return true; + return R_OK; } -static bool def_reduce(struct printer *p, struct status *stat) +static enum result def_reduce(struct printer *p, struct status *stat) { - return false; + const char *sym = _ul_reduce(stat->unit); + if (!sym) + return R_FAIL; + + if (p->prefix) + CHECK_R(_puts(stat, p->prefix)); + + bool first = true; + CHECK_R(p->fac(stat, stat->unit->factor, &first)); + CHECK_R(p->sym(stat, sym, 1, &first)); + + if (p->postfix) + CHECK_R(_puts(stat, p->postfix)); + + return R_OK; } static struct printer printer[UL_NUM_FORMATS] = { [UL_FMT_PLAIN] = { .sym = p_plain_sym, .fac = p_plain_fac, .normal = def_normal, .reduce = def_reduce, .prefix = NULL, .postfix = NULL, }, [UL_FMT_LATEX_INLINE] = { .sym = p_latex_sym, .fac = p_latex_fac, .normal = def_normal, .reduce = def_reduce, .prefix = "$", .postfix = "$", }, [UL_FMT_LATEX_FRAC] = { .sym = p_latex_sym, .fac = p_latex_fac, .normal = p_lfrac, .reduce = def_reduce, .prefix = "$", .postfix = "$", }, }; -static bool _print(struct status *stat) +static bool _print(struct status *stat, int opts) { if (stat->format >= UL_NUM_FORMATS) { ERROR("Invalid format: %d\n", stat->format); return false; } struct printer *p = &printer[stat->format]; - return p->normal(p, stat); + + print_all_f f = p->normal; + if (opts & UL_FOP_REDUCE) { + f = p->reduce; + } + + enum result res = f(p, stat); + if (res == R_FAIL) + res = p->normal(p, stat); + return res == R_OK; } -UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format) +UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, int fops) { struct f_info info = { .out = f, }; struct status status = { .put_char = f_putc, .info = &info, .unit = unit, .format = format, .extra = NULL, }; - return _print(&status); + return _print(&status, fops); } -UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format) +UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, int fops) { struct sn_info info = { .buffer = buffer, .size = buflen, .idx = 0, }; struct status status = { .put_char = sn_putc, .info = &info, .unit = unit, .format = format, .extra = NULL, }; memset(buffer, 0, buflen); - return _print(&status); + return _print(&status, fops); } -UL_API size_t ul_length(const unit_t *unit, ul_format_t format) +UL_API size_t ul_length(const unit_t *unit, ul_format_t format, int fops) { struct cnt_info info = {0}; struct status status = { .put_char = cnt_putc, .info = &info, .unit = unit, .format = format, .extra = NULL, }; - _print(&status); + _print(&status, fops); return info.count; } diff --git a/intern.h b/intern.h index ff17a8d..c86c757 100644 --- a/intern.h +++ b/intern.h @@ -1,57 +1,59 @@ #ifndef UL_INTERN_H #define UL_INTERN_H #include <float.h> #include <math.h> #include "unitlib.h" extern const char *_ul_symbols[]; extern size_t _ul_symlens[]; extern bool _ul_debugging; UL_LINKAGE void _ul_debug(const char *fmt, ...); #define debug(fmt,...) \ do { \ if (_ul_debugging) _ul_debug("[%s] " fmt "\n",\ __func__, ##__VA_ARGS__);\ } while(0) UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...); #define ERROR(msg, ...) _ul_set_error(__func__, __LINE__, msg, ##__VA_ARGS__) +UL_LINKAGE const char *_ul_reduce(const unit_t *unit); + UL_LINKAGE bool _ul_init_parser(void); UL_LINKAGE void _ul_free_rules(void); #define EXPS_SIZE(unit) (sizeof((unit)->exps[0]) * NUM_BASE_UNITS) static inline void init_unit(unit_t *unit) { memset(unit->exps, 0, EXPS_SIZE(unit)); unit->factor = 1.0; } static inline void copy_unit(const unit_t *restrict src, unit_t *restrict dst) { memcpy(dst->exps, src->exps, EXPS_SIZE(dst)); dst->factor = src->factor; } static inline void add_unit(unit_t *restrict to, const unit_t *restrict other, int times) { for (int i=0; i < NUM_BASE_UNITS; ++i) { to->exps[i] += (times * other->exps[i]); } to->factor *= _pown(other->factor, times); } static inline int ncmp(ul_number a, ul_number b) { if (_fabsn(a-b) < N_EPSILON) return 0; if (a < b) return -1; return 1; } -#endif /*UL_INTERN_H*/ +#endif /*UL_INTERN_H*/ \ No newline at end of file diff --git a/parser.c b/parser.c index aebb334..5ec88b7 100644 --- a/parser.c +++ b/parser.c @@ -1,576 +1,585 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static prefix_t *prefixes = NULL; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= _pown(f, state->sign); return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': // shall be ignored return true; case '/': // change sign return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; // And add the definitions add_unit(unit, rule, exp); unit->factor *= _pown(prefix, exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } +UL_LINKAGE const char *_ul_reduce(const unit_t *unit) +{ + for (rule_t *cur = rules; cur; cur = cur->next) { + if (ul_cmp(&cur->unit, unit) & UL_SAME_UNIT) + return cur->symbol; + } + return NULL; +} + static bool init_prefixes(void) { debug("Initializing prefixes"); if (!add_prefix('Y', 1e24)) return false; if (!add_prefix('Z', 1e21)) return false; //zetta if (!add_prefix('E', 1e18)) return false; //exa if (!add_prefix('P', 1e15)) return false; //peta if (!add_prefix('T', 1e12)) return false; //tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca if (!add_prefix('d', 1e-1)) return false; //deci if (!add_prefix('c', 1e-2)) return false; //centi if (!add_prefix('m', 1e-3)) return false; //milli if (!add_prefix('u', 1e-6)) return false; //micro if (!add_prefix('n', 1e-9)) return false; //nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto debug("Prefixes initialized!"); return true; } UL_LINKAGE bool _ul_init_parser(void) { debug("Initializing parser"); for (int i=0; i < NUM_BASE_UNITS; ++i) { debug("Base rule: %d", i); base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; debug("Base rules initialized"); // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; debug("Adding gram"); if (!add_rule("g", &gram, true)) return false; if (!init_prefixes()) return false; debug("Parser initalized!"); return true; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } prefix_t *pref = prefixes; while (pref) { prefix_t *next = pref->next; free(pref); pref = next; } } diff --git a/unitlib.h b/unitlib.h index 12f0e53..6f7162d 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,245 +1,251 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" #define UL_VERSION "0.4b2" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) __stdcall #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) __stdcall #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN = 0, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, UL_NUM_FORMATS, } ul_format_t; typedef enum ul_cmpres { UL_DIFFERENT = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, UL_ERROR = 0xFF, } ul_cmpres_t; +enum ul_fmtop +{ + UL_FOP_REDUCE = 0x01, +}; + typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the full name of unitlib, including the version * @return String in the form "unitlib-x.yz" */ UL_API const char *ul_get_name(void); /** * Returns the version of unitlib * @return String in the form "x.yz" */ UL_API const char *ul_get_version(void); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format - * @param fmtp Additional format parameters + * @param fops A bitmap containing UL_FOP_* flags * @return success */ -UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format); +UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, int fops); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format - * @param fmtp Additional format parameters + * @param fops A bitmap containing UL_FOP_* flags * @return success */ -static inline bool ul_print(const unit_t *unit, ul_format_t format) +static inline bool ul_print(const unit_t *unit, ul_format_t format, int fops) { - return ul_fprint(stdout, unit, format); + return ul_fprint(stdout, unit, format, fops); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format - * @param fmtp Additional format parameters + * @param fops A bitmap containing UL_FOP_* flags * @return success */ -UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format); +UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, int fops); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option + * @param fops A bitmap containing UL_FOP_* flags * @return Length of the formated string */ -UL_API size_t ul_length(const unit_t *unit, ul_format_t format); +UL_API size_t ul_length(const unit_t *unit, ul_format_t format, int fops); #endif /*UNITLIB_H*/ diff --git a/unittest.c b/unittest.c index fa057db..ed12728 100644 --- a/unittest.c +++ b/unittest.c @@ -1,560 +1,560 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) TEST_SUITE(parser) TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; const char *strings[] = { "5*kg^2", // need whitespace "5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST TEST static char prefs[] = "YZEPTGMkh dcmunpfazy"; static ul_number factors[] = { 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1, 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, }; size_t num_prefs = strlen(prefs); FATAL((sizeof(factors) / sizeof(factors[0])) != num_prefs); for (size_t i = 0; i < num_prefs; ++i) { char expr[128] = ""; snprintf(expr, 128, "5 %cm", prefs[i]); unit_t u; CHECK(ul_parse(expr, &u)); FAIL_MSG("Failed to parse: '%s' (%s)", expr, ul_error()); CHECK(ncmp(ul_factor(&u), 5 * factors[i]) == 0); FAIL_MSG("Factor: %g instead of %g (%c)", ul_factor(&u), 5 * factors[i], prefs[i]); // check kilogram, the only base unit with a prefix snprintf(expr, 128, "%cg", prefs[i]); CHECK(ul_parse(expr, &u)); } END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -1); unit_t test; CHECK(ul_parse("kg / s", &test)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&test, &correct)); correct.factor = 2.0; CHECK(ul_parse("8 kg / 4 s", &test)); CHECK(ul_equal(&test, &correct)); END_TEST END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t one_kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t five_kg = MAKE_UNIT(5.0, U_KILOGRAM, 1); CHECK(!ul_equal(&one_kg, &five_kg)); CHECK(ul_cmp(&one_kg, &five_kg) == UL_SAME_UNIT); unit_t five_sec = MAKE_UNIT(5.0, U_SECOND, 1); CHECK(ul_cmp(&five_kg, &five_sec) == UL_SAME_FACTOR); CHECK(ul_cmp(&one_kg, &five_sec) == UL_DIFFERENT); CHECK(ul_cmp(NULL, &one_kg) == UL_ERROR); CHECK(ul_cmp(&one_kg, NULL) == UL_ERROR); CHECK(ul_cmp(NULL, NULL) == UL_ERROR); /* UL_EQUAL result is tested by the previous test */ END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST TEST unit_t test = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, 5.0)); CHECK(ul_factor(&test) == 5.0); CHECK(ul_mult(&test, 1/5.0)); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, -1)); CHECK(ul_factor(&test) == -1.0); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; - CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN)); + CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); - CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); - FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); + CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); + FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = 1.5; - CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN)); + CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); - CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); - FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); + CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); + FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); kg.factor = -1.0; - CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN)); + CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); - CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); - FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); + CHECK(ul_length(&kg, UL_FMT_PLAIN, 0) == strlen(buffer)); + FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; - CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN)); + CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); - CHECK(ul_length(&N, UL_FMT_PLAIN) == strlen(buffer)); - FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN)); + CHECK(ul_length(&N, UL_FMT_PLAIN, 0) == strlen(buffer)); + FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; - CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE)); + CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); - CHECK(ul_length(&N, UL_FMT_LATEX_INLINE) == strlen(buffer)); - FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE)); + CHECK(ul_length(&N, UL_FMT_LATEX_INLINE, 0) == strlen(buffer)); + FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE, 0)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; - CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC)); + CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}$") == 0); FAIL_MSG("buffer: '%s'", buffer); - CHECK(ul_length(&N, UL_FMT_LATEX_FRAC) == strlen(buffer)); - FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_FRAC)); + CHECK(ul_length(&N, UL_FMT_LATEX_FRAC, 0) == strlen(buffer)); + FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_FRAC, 0)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; - CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN)); + CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, 0)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() int main(void) { ul_debugging(false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define FATAL(expr) \ do { \ if (expr) { \ PRINT(_o, L_RESULT, "[%s-%d] Fatal: %s\n", _name, _id, #expr); \ exit(1); \ } \ } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s-%d-%d] Fail: '%s'\n", _name, _id, _this, #expr); \ _last = false;\ } \ else { \ PRINT(_o, L_VERBOSE, "[%s-%d-%d] Pass: '%s'\n", _name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s-%d] failed with %d error%s.\n", _name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s-%d] passed.\n", _name, _id); \ } \ } // OTHER typedef struct { int loglvl; } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
ba0527106ba30732b855fb7896c3618d48efeb2b
Major overhaul of the formating procedure. Incompatibilities: * UL_FMT_LATEX_FRAC will enclose it's output in '$'
diff --git a/format.c b/format.c index 109891b..81af6df 100644 --- a/format.c +++ b/format.c @@ -1,420 +1,357 @@ #include <assert.h> #include <stdio.h> #include <string.h> #include "intern.h" #include "unitlib.h" struct status { bool (*put_char)(char c, void *info); void *info; const unit_t *unit; ul_format_t format; void *extra; }; struct printer; typedef bool (*print_all_f)(struct printer* p, struct status *stat); typedef bool (*print_fac_f)(struct status *stat, ul_number factor, bool *first); typedef bool (*print_sym_f)(struct status *stat, const char *sym, int exp, bool *first); struct printer { print_sym_f sym; print_fac_f fac; print_all_f normal; print_all_f reduce; const char *prefix; const char *postfix; }; struct f_info { FILE *out; }; static bool f_putc(char c, void *i) { struct f_info *info = i; return fputc(c, info->out) == c; } struct sn_info { char *buffer; int idx; int size; }; static bool sn_putc(char c, void *i) { struct sn_info *info = i; if (info->idx >= info->size) { return false; } info->buffer[info->idx++] = c; return true; } struct cnt_info { size_t count; }; static bool cnt_putc(char c, void *i) { (void)c; struct cnt_info *info = i; info->count++; return true; } #define _putc(s,c) (s)->put_char((c),(s)->info) #define CHECK(x) do { if (!(x)) return false; } while (0) static bool _puts(struct status *s, const char *str) { while (*str) { char c = *str++; if (!_putc(s, c)) return false; } return true; } static bool _putd(struct status *stat, int n) { char buffer[1024]; snprintf(buffer, 1024, "%d", n); return _puts(stat, buffer); } static bool _putn(struct status *stat, ul_number n) { char buffer[1024]; snprintf(buffer, 1024, N_FMT, n); return _puts(stat, buffer); } static void getnexp(ul_number n, ul_number *mantissa, int *exp) { bool neg = false; if (n < 0) { neg = true; n = -n; } if ((ncmp(n, 10.0) == -1) && (ncmp(n, 1.0) == 1)) { *mantissa = neg ? -n : n; *exp = 0; return; } else if (ncmp(n, 10.0) > -1) { int e = 0; do { e++; n /= 10; } while (ncmp(n, 10.0) == 1); *exp = e; *mantissa = neg ? -n : n; } else if (ncmp(n, 1.0) < 1) { int e = 0; while (ncmp(n, 1.0) == -1) { e--; n *= 10; } *exp = e; *mantissa = neg ? -n : n; } } // global for testing purpose, it's not declared in the header void _ul_getnexp(ul_number n, ul_number *m, int *e) { getnexp(n, m, e); } +static bool p_lfrac(struct printer *p, struct status *stat) +{ + if (p->prefix) + CHECK(_puts(stat, p->prefix)); + + bool first = true; + + CHECK(_puts(stat, "\\frac{")); + if (_fabsn(stat->unit->factor) >= 1) + CHECK(p->fac(stat, stat->unit->factor, &first)); + + for (int i=0; i < NUM_BASE_UNITS; ++i) { + if (stat->unit->exps[i] > 0) + CHECK(p->sym(stat, _ul_symbols[i], stat->unit->exps[i], &first)); + } + if (first) + CHECK(p->fac(stat, 1.0, &first)); + + CHECK(_puts(stat, "}{")); + first = true; + if (_fabsn(stat->unit->factor) < 1) + CHECK(p->fac(stat, stat->unit->factor, &first)); + for (int i=0; i < NUM_BASE_UNITS; ++i) { + if (stat->unit->exps[i] < 0) + CHECK(p->sym(stat, _ul_symbols[i], -stat->unit->exps[i], &first)); + } + if (first) + CHECK(p->fac(stat, 1.0, &first)); + + CHECK(_putc(stat, '}')); + + if (p->postfix) + CHECK(_puts(stat, p->postfix)); + + return true; +} + static bool p_plain_fac(struct status *stat, ul_number fac, bool *first) { + if (!*first) + CHECK(_putc(stat, ' ')); CHECK(_putn(stat, fac)); - *first = true; + *first = false; return true; } static bool p_plain_sym(struct status *stat, const char *sym, int exp, bool *first) { if (!exp) return true; if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, sym)); if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putd(stat, exp)); } + *first = false; return true; } -// Begin - plain -static bool print_one_plain(struct status* stat, int unit, int exp) -{ - if (exp == 0) - return true; - - CHECK(_putc(stat, ' ')); - CHECK(_puts(stat, _ul_symbols[unit])); - // and the exponent - if (exp != 1) { - CHECK(_putc(stat, '^')); - CHECK(_putd(stat, exp)); - } - return true; -} - -static bool p_plain(struct status *stat) +static bool p_latex_fac(struct status *stat, ul_number fac, bool *first) { - CHECK(_putn(stat, stat->unit->factor)); + ul_number m; int e; + getnexp(fac, &m, &e); - for (int i=0; i < NUM_BASE_UNITS; ++i) { - CHECK(print_one_plain(stat,i,stat->unit->exps[i])); + if (!*first) + CHECK(_putc(stat, ' ')); + CHECK(_putn(stat, m)); + if (e != 0) { + CHECK(_puts(stat, " \\cdot 10^{")); + CHECK(_putd(stat, e)); + CHECK(_putc(stat, '}')); } - + *first = false; return true; } -// End - plain -// Begin - LaTeX -static bool print_one_latex(struct status *stat, int unit, int exp, bool *first) +static bool p_latex_sym(struct status *stat, const char *sym, int exp, bool *first) { - if (exp == 0) - return true; - if (stat->extra) { - bool pos = *(bool*)stat->extra; - if (exp > 0 && !pos) - return true; - if (exp < 0) { - if (pos) - return true; - exp = -exp; - } - } - if (!first || !*first) + if (!*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, "\\text{")); - if (!first || !*first) + if (!*first) CHECK(_putc(stat, ' ')); - CHECK(_puts(stat, _ul_symbols[unit])); + CHECK(_puts(stat, sym)); CHECK(_puts(stat, "}")); if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putc(stat, '{')); CHECK(_putd(stat, exp)); CHECK(_putc(stat, '}')); } if (first) *first = false; return true; } -static bool p_latex_frac(struct status *stat) -{ - bool first = true; - bool positive = true; - stat->extra = &positive; - - ul_number m; int e; - getnexp(stat->unit->factor, &m, &e); - - CHECK(_puts(stat, "\\frac{")); - - // upper side of the fraction - if (e >= 0) { - // print factors |x| > 1 - CHECK(_putn(stat, m)); - if (e > 0) { - CHECK(_puts(stat, " \\cdot 10^{")); - CHECK(_putd(stat, e)); - CHECK(_putc(stat, '}')); - } - first = false; - } - for (int i=0; i < NUM_BASE_UNITS; ++i) { - CHECK(print_one_latex(stat,i,stat->unit->exps[i], &first)); - } - if (first) { // nothing up there... - CHECK(_putc(stat, '1')); - } - CHECK(_puts(stat, "}{")); - - // lower side - first = true; - positive = false; - if (e < 0) { - // print factors |x| < 1 - e = -e; - CHECK(_putn(stat, m)); - if (e > 0) { - CHECK(_puts(stat, " \\cdot 10^{")); - CHECK(_putd(stat, e)); - CHECK(_putc(stat, '}')); - } - first = false; - } - for (int i=0; i < NUM_BASE_UNITS; ++i) { - CHECK(print_one_latex(stat,i,stat->unit->exps[i], &first)); - } - if (first) { - CHECK(_putc(stat, '1')); - } - CHECK(_putc(stat, '}')); - return true; -} - -static bool p_latex_inline(struct status *stat) -{ - CHECK(_putc(stat, '$')); - - ul_number m; int e; - getnexp(stat->unit->factor, &m, &e); - CHECK(_putn(stat, m)); - if (e != 0) { - CHECK(_puts(stat, " \\cdot 10^{")); - CHECK(_putd(stat, e)); - CHECK(_putc(stat, '}')); - } - - for (int i=0; i < NUM_BASE_UNITS; ++i) { - int exp = stat->unit->exps[i]; - if (exp != 0) { - CHECK(print_one_latex(stat, i, exp, NULL)); - } - } - CHECK(_putc(stat, '$')); - return true; -} -// End - LaTeX - static bool def_normal(struct printer *p, struct status *stat) { if (p->prefix) CHECK(_puts(stat, p->prefix)); bool first = true; CHECK(p->fac(stat, stat->unit->factor, &first)); for (int i=0; i < NUM_BASE_UNITS; ++i) { - CHECK(p->sym(stat, _ul_symbols[i], stat->unit->exps[i], &first)); + if (stat->unit->exps[i] != 0) + CHECK(p->sym(stat, _ul_symbols[i], stat->unit->exps[i], &first)); } if (p->postfix) CHECK(_puts(stat, p->postfix)); return true; } static bool def_reduce(struct printer *p, struct status *stat) { return false; } -//----------------------------------------------------------------------------- static struct printer printer[UL_NUM_FORMATS] = { [UL_FMT_PLAIN] = { .sym = p_plain_sym, .fac = p_plain_fac, .normal = def_normal, .reduce = def_reduce, .prefix = NULL, .postfix = NULL, }, [UL_FMT_LATEX_INLINE] = { .sym = p_latex_sym, .fac = p_latex_fac, .normal = def_normal, .reduce = def_reduce, .prefix = "$", .postfix = "$", }, - [UL_FMT_LATEX_frac] = { + [UL_FMT_LATEX_FRAC] = { .sym = p_latex_sym, .fac = p_latex_fac, .normal = p_lfrac, .reduce = def_reduce, .prefix = "$", .postfix = "$", }, }; static bool _print(struct status *stat) { if (stat->format >= UL_NUM_FORMATS) { ERROR("Invalid format: %d\n", stat->format); return false; } struct printer *p = &printer[stat->format]; - return p->normal(p, stat); } UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format) { struct f_info info = { .out = f, }; struct status status = { .put_char = f_putc, .info = &info, .unit = unit, .format = format, .extra = NULL, }; return _print(&status); } UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format) { struct sn_info info = { .buffer = buffer, .size = buflen, .idx = 0, }; struct status status = { .put_char = sn_putc, .info = &info, .unit = unit, .format = format, .extra = NULL, }; memset(buffer, 0, buflen); return _print(&status); } UL_API size_t ul_length(const unit_t *unit, ul_format_t format) { struct cnt_info info = {0}; struct status status = { .put_char = cnt_putc, .info = &info, .unit = unit, .format = format, .extra = NULL, }; _print(&status); return info.count; } diff --git a/unittest.c b/unittest.c index 535d148..fa057db 100644 --- a/unittest.c +++ b/unittest.c @@ -1,560 +1,560 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) TEST_SUITE(parser) TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; const char *strings[] = { "5*kg^2", // need whitespace "5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST TEST static char prefs[] = "YZEPTGMkh dcmunpfazy"; static ul_number factors[] = { 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1, 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, }; size_t num_prefs = strlen(prefs); FATAL((sizeof(factors) / sizeof(factors[0])) != num_prefs); for (size_t i = 0; i < num_prefs; ++i) { char expr[128] = ""; snprintf(expr, 128, "5 %cm", prefs[i]); unit_t u; CHECK(ul_parse(expr, &u)); FAIL_MSG("Failed to parse: '%s' (%s)", expr, ul_error()); CHECK(ncmp(ul_factor(&u), 5 * factors[i]) == 0); FAIL_MSG("Factor: %g instead of %g (%c)", ul_factor(&u), 5 * factors[i], prefs[i]); // check kilogram, the only base unit with a prefix snprintf(expr, 128, "%cg", prefs[i]); CHECK(ul_parse(expr, &u)); } END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -1); unit_t test; CHECK(ul_parse("kg / s", &test)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&test, &correct)); correct.factor = 2.0; CHECK(ul_parse("8 kg / 4 s", &test)); CHECK(ul_equal(&test, &correct)); END_TEST END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t one_kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t five_kg = MAKE_UNIT(5.0, U_KILOGRAM, 1); CHECK(!ul_equal(&one_kg, &five_kg)); CHECK(ul_cmp(&one_kg, &five_kg) == UL_SAME_UNIT); unit_t five_sec = MAKE_UNIT(5.0, U_SECOND, 1); CHECK(ul_cmp(&five_kg, &five_sec) == UL_SAME_FACTOR); CHECK(ul_cmp(&one_kg, &five_sec) == UL_DIFFERENT); CHECK(ul_cmp(NULL, &one_kg) == UL_ERROR); CHECK(ul_cmp(&one_kg, NULL) == UL_ERROR); CHECK(ul_cmp(NULL, NULL) == UL_ERROR); /* UL_EQUAL result is tested by the previous test */ END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST TEST unit_t test = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, 5.0)); CHECK(ul_factor(&test) == 5.0); CHECK(ul_mult(&test, 1/5.0)); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, -1)); CHECK(ul_factor(&test) == -1.0); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_INLINE) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC)); FAIL_MSG("Error: %s", ul_error()); - CHECK(strcmp(buffer, "\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}") == 0); + CHECK(strcmp(buffer, "$\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_FRAC) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_FRAC)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() int main(void) { ul_debugging(false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define FATAL(expr) \ do { \ if (expr) { \ PRINT(_o, L_RESULT, "[%s-%d] Fatal: %s\n", _name, _id, #expr); \ exit(1); \ } \ } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s-%d-%d] Fail: '%s'\n", _name, _id, _this, #expr); \ _last = false;\ } \ else { \ PRINT(_o, L_VERBOSE, "[%s-%d-%d] Pass: '%s'\n", _name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s-%d] failed with %d error%s.\n", _name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s-%d] passed.\n", _name, _id); \ } \ } // OTHER typedef struct { int loglvl; } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
d431af237f76cba04ce4a55e3bfac1310280973f
Started new format system (does not compile at the moment).
diff --git a/format.c b/format.c index 5db5ba4..109891b 100644 --- a/format.c +++ b/format.c @@ -1,337 +1,420 @@ #include <assert.h> #include <stdio.h> #include <string.h> #include "intern.h" #include "unitlib.h" struct status { bool (*put_char)(char c, void *info); void *info; const unit_t *unit; ul_format_t format; void *extra; }; -typedef bool (*printer_t)(struct status*,int,int,bool*); +struct printer; + +typedef bool (*print_all_f)(struct printer* p, struct status *stat); +typedef bool (*print_fac_f)(struct status *stat, ul_number factor, bool *first); +typedef bool (*print_sym_f)(struct status *stat, const char *sym, int exp, bool *first); + +struct printer +{ + print_sym_f sym; + print_fac_f fac; + print_all_f normal; + print_all_f reduce; + const char *prefix; + const char *postfix; +}; struct f_info { FILE *out; }; static bool f_putc(char c, void *i) { struct f_info *info = i; return fputc(c, info->out) == c; } struct sn_info { char *buffer; int idx; int size; }; static bool sn_putc(char c, void *i) { struct sn_info *info = i; if (info->idx >= info->size) { return false; } info->buffer[info->idx++] = c; return true; } struct cnt_info { size_t count; }; static bool cnt_putc(char c, void *i) { (void)c; struct cnt_info *info = i; info->count++; return true; } #define _putc(s,c) (s)->put_char((c),(s)->info) #define CHECK(x) do { if (!(x)) return false; } while (0) static bool _puts(struct status *s, const char *str) { while (*str) { char c = *str++; if (!_putc(s, c)) return false; } return true; } static bool _putd(struct status *stat, int n) { char buffer[1024]; snprintf(buffer, 1024, "%d", n); return _puts(stat, buffer); } static bool _putn(struct status *stat, ul_number n) { char buffer[1024]; snprintf(buffer, 1024, N_FMT, n); return _puts(stat, buffer); } static void getnexp(ul_number n, ul_number *mantissa, int *exp) { bool neg = false; if (n < 0) { neg = true; n = -n; } if ((ncmp(n, 10.0) == -1) && (ncmp(n, 1.0) == 1)) { *mantissa = neg ? -n : n; *exp = 0; return; } else if (ncmp(n, 10.0) > -1) { int e = 0; do { e++; n /= 10; } while (ncmp(n, 10.0) == 1); *exp = e; *mantissa = neg ? -n : n; } else if (ncmp(n, 1.0) < 1) { int e = 0; while (ncmp(n, 1.0) == -1) { e--; n *= 10; } *exp = e; *mantissa = neg ? -n : n; } } // global for testing purpose, it's not declared in the header void _ul_getnexp(ul_number n, ul_number *m, int *e) { getnexp(n, m, e); } +static bool p_plain_fac(struct status *stat, ul_number fac, bool *first) +{ + CHECK(_putn(stat, fac)); + *first = true; + return true; +} + +static bool p_plain_sym(struct status *stat, const char *sym, int exp, bool *first) +{ + if (!exp) + return true; + + if (!*first) + CHECK(_putc(stat, ' ')); + + CHECK(_puts(stat, sym)); + if (exp != 1) { + CHECK(_putc(stat, '^')); + CHECK(_putd(stat, exp)); + } + return true; +} + // Begin - plain static bool print_one_plain(struct status* stat, int unit, int exp) { if (exp == 0) return true; CHECK(_putc(stat, ' ')); CHECK(_puts(stat, _ul_symbols[unit])); // and the exponent if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putd(stat, exp)); } return true; } static bool p_plain(struct status *stat) { CHECK(_putn(stat, stat->unit->factor)); for (int i=0; i < NUM_BASE_UNITS; ++i) { CHECK(print_one_plain(stat,i,stat->unit->exps[i])); } return true; } // End - plain // Begin - LaTeX static bool print_one_latex(struct status *stat, int unit, int exp, bool *first) { if (exp == 0) return true; if (stat->extra) { bool pos = *(bool*)stat->extra; if (exp > 0 && !pos) return true; if (exp < 0) { if (pos) return true; exp = -exp; } } if (!first || !*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, "\\text{")); if (!first || !*first) CHECK(_putc(stat, ' ')); CHECK(_puts(stat, _ul_symbols[unit])); CHECK(_puts(stat, "}")); if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putc(stat, '{')); CHECK(_putd(stat, exp)); CHECK(_putc(stat, '}')); } if (first) *first = false; return true; } static bool p_latex_frac(struct status *stat) { bool first = true; bool positive = true; stat->extra = &positive; ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_puts(stat, "\\frac{")); // upper side of the fraction if (e >= 0) { // print factors |x| > 1 CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { CHECK(print_one_latex(stat,i,stat->unit->exps[i], &first)); } if (first) { // nothing up there... CHECK(_putc(stat, '1')); } CHECK(_puts(stat, "}{")); // lower side first = true; positive = false; if (e < 0) { // print factors |x| < 1 e = -e; CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { CHECK(print_one_latex(stat,i,stat->unit->exps[i], &first)); } if (first) { CHECK(_putc(stat, '1')); } CHECK(_putc(stat, '}')); return true; } static bool p_latex_inline(struct status *stat) { CHECK(_putc(stat, '$')); ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_putn(stat, m)); if (e != 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } for (int i=0; i < NUM_BASE_UNITS; ++i) { int exp = stat->unit->exps[i]; if (exp != 0) { CHECK(print_one_latex(stat, i, exp, NULL)); } } CHECK(_putc(stat, '$')); return true; } // End - LaTeX -static bool _print(struct status *stat) +static bool def_normal(struct printer *p, struct status *stat) { - switch (stat->format) { - case UL_FMT_PLAIN: - return p_plain(stat); + if (p->prefix) + CHECK(_puts(stat, p->prefix)); + + bool first = true; + + CHECK(p->fac(stat, stat->unit->factor, &first)); - case UL_FMT_LATEX_FRAC: - return p_latex_frac(stat); + for (int i=0; i < NUM_BASE_UNITS; ++i) { + CHECK(p->sym(stat, _ul_symbols[i], stat->unit->exps[i], &first)); + } + + if (p->postfix) + CHECK(_puts(stat, p->postfix)); - case UL_FMT_LATEX_INLINE: - return p_latex_inline(stat); + return true; +} - default: - ERROR("Unknown format: %d", stat->format); +static bool def_reduce(struct printer *p, struct status *stat) +{ + return false; +} + +//----------------------------------------------------------------------------- +static struct printer printer[UL_NUM_FORMATS] = { + [UL_FMT_PLAIN] = { + .sym = p_plain_sym, + .fac = p_plain_fac, + .normal = def_normal, + .reduce = def_reduce, + .prefix = NULL, + .postfix = NULL, + }, + [UL_FMT_LATEX_INLINE] = { + .sym = p_latex_sym, + .fac = p_latex_fac, + .normal = def_normal, + .reduce = def_reduce, + .prefix = "$", + .postfix = "$", + }, + [UL_FMT_LATEX_frac] = { + .sym = p_latex_sym, + .fac = p_latex_fac, + .normal = p_lfrac, + .reduce = def_reduce, + .prefix = "$", + .postfix = "$", + }, +}; + +static bool _print(struct status *stat) +{ + if (stat->format >= UL_NUM_FORMATS) { + ERROR("Invalid format: %d\n", stat->format); return false; } + + struct printer *p = &printer[stat->format]; + + return p->normal(p, stat); } UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format) { struct f_info info = { .out = f, }; struct status status = { .put_char = f_putc, .info = &info, .unit = unit, .format = format, .extra = NULL, }; return _print(&status); } UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format) { struct sn_info info = { .buffer = buffer, .size = buflen, .idx = 0, }; struct status status = { .put_char = sn_putc, .info = &info, .unit = unit, .format = format, .extra = NULL, }; memset(buffer, 0, buflen); return _print(&status); } UL_API size_t ul_length(const unit_t *unit, ul_format_t format) { struct cnt_info info = {0}; struct status status = { .put_char = cnt_putc, .info = &info, .unit = unit, .format = format, .extra = NULL, }; _print(&status); return info.count; } diff --git a/unitlib.h b/unitlib.h index b35b3e7..12f0e53 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,244 +1,245 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" #define UL_VERSION "0.4b2" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) __stdcall #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) __stdcall #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { - UL_FMT_PLAIN, + UL_FMT_PLAIN = 0, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, + UL_NUM_FORMATS, } ul_format_t; typedef enum ul_cmpres { - UL_ERROR = 0xFF, UL_DIFFERENT = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, + UL_ERROR = 0xFF, } ul_cmpres_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the full name of unitlib, including the version * @return String in the form "unitlib-x.yz" */ UL_API const char *ul_get_name(void); /** * Returns the version of unitlib * @return String in the form "x.yz" */ UL_API const char *ul_get_version(void); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format) { return ul_fprint(stdout, unit, format); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option * @return Length of the formated string */ UL_API size_t ul_length(const unit_t *unit, ul_format_t format); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
6fb47490bbb7bfb0d37e94c70aed1a58ad8e696d
API CHANGE: Removed fmtops parameter of the printing functions.
diff --git a/format.c b/format.c index 0ca05d9..5db5ba4 100644 --- a/format.c +++ b/format.c @@ -1,389 +1,337 @@ #include <assert.h> #include <stdio.h> #include <string.h> #include "intern.h" #include "unitlib.h" struct status { bool (*put_char)(char c, void *info); void *info; const unit_t *unit; ul_format_t format; - ul_fmtops_t *fmtp; void *extra; }; typedef bool (*printer_t)(struct status*,int,int,bool*); struct f_info { FILE *out; }; static bool f_putc(char c, void *i) { struct f_info *info = i; return fputc(c, info->out) == c; } struct sn_info { char *buffer; int idx; int size; }; static bool sn_putc(char c, void *i) { struct sn_info *info = i; if (info->idx >= info->size) { return false; } info->buffer[info->idx++] = c; return true; } struct cnt_info { size_t count; }; static bool cnt_putc(char c, void *i) { (void)c; struct cnt_info *info = i; info->count++; return true; } #define _putc(s,c) (s)->put_char((c),(s)->info) #define CHECK(x) do { if (!(x)) return false; } while (0) static bool _puts(struct status *s, const char *str) { while (*str) { char c = *str++; if (!_putc(s, c)) return false; } return true; } static bool _putd(struct status *stat, int n) { char buffer[1024]; snprintf(buffer, 1024, "%d", n); return _puts(stat, buffer); } static bool _putn(struct status *stat, ul_number n) { char buffer[1024]; snprintf(buffer, 1024, N_FMT, n); return _puts(stat, buffer); } static void getnexp(ul_number n, ul_number *mantissa, int *exp) { bool neg = false; if (n < 0) { neg = true; n = -n; } if ((ncmp(n, 10.0) == -1) && (ncmp(n, 1.0) == 1)) { *mantissa = neg ? -n : n; *exp = 0; return; } else if (ncmp(n, 10.0) > -1) { int e = 0; do { e++; n /= 10; } while (ncmp(n, 10.0) == 1); *exp = e; *mantissa = neg ? -n : n; } else if (ncmp(n, 1.0) < 1) { int e = 0; while (ncmp(n, 1.0) == -1) { e--; n *= 10; } *exp = e; *mantissa = neg ? -n : n; } } // global for testing purpose, it's not declared in the header void _ul_getnexp(ul_number n, ul_number *m, int *e) { getnexp(n, m, e); } -static bool print_sorted(struct status *stat, printer_t func, bool *first) -{ - bool printed[NUM_BASE_UNITS] = {0}; - bool _first = true; - bool *fptr = first ? first : &_first; - - // Print any sorted order - for (int i=0; i < NUM_BASE_UNITS; ++i) { - int unit = stat->fmtp->order[i]; - if (unit == U_ANY) { - break; - } - int exp = stat->unit->exps[unit]; - CHECK(func(stat, unit, exp , fptr)); - printed[unit] = true; - } - // Print the rest - for (int i=0; i < NUM_BASE_UNITS; ++i) { - if (!printed[i]) { - int exp = stat->unit->exps[i]; - if (exp != 0) { - CHECK(func(stat, i, exp , fptr)); - } - } - } - return true; -} - -static bool print_normal(struct status *stat, printer_t func, bool *first) -{ - bool _first = true; - bool *fptr = first ? first : &_first; - for (int i=0; i < NUM_BASE_UNITS; ++i) { - CHECK(func(stat,i,stat->unit->exps[i], fptr)); - } - return true; -} - // Begin - plain -static bool _plain_one(struct status* stat, int unit, int exp, bool *first) +static bool print_one_plain(struct status* stat, int unit, int exp) { if (exp == 0) return true; - if (!*first) - CHECK(_putc(stat, ' ')); - + CHECK(_putc(stat, ' ')); CHECK(_puts(stat, _ul_symbols[unit])); // and the exponent if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putd(stat, exp)); } - *first = false; return true; } static bool p_plain(struct status *stat) { CHECK(_putn(stat, stat->unit->factor)); - CHECK(_putc(stat, ' ')); - if (stat->fmtp && stat->fmtp->sort) { - return print_sorted(stat, _plain_one, NULL); - } - else { - return print_normal(stat, _plain_one, NULL); + + for (int i=0; i < NUM_BASE_UNITS; ++i) { + CHECK(print_one_plain(stat,i,stat->unit->exps[i])); } + return true; } // End - plain // Begin - LaTeX -static bool _latex_one(struct status *stat, int unit, int exp, bool *first) +static bool print_one_latex(struct status *stat, int unit, int exp, bool *first) { if (exp == 0) return true; if (stat->extra) { bool pos = *(bool*)stat->extra; if (exp > 0 && !pos) return true; if (exp < 0) { if (pos) return true; exp = -exp; } } - if (!*first) + if (!first || !*first) CHECK(_putc(stat, ' ')); + CHECK(_puts(stat, "\\text{")); - if (!*first) + if (!first || !*first) CHECK(_putc(stat, ' ')); + CHECK(_puts(stat, _ul_symbols[unit])); CHECK(_puts(stat, "}")); if (exp != 1) { CHECK(_putc(stat, '^')); CHECK(_putc(stat, '{')); CHECK(_putd(stat, exp)); CHECK(_putc(stat, '}')); } - *first = false; + if (first) + *first = false; return true; } static bool p_latex_frac(struct status *stat) { bool first = true; bool positive = true; stat->extra = &positive; ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_puts(stat, "\\frac{")); + // upper side of the fraction if (e >= 0) { + // print factors |x| > 1 CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } - - if (stat->fmtp && stat->fmtp->sort) { - print_sorted(stat, _latex_one, &first); - } - else { - print_normal(stat, _latex_one, &first); + for (int i=0; i < NUM_BASE_UNITS; ++i) { + CHECK(print_one_latex(stat,i,stat->unit->exps[i], &first)); } - - if (first) { - // nothing up there... + if (first) { // nothing up there... CHECK(_putc(stat, '1')); } CHECK(_puts(stat, "}{")); + // lower side first = true; positive = false; - if (e < 0) { + // print factors |x| < 1 e = -e; CHECK(_putn(stat, m)); if (e > 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } first = false; } - - if (stat->fmtp && stat->fmtp->sort) { - print_sorted(stat, _latex_one, &first); - } - else { - print_normal(stat, _latex_one, &first); + for (int i=0; i < NUM_BASE_UNITS; ++i) { + CHECK(print_one_latex(stat,i,stat->unit->exps[i], &first)); } if (first) { CHECK(_putc(stat, '1')); } CHECK(_putc(stat, '}')); return true; } static bool p_latex_inline(struct status *stat) { - bool first = false; CHECK(_putc(stat, '$')); ul_number m; int e; getnexp(stat->unit->factor, &m, &e); CHECK(_putn(stat, m)); if (e != 0) { CHECK(_puts(stat, " \\cdot 10^{")); CHECK(_putd(stat, e)); CHECK(_putc(stat, '}')); } for (int i=0; i < NUM_BASE_UNITS; ++i) { int exp = stat->unit->exps[i]; if (exp != 0) { - CHECK(_latex_one(stat, i, exp, &first)); + CHECK(print_one_latex(stat, i, exp, NULL)); } } CHECK(_putc(stat, '$')); return true; } // End - LaTeX static bool _print(struct status *stat) { switch (stat->format) { case UL_FMT_PLAIN: return p_plain(stat); case UL_FMT_LATEX_FRAC: return p_latex_frac(stat); case UL_FMT_LATEX_INLINE: return p_latex_inline(stat); default: ERROR("Unknown format: %d", stat->format); return false; } } -UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) +UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format) { struct f_info info = { .out = f, }; struct status status = { .put_char = f_putc, .info = &info, .unit = unit, .format = format, - .fmtp = fmtp, .extra = NULL, }; return _print(&status); } -UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) +UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format) { struct sn_info info = { .buffer = buffer, .size = buflen, .idx = 0, }; struct status status = { .put_char = sn_putc, .info = &info, .unit = unit, .format = format, - .fmtp = fmtp, .extra = NULL, }; memset(buffer, 0, buflen); return _print(&status); } UL_API size_t ul_length(const unit_t *unit, ul_format_t format) { struct cnt_info info = {0}; struct status status = { .put_char = cnt_putc, .info = &info, .unit = unit, .format = format, - .fmtp = NULL, .extra = NULL, }; _print(&status); return info.count; } diff --git a/unitlib.h b/unitlib.h index 6388aee..b35b3e7 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,250 +1,244 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" #define UL_VERSION "0.4b2" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) __stdcall #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) __stdcall #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; typedef enum ul_cmpres { UL_ERROR = 0xFF, UL_DIFFERENT = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, } ul_cmpres_t; -typedef struct ul_format_ops -{ - bool sort; - int order[NUM_BASE_UNITS]; -} ul_fmtops_t; - typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the full name of unitlib, including the version * @return String in the form "unitlib-x.yz" */ UL_API const char *ul_get_name(void); /** * Returns the version of unitlib * @return String in the form "x.yz" */ UL_API const char *ul_get_version(void); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ -UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); +UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ -static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) +static inline bool ul_print(const unit_t *unit, ul_format_t format) { - return ul_fprint(stdout, unit, format, fmtp); + return ul_fprint(stdout, unit, format); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ -UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); +UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option * @return Length of the formated string */ UL_API size_t ul_length(const unit_t *unit, ul_format_t format); #endif /*UNITLIB_H*/ diff --git a/unittest.c b/unittest.c index 616b03f..535d148 100644 --- a/unittest.c +++ b/unittest.c @@ -1,560 +1,560 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) TEST_SUITE(parser) TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; const char *strings[] = { "5*kg^2", // need whitespace "5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST TEST static char prefs[] = "YZEPTGMkh dcmunpfazy"; static ul_number factors[] = { 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1, 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, }; size_t num_prefs = strlen(prefs); FATAL((sizeof(factors) / sizeof(factors[0])) != num_prefs); for (size_t i = 0; i < num_prefs; ++i) { char expr[128] = ""; snprintf(expr, 128, "5 %cm", prefs[i]); unit_t u; CHECK(ul_parse(expr, &u)); FAIL_MSG("Failed to parse: '%s' (%s)", expr, ul_error()); CHECK(ncmp(ul_factor(&u), 5 * factors[i]) == 0); FAIL_MSG("Factor: %g instead of %g (%c)", ul_factor(&u), 5 * factors[i], prefs[i]); // check kilogram, the only base unit with a prefix snprintf(expr, 128, "%cg", prefs[i]); CHECK(ul_parse(expr, &u)); } END_TEST TEST unit_t correct = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -1); unit_t test; CHECK(ul_parse("kg / s", &test)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&test, &correct)); correct.factor = 2.0; CHECK(ul_parse("8 kg / 4 s", &test)); CHECK(ul_equal(&test, &correct)); END_TEST END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST TEST unit_t one_kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t five_kg = MAKE_UNIT(5.0, U_KILOGRAM, 1); CHECK(!ul_equal(&one_kg, &five_kg)); CHECK(ul_cmp(&one_kg, &five_kg) == UL_SAME_UNIT); unit_t five_sec = MAKE_UNIT(5.0, U_SECOND, 1); CHECK(ul_cmp(&five_kg, &five_sec) == UL_SAME_FACTOR); CHECK(ul_cmp(&one_kg, &five_sec) == UL_DIFFERENT); CHECK(ul_cmp(NULL, &one_kg) == UL_ERROR); CHECK(ul_cmp(&one_kg, NULL) == UL_ERROR); CHECK(ul_cmp(NULL, NULL) == UL_ERROR); /* UL_EQUAL result is tested by the previous test */ END_TEST TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST TEST unit_t test = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, 5.0)); CHECK(ul_factor(&test) == 5.0); CHECK(ul_mult(&test, 1/5.0)); CHECK(ul_factor(&test) == 1.0); CHECK(ul_mult(&test, -1)); CHECK(ul_factor(&test) == -1.0); END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; - CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); + CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); kg.factor = 1.5; - CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); + CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); kg.factor = -1.0; - CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); + CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; - CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, NULL)); + CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; - CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, NULL)); + CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_INLINE) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; - CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, NULL)); + CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_FRAC) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_FRAC)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; - CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, NULL)); + CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() int main(void) { ul_debugging(false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define FATAL(expr) \ do { \ if (expr) { \ PRINT(_o, L_RESULT, "[%s-%d] Fatal: %s\n", _name, _id, #expr); \ exit(1); \ } \ } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s-%d-%d] Fail: '%s'\n", _name, _id, _this, #expr); \ _last = false;\ } \ else { \ PRINT(_o, L_VERBOSE, "[%s-%d-%d] Pass: '%s'\n", _name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s-%d] failed with %d error%s.\n", _name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s-%d] passed.\n", _name, _id); \ } \ } // OTHER typedef struct { int loglvl; } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
557703d3281e8f9c79c502db2957f652fde459af
Workarround for ld bug with --out-implib, now using --output-def and Microsofts lib.exe.
diff --git a/Makefile b/Makefile index c819263..bb4b6e3 100644 --- a/Makefile +++ b/Makefile @@ -1,102 +1,106 @@ ## # Makefile for unitlib ## MSVC_COMPAT = -mms-bitfields -mno-cygwin CC = gcc CFLAGS = -O2 -std=c99 -Wall -Wextra AR = ar RANLIB = ranlib TARGET = libunit.a DLL = libunit.dll IMPLIB = libunit.lib HEADER = unitlib-config.h unitlib.h SRCFILES = unitlib.c parser.c format.c HDRFILES = unitlib.h intern.h unitlib-config.h WIN_DLL_INSTALL = /c/Windows WIN_LIB_INSTALL = /g/Programmieren/lib WIN_HDR_INSTALL = /g/Programmieren/include PREFIX = /usr INSTALL_LIB = $(PREFIX)/lib INSTALL_HDR = $(PREFIX)/include OBJFILES = unitlib.o parser.o format.o TESTPROG = _test.exe SMASHPROG = _smash.exe UNITTEST = ultest .PHONY: test clean allclean all: $(TARGET) dll: $(DLL) install-dll: dll cp $(DLL) $(WIN_DLL_INSTALL) + cp $(DLL) $(WIN_LIB_INSTALL) cp $(IMPLIB) $(WIN_LIB_INSTALL) cp $(HEADER) $(WIN_HDR_INSTALL) install: cp $(TARGET) $(INSTALL_LIB) cp $(HEADER) $(INSTALL_HDR) uninstall: rm $(INSTALL_LIB)/$(TARGET) cd $(INSTALL_HDR) rm $(HEADER) test: $(TESTPROG) @./$(TESTPROG) utest: $(UNITTEST) @./$(UNITTEST) smash: $(SMASHPROG) @./$(SMASHPROG) $(TARGET): $(OBJFILES) @$(AR) rc $(TARGET) $(OBJFILES) @$(RANLIB) $(TARGET) $(DLL): $(SRCFILES) $(HDRFILES) Makefile - @$(CC) $(CFLAGS) $(MSVC_COMPAT) -shared -o $(DLL) $(SRCFILES) -Wl,--out-implib,$(IMPLIB) + @$(CC) $(CFLAGS) $(MSVC_COMPAT) -shared -o $(DLL) $(SRCFILES) -Wl,--output-def,libunit.def + lib.exe /DEF:libunit.def /OUT:libunit.lib /MACHINE:X86 unitlib.o: unitlib.c $(HDRFILES) @$(CC) $(CFLAGS) -o unitlib.o -c unitlib.c parser.o: parser.c $(HDRFILES) @$(CC) $(CFLAGS) -o parser.o -c parser.c format.o: format.c $(HDRFILES) @$(CC) $(CFLAGS) -o format.o -c format.c $(TESTPROG): $(TARGET) _test.c @$(CC) -o $(TESTPROG) -g -L. _test.c -lunit $(SMASHPROG): $(TARGET) _test.c @$(CC) -o $(SMASHPROG) -L. -DSMASH _test.c -lunit $(UNITTEST): $(TARGET) unittest.c @$(CC) -std=gnu99 -o $(UNITTEST) -L. unittest.c -lunit clean: @rm -f $(OBJFILES) @rm -f $(TESTPROG) @rm -f $(SMASHPROG) @rm -f $(UNITTEST) @rm -f debug.log allclean: clean @rm -f $(TARGET) @rm -f $(DLL) @rm -f $(IMPLIB) + @rm -f libunit.def + @rm -f libunit.exp
jan-kuechler/unitlib
bc2d2c1a4070ad1291e2e6443debbc159b077860
Some debug messages, found the problem of the crashing MFC app using the DLL.
diff --git a/intern.h b/intern.h index 65a0c1f..ff17a8d 100644 --- a/intern.h +++ b/intern.h @@ -1,57 +1,57 @@ #ifndef UL_INTERN_H #define UL_INTERN_H #include <float.h> #include <math.h> #include "unitlib.h" extern const char *_ul_symbols[]; extern size_t _ul_symlens[]; extern bool _ul_debugging; UL_LINKAGE void _ul_debug(const char *fmt, ...); #define debug(fmt,...) \ do { \ - if (_ul_debugging) _ul_debug("[ul - %s] " fmt "\n",\ + if (_ul_debugging) _ul_debug("[%s] " fmt "\n",\ __func__, ##__VA_ARGS__);\ } while(0) UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...); #define ERROR(msg, ...) _ul_set_error(__func__, __LINE__, msg, ##__VA_ARGS__) -UL_LINKAGE bool _ul_init_rules(void); +UL_LINKAGE bool _ul_init_parser(void); UL_LINKAGE void _ul_free_rules(void); #define EXPS_SIZE(unit) (sizeof((unit)->exps[0]) * NUM_BASE_UNITS) static inline void init_unit(unit_t *unit) { memset(unit->exps, 0, EXPS_SIZE(unit)); unit->factor = 1.0; } static inline void copy_unit(const unit_t *restrict src, unit_t *restrict dst) { memcpy(dst->exps, src->exps, EXPS_SIZE(dst)); dst->factor = src->factor; } static inline void add_unit(unit_t *restrict to, const unit_t *restrict other, int times) { for (int i=0; i < NUM_BASE_UNITS; ++i) { to->exps[i] += (times * other->exps[i]); } to->factor *= _pown(other->factor, times); } static inline int ncmp(ul_number a, ul_number b) { if (_fabsn(a-b) < N_EPSILON) return 0; if (a < b) return -1; return 1; } #endif /*UL_INTERN_H*/ diff --git a/parser.c b/parser.c index 912f00b..aebb334 100644 --- a/parser.c +++ b/parser.c @@ -1,568 +1,576 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" typedef struct rule { const char *symbol; unit_t unit; bool force; struct rule *next; } rule_t; typedef struct prefix { char symbol; ul_number value; struct prefix *next; } prefix_t; // A list of all rules static rule_t *rules = NULL; // The base rules static rule_t base_rules[NUM_BASE_UNITS]; static prefix_t *prefixes = NULL; #define dynamic_rules (base_rules[NUM_BASE_UNITS-1].next) struct parser_state { int sign; }; enum { MAX_SYM_SIZE = 128, MAX_ITEM_SIZE = 1024, }; // Returns the last rule in the list static rule_t *last_rule(void) { rule_t *cur = rules; while (cur) { if (!cur->next) return cur; cur = cur->next; } // rules cannot be NULL assert(false); return NULL; } static rule_t *get_rule(const char *sym) { assert(sym); for (rule_t *cur = rules; cur; cur = cur->next) { if (strcmp(cur->symbol, sym) == 0) return cur; } return NULL; } static prefix_t *last_prefix(void) { prefix_t *cur = prefixes; while (cur) { if (!cur->next) return cur; cur = cur->next; } return NULL; } static prefix_t *get_prefix(char sym) { for (prefix_t *cur = prefixes; cur; cur = cur->next) { if (cur->symbol == sym) return cur; } return NULL; } static size_t skipspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && isspace(text[i])) i++; return i; } static size_t nextspace(const char *text, size_t start) { assert(text); size_t i = start; while (text[i] && !isspace(text[i])) i++; return i; } static bool try_parse_factor(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); char *endptr; ul_number f = _strton(str, &endptr); if (endptr && *endptr) { debug("'%s' is not a factor", str); return false; } unit->factor *= _pown(f, state->sign); return true; } static bool is_special(const char *str) { assert(str); if (strlen(str) == 1) { switch (str[0]) { case '*': // shall be ignored return true; case '/': // change sign return true; } } return false; } static bool handle_special(const char *str, struct parser_state *state) { assert(str); assert(state); switch (str[0]) { case '*': // ignore return true; case '/': state->sign *= -1; return true; } ERROR("Internal error: is_special/handle_special missmatch for '%s'.", str); return false; } static bool unit_and_prefix(const char *sym, unit_t **unit, ul_number *prefix) { rule_t *rule = get_rule(sym); if (rule) { *unit = &rule->unit; *prefix = 1.0; return true; } char p = sym[0]; debug("Got prefix: %c", p); prefix_t *pref = get_prefix(p); if (!pref) { ERROR("Unknown symbol: '%s'", sym); return false; } rule = get_rule(sym + 1); if (!rule) { ERROR("Unknown symbol: '%s' with prefix %c", sym + 1, p); return false; } *unit = &rule->unit; *prefix = pref->value; return true; } static bool parse_item(const char *str, unit_t *unit, struct parser_state *state) { assert(str); assert(unit); assert(state); debug("Parse item: '%s'", str); // Split symbol and exponent char symbol[MAX_SYM_SIZE]; int exp = 1; size_t symend = 0; while (str[symend] && str[symend] != '^') symend++; if (symend >= MAX_SYM_SIZE) { ERROR("Symbol to long"); return false; } strncpy(symbol, str, symend); symbol[symend] = '\0'; if (str[symend]) { // The '^' should not be the last value of the string if (!str[symend+1]) { ERROR("Missing exponent after '^' while parsing '%s'", str); return false; } // Parse the exponent char *endptr = NULL; exp = strtol(str+symend+1, &endptr, 10); // the whole exp string was valid only if *endptr is '\0' if (endptr && *endptr) { ERROR("Invalid exponent at char '%c' while parsing '%s'", *endptr, str); return false; } } debug("Exponent is %d", exp); exp *= state->sign; unit_t *rule; ul_number prefix; if (!unit_and_prefix(symbol, &rule, &prefix)) return false; // And add the definitions add_unit(unit, rule, exp); unit->factor *= _pown(prefix, exp); return true; } UL_API bool ul_parse(const char *str, unit_t *unit) { if (!str || !unit) { ERROR("Invalid paramters"); return false; } debug("Parse unit: '%s'", str); struct parser_state state; state.sign = 1; init_unit(unit); size_t len = strlen(str); size_t start = 0; do { char this_item[MAX_ITEM_SIZE ]; // Skip leading whitespaces start = skipspace(str, start); // And find the next whitespace size_t end = nextspace(str, start); if (end == start) {// End of string break; } // sanity check if ((end - start) > MAX_ITEM_SIZE ) { ERROR("Item too long"); return false; } // copy the item out of the string strncpy(this_item, str+start, end-start); this_item[end-start] = '\0'; // and parse it if (is_special(this_item)) { if (!handle_special(this_item, &state)) return false; } else if (try_parse_factor(this_item, unit, &state)) { // nothing todo } else { if (!parse_item(this_item, unit, &state)) return false; } start = end + 1; } while (start < len); return true; } static bool add_rule(const char *symbol, const unit_t *unit, bool force) { assert(symbol); assert(unit); rule_t *rule = malloc(sizeof(*rule)); if (!rule) { ERROR("Failed to allocate memory"); return false; } rule->next = NULL; rule->symbol = symbol; rule->force = force; copy_unit(unit, &rule->unit); rule_t *last = last_rule(); last->next = rule; return true; } static bool add_prefix(char sym, ul_number n) { prefix_t *pref = malloc(sizeof(*pref)); if (!pref) { ERROR("Failed to allocate %d bytes", sizeof(*pref)); return false; } pref->symbol = sym; pref->value = n; pref->next = NULL; prefix_t *last = last_prefix(); if (last) last->next = pref; else prefixes = pref; return true; } static bool rm_rule(rule_t *rule) { assert(rule); if (rule->force) { ERROR("Cannot remove forced rule"); return false; } rule_t *cur = dynamic_rules; // base rules cannot be removed rule_t *prev = &base_rules[NUM_BASE_UNITS-1]; while (cur && cur != rule) { prev = cur; cur = cur->next; } if (cur != rule) { ERROR("Rule not found."); return false; } prev->next = rule->next; return true; } static bool valid_symbol(const char *sym) { assert(sym); while (*sym) { if (!isalpha(*sym)) return false; sym++; } return true; } static char *get_symbol(const char *rule, size_t splitpos, bool *force) { assert(rule); assert(force); size_t skip = skipspace(rule, 0); size_t symend = nextspace(rule, skip); if (symend > splitpos) symend = splitpos; if (skipspace(rule,symend) != splitpos) { // rule was something like "a b = kg" ERROR("Invalid symbol, whitespaces are not allowed."); return NULL; } if ((symend-skip) > MAX_SYM_SIZE) { ERROR("Symbol to long"); return NULL; } if ((symend-skip) == 0) { ERROR("Empty symbols are not allowed."); return NULL; } if (rule[skip] == '!') { debug("Forced rule."); *force = true; skip++; } else { *force = false; } debug("Allocate %d bytes", symend-skip + 1); char *symbol = malloc(symend-skip + 1); if (!symbol) { ERROR("Failed to allocate memory"); return NULL; } strncpy(symbol, rule + skip, symend-skip); symbol[symend-skip] = '\0'; debug("Symbol is '%s'", symbol); return symbol; } // parses a string like "symbol = def" UL_API bool ul_parse_rule(const char *rule) { if (!rule) { ERROR("Invalid parameter"); return false; } // split symbol and definition size_t len = strlen(rule); size_t splitpos = 0; debug("Parsing rule '%s'", rule); for (size_t i=0; i < len; ++i) { if (rule[i] == '=') { debug("Split at %d", i); splitpos = i; break; } } if (!splitpos) { ERROR("Missing '=' in rule definition '%s'", rule); return false; } // Get the symbol bool force = false; char *symbol = get_symbol(rule, splitpos, &force); if (!symbol) return false; if (!valid_symbol(symbol)) { ERROR("Symbol '%s' is invalid.", symbol); free(symbol); return false; } rule_t *old_rule = NULL; if ((old_rule = get_rule(symbol)) != NULL) { if (old_rule->force || !force) { ERROR("You may not redefine '%s'", symbol); free(symbol); return false; } // remove the old rule, so it cannot be used in the definition // of the new one, so something like "!R = R" is not possible if (force) { if (!rm_rule(old_rule)) { free(symbol); return false; } } } rule = rule + splitpos + 1; // ommiting the '=' debug("Rest definition is '%s'", rule); unit_t unit; if (!ul_parse(rule, &unit)) { free(symbol); return false; } return add_rule(symbol, &unit, force); } UL_API bool ul_load_rules(const char *path) { FILE *f = fopen(path, "r"); if (!f) { ERROR("Failed to open file '%s'", path); return false; } bool ok = true; char line[1024]; while (fgets(line, 1024, f)) { size_t skip = skipspace(line, 0); if (!line[skip] || line[skip] == '#') continue; // empty line or comment ok = ul_parse_rule(line); if (!ok) break; } fclose(f); return ok; } static bool init_prefixes(void) { + debug("Initializing prefixes"); if (!add_prefix('Y', 1e24)) return false; if (!add_prefix('Z', 1e21)) return false; //zetta if (!add_prefix('E', 1e18)) return false; //exa if (!add_prefix('P', 1e15)) return false; //peta if (!add_prefix('T', 1e12)) return false; //tera if (!add_prefix('G', 1e9)) return false; // giga if (!add_prefix('M', 1e6)) return false; // mega if (!add_prefix('k', 1e3)) return false; // kilo if (!add_prefix('h', 1e2)) return false; // hecto // missing: da - deca if (!add_prefix('d', 1e-1)) return false; //deci if (!add_prefix('c', 1e-2)) return false; //centi if (!add_prefix('m', 1e-3)) return false; //milli if (!add_prefix('u', 1e-6)) return false; //micro if (!add_prefix('n', 1e-9)) return false; //nano if (!add_prefix('p', 1e-12)) return false; // pico if (!add_prefix('f', 1e-15)) return false; // femto if (!add_prefix('a', 1e-18)) return false; // atto if (!add_prefix('z', 1e-21)) return false; // zepto if (!add_prefix('y', 1e-24)) return false; // yocto + debug("Prefixes initialized!"); return true; } -UL_LINKAGE bool _ul_init_rules(void) +UL_LINKAGE bool _ul_init_parser(void) { + debug("Initializing parser"); for (int i=0; i < NUM_BASE_UNITS; ++i) { + debug("Base rule: %d", i); base_rules[i].symbol = _ul_symbols[i]; init_unit(&base_rules[i].unit); base_rules[i].force = true; base_rules[i].unit.exps[i] = 1; base_rules[i].next = &base_rules[i+1]; } dynamic_rules = NULL; rules = base_rules; + debug("Base rules initialized"); // stupid inconsistend SI system... unit_t gram = { {[U_KILOGRAM] = 1}, 1e-3, }; + debug("Adding gram"); if (!add_rule("g", &gram, true)) return false; if (!init_prefixes()) return false; + + debug("Parser initalized!"); return true; } UL_LINKAGE void _ul_free_rules(void) { debug("Freeing rule list"); rule_t *cur = dynamic_rules; while (cur) { rule_t *next = cur->next; free((char*)cur->symbol); free(cur); cur = next; } prefix_t *pref = prefixes; while (pref) { prefix_t *next = pref->next; free(pref); pref = next; } } diff --git a/unitlib.c b/unitlib.c index 0e8c530..40419a7 100644 --- a/unitlib.c +++ b/unitlib.c @@ -1,187 +1,192 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" #define static_assert(e) extern char (*STATIC_ASSERT(void))[sizeof(char[1 - 2*!(e)])] #define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) static FILE *dbg_out = NULL; bool _ul_debugging = false; UL_LINKAGE void _ul_debug(const char *fmt, ...) { assert(dbg_out); va_list ap; va_start(ap, fmt); vfprintf(dbg_out, fmt, ap); va_end(ap); } const char *_ul_symbols[] = { "m", "kg", "s", "A", "K", "mol", "Cd", "L", }; static_assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); // The last error message static char errmsg[1024]; UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) { snprintf(errmsg, 1024, "[%s:%d] ", func, line); size_t len = strlen(errmsg); va_list ap; va_start(ap, fmt); vsnprintf(errmsg + len, 1024 - len, fmt, ap); va_end(ap); } UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b) { if (!a || !b) { ERROR("Invalid parameters"); return UL_ERROR; } int res = UL_SAME_UNIT; for (int i=0; i < NUM_BASE_UNITS; ++i) { if (a->exps[i] != b->exps[i]) { res = 0; break; } } if (ncmp(a->factor, b->factor) == 0) { res |= UL_SAME_FACTOR; } return res; } UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with) { if (!unit || !with) { ERROR("Invalid parameter"); return false; } add_unit(unit, with, 1); return true; } UL_API bool ul_mult(unit_t *unit, ul_number factor) { if (!unit) { ERROR("Invalid parameter"); return false; } unit->factor *= factor; return true; } UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src) { if (!dst || !src) { ERROR("Invalid parameter"); return false; } copy_unit(src, dst); return true; } UL_API bool ul_inverse(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } if (ncmp(unit->factor, 0.0) == 0) { ERROR("Cannot inverse 0.0"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] = -unit->exps[i]; } unit->factor = 1/unit->factor; return true; } UL_API bool ul_sqrt(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { if ((unit->exps[i] % 2) != 0) { ERROR("Cannot take root of an odd exponent"); return false; } } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] /= 2; } unit->factor = _sqrtn(unit->factor); return false; } UL_API void ul_debugging(bool flag) { _ul_debugging = flag; } UL_API void ul_debugout(const char *path, bool append) { if (dbg_out && dbg_out != stderr) { debug("New debug file: %s", path ? path : "stderr"); fclose(dbg_out); } if (!path) { dbg_out = stderr; } else { dbg_out = fopen(path, append ? "a" : "w"); if (!dbg_out) { dbg_out = stderr; debug("Failed to open '%s' as debugout, using stderr.", path); } + setvbuf(dbg_out, NULL, _IONBF, 0); } + fprintf(dbg_out, "** unitlib - debug log **\n"); } UL_API const char *ul_error(void) { return errmsg; } UL_API const char *ul_get_name(void) { return UL_FULL_NAME; } UL_API const char *ul_get_version(void) { return UL_VERSION; } UL_API bool ul_init(void) { if(!dbg_out) dbg_out = stderr; - debug("Initializing base rules"); - if (!_ul_init_rules()) + debug("Initializing unitlib...."); + + if (!_ul_init_parser()) { return false; + } + debug("Init done!"); return true; } UL_API void ul_quit(void) { _ul_free_rules(); if (dbg_out && dbg_out != stderr) fclose(dbg_out); }
jan-kuechler/unitlib
7da0385399d420f447fc032a96c8dbc2a79382d8
Removed the loading of the env var UL_RULES as a rule file at ul_init().
diff --git a/unitlib.c b/unitlib.c index 2d64c50..c7c12eb 100644 --- a/unitlib.c +++ b/unitlib.c @@ -1,186 +1,177 @@ #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "intern.h" #include "unitlib.h" #define static_assert(e) extern char (*STATIC_ASSERT(void))[sizeof(char[1 - 2*!(e)])] #define sizeofarray(ar) (sizeof((ar))/sizeof((ar)[0])) static FILE *dbg_out = NULL; bool _ul_debugging = false; UL_LINKAGE void _ul_debug(const char *fmt, ...) { assert(dbg_out); va_list ap; va_start(ap, fmt); vfprintf(dbg_out, fmt, ap); va_end(ap); } const char *_ul_symbols[] = { "m", "kg", "s", "A", "K", "mol", "Cd", "L", }; static_assert(sizeofarray(_ul_symbols) == NUM_BASE_UNITS); // The last error message static char errmsg[1024]; UL_LINKAGE void _ul_set_error(const char *func, int line, const char *fmt, ...) { snprintf(errmsg, 1024, "[%s:%d] ", func, line); size_t len = strlen(errmsg); va_list ap; va_start(ap, fmt); vsnprintf(errmsg + len, 1024 - len, fmt, ap); va_end(ap); } UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b) { if (!a || !b) { ERROR("Invalid parameters"); return UL_ERROR; } int res = UL_SAME_UNIT; for (int i=0; i < NUM_BASE_UNITS; ++i) { if (a->exps[i] != b->exps[i]) { res = 0; break; } } if (ncmp(a->factor, b->factor) == 0) { res |= UL_SAME_FACTOR; } return res; } UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with) { if (!unit || !with) { ERROR("Invalid parameter"); return false; } add_unit(unit, with, 1); return true; } UL_API bool ul_mult(unit_t *unit, ul_number factor) { if (!unit) { ERROR("Invalid parameter"); return false; } unit->factor *= factor; return true; } UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src) { if (!dst || !src) { ERROR("Invalid parameter"); return false; } copy_unit(src, dst); return true; } UL_API bool ul_inverse(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } if (ncmp(unit->factor, 0.0) == 0) { ERROR("Cannot inverse 0.0"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] = -unit->exps[i]; } unit->factor = 1/unit->factor; return true; } UL_API bool ul_sqrt(unit_t *unit) { if (!unit) { ERROR("Invalid parameter"); return false; } for (int i=0; i < NUM_BASE_UNITS; ++i) { if ((unit->exps[i] % 2) != 0) { ERROR("Cannot take root of an odd exponent"); return false; } } for (int i=0; i < NUM_BASE_UNITS; ++i) { unit->exps[i] /= 2; } unit->factor = _sqrtn(unit->factor); return false; } UL_API void ul_debugging(bool flag) { _ul_debugging = flag; } UL_API void ul_debugout(const char *path, bool append) { if (dbg_out && dbg_out != stderr) { debug("New debug file: %s", path ? path : "stderr"); fclose(dbg_out); } if (!path) { dbg_out = stderr; } else { dbg_out = fopen(path, append ? "a" : "w"); if (!dbg_out) { dbg_out = stderr; debug("Failed to open '%s' as debugout, using stderr.", path); } } } UL_API const char *ul_error(void) { return errmsg; } UL_API bool ul_init(void) { if(!dbg_out) dbg_out = stderr; debug("Initializing base rules"); if (!_ul_init_rules()) return false; - const char *rulePath = getenv("UL_RULES"); - if (rulePath) { - debug("UL_RULES is set: %s", rulePath); - if (!ul_load_rules(rulePath)) { - ERROR("Failed to load rules: %s", errmsg); - return false; - } - } - return true; } UL_API void ul_quit(void) { _ul_free_rules(); if (dbg_out && dbg_out != stderr) fclose(dbg_out); }
jan-kuechler/unitlib
551de8169f23db28d18ea614ca0ccac0aa831fc1
Changed version to 0.4b1
diff --git a/unitlib.h b/unitlib.h index fef1c89..9fb2f75 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,238 +1,238 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" -#define UL_VERSION "0.4a1" +#define UL_VERSION "0.4b1" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; typedef enum ul_cmpres { UL_ERROR = 0xFF, UL_DIFFERENT = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, } ul_cmpres_t; typedef struct ul_format_ops { bool sort; int order[NUM_BASE_UNITS]; } ul_fmtops_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { return ul_fprint(stdout, unit, format, fmtp); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option * @return Length of the formated string */ UL_API size_t ul_length(const unit_t *unit, ul_format_t format); #endif /*UNITLIB_H*/
jan-kuechler/unitlib
74ec946bf0df62ec4efb7dcd735de0c1bffa6bae
Added UL_DIFFERENT return value to ul_cmp, that is distinct to UL_ERROR. Added some more tests.
diff --git a/unitlib.h b/unitlib.h index 5aff1f7..fef1c89 100644 --- a/unitlib.h +++ b/unitlib.h @@ -1,237 +1,238 @@ /** * unitlib.h - Main header for the unitlib */ #ifndef UNITLIB_H #define UNITLIB_H #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "unitlib-config.h" #define UL_NAME "unitlib" #define UL_VERSION "0.4a1" #define UL_FULL_NAME UL_NAME "-" UL_VERSION #ifdef __cplusplus #define UL_LINKAGE extern "C" #else #define UL_LINKAGE #endif #if defined(UL_EXPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllexport) #elif defined(UL_IMPORT_DLL) #define UL_API UL_LINKAGE __declspec(dllimport) #else #define UL_API UL_LINKAGE #endif typedef enum base_unit { U_METER, U_KILOGRAM, U_SECOND, U_AMPERE, U_KELVIN, U_MOL, U_CANDELA, U_LEMMING, /* Man kann alles in Lemminge umrechnen! */ NUM_BASE_UNITS, } base_unit_t; #define U_ANY -1 typedef enum ul_format { UL_FMT_PLAIN, UL_FMT_LATEX_FRAC, UL_FMT_LATEX_INLINE, } ul_format_t; typedef enum ul_cmpres { - UL_ERROR = 0x00, + UL_ERROR = 0xFF, + UL_DIFFERENT = 0x00, UL_SAME_UNIT = 0x01, UL_SAME_FACTOR = 0x02, UL_EQUAL = 0x03, } ul_cmpres_t; typedef struct ul_format_ops { bool sort; int order[NUM_BASE_UNITS]; } ul_fmtops_t; typedef struct unit { int exps[NUM_BASE_UNITS]; ul_number factor; } unit_t; /** * Initializes the unitlib. Has to be called before any * other ul_* function (excl. the ul_debug* functions). * @return success */ UL_API bool ul_init(void); /** * Deinitializes the unitlib and frees all. This function * has to be called at the end of the program. * internals resources. */ UL_API void ul_quit(void); /** * Enables or disables debugging messages * @param flag Enable = true */ UL_API void ul_debugging(bool flag); /** * Sets the debug output stream * @param out The outstream */ UL_API void ul_debugout(const char *path, bool append); /** * Returns the last error message * @return The last error message */ UL_API const char *ul_error(void); /** * Parses a rule and adds it to the rule list * @param rule The rule to parse * @return success */ UL_API bool ul_parse_rule(const char *rule); /** * Loads a rule file * @param path Path to the file * @return success */ UL_API bool ul_load_rules(const char *path); /** * Parses the unit definition from str to unit * @param str The unit definition * @param unit The parsed unit will be stored here * @return success */ UL_API bool ul_parse(const char *str, unit_t *unit); /** * Returns the factor of a unit * @param unit The unit * @return The factor */ static inline ul_number ul_factor(const unit_t *unit) { if (!unit) return 0.0; return unit->factor; } /** * Compares two units * @param a A unit * @param b Another unit * @return Compare result */ UL_API ul_cmpres_t ul_cmp(const unit_t *a, const unit_t *b); /** * Compares two units * @param a A unit * @param b Another unit * @return true if both units are equal */ static inline bool ul_equal(const unit_t *a, const unit_t *b) { return ul_cmp(a, b) == UL_EQUAL; } /** * Copies a unit into another * @param dst Destination unit * @param src Source unit * @return success */ UL_API bool ul_copy(unit_t *restrict dst, const unit_t *restrict src); /** * Multiplies a unit to a unit. * @param unit One factor and destination of the operation * @param with The other unit * @return success */ UL_API bool ul_combine(unit_t *restrict unit, const unit_t *restrict with); /** * Multiplies a unit with a factor * @param unit The unit * @param factor The factor * @return success */ UL_API bool ul_mult(unit_t *unit, ul_number factor); /** * Builds the inverse of a unit * @param unit The unit * @return success */ UL_API bool ul_inverse(unit_t *unit); /** * Takes the square root of the unit * @param unit The unit * @return success */ UL_API bool ul_sqrt(unit_t *unit); /** * Prints the unit to a file according to the format * @param file The file * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_fprint(FILE *f, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Prints the unit to stdout according to the format * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ static inline bool ul_print(const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp) { return ul_fprint(stdout, unit, format, fmtp); } /** * Prints the unit to a buffer according to the format * @param buffer The buffer * @param buflen Length of the buffer * @param unit The unit * @param format The format * @param fmtp Additional format parameters * @return success */ UL_API bool ul_snprint(char *buffer, size_t buflen, const unit_t *unit, ul_format_t format, ul_fmtops_t *fmtp); /** * Returns the length of the formated unit * @param unit The unit * @param format Format option * @return Length of the formated string */ UL_API size_t ul_length(const unit_t *unit, ul_format_t format); #endif /*UNITLIB_H*/ diff --git a/unittest.c b/unittest.c index 56e5863..616b03f 100644 --- a/unittest.c +++ b/unittest.c @@ -1,515 +1,560 @@ #ifndef GET_TEST_DEFS #include <stdarg.h> #include <stdlib.h> #include <string.h> #include "unitlib.h" #include "intern.h" // yay, self include (-: #define GET_TEST_DEFS #include "unittest.c" #undef GET_TEST_DEFS static unit_t make_unit(ul_number fac, ...) { va_list args; va_start(args, fac); unit_t u; memset(u.exps, 0, NUM_BASE_UNITS * sizeof(int)); u.factor = fac; int b = va_arg(args, int); int e = va_arg(args, int); while (b || e) { u.exps[b] = e; b = va_arg(args, int); e = va_arg(args, int); } return u; } #define MAKE_UNIT(...) make_unit(__VA_ARGS__,0,0,0) TEST_SUITE(parser) TEST unit_t u; CHECK(ul_parse("m", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_METER] == 1); int i=0; for (; i < NUM_BASE_UNITS; ++i) { if (i != U_METER) { CHECK(u.exps[i] == 0); } } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(" \n kg^2 * m ", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_KILOGRAM] == 2); CHECK(u.exps[U_METER] == 1); CHECK(u.exps[U_SECOND] == 0); CHECK(ncmp(u.factor, 1.0) == 0); CHECK(ul_parse("2 Cd 7 s^-1", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(u.exps[U_CANDELA] == 1); CHECK(u.exps[U_SECOND] == -1); CHECK(ncmp(u.factor, 14.0) == 0); CHECK(ul_parse("", &u)); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; const char *strings[] = { "5*kg^2", // need whitespace "5 ** kg^2", // double * "5! * kg^2", // ! "5 * kg^2!", // ! NULL }; int i = 0; while (strings[i]) { CHECK(ul_parse(strings[i], &u) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST const char *strings[] = { "", // empty rule " =", // empty symbol "16 = 16", // invalid rule " a b = s ", // invalid symbol " c == kg", // double = "d = e", // unknown 'e' " = kg", // empty symbol NULL, }; int i=0; while (strings[i]) { CHECK(ul_parse_rule(strings[i]) == false); PASS_MSG("Error message: %s", ul_error()); FAIL_MSG("'%s' is invalid but the parser reports no error.", strings[i]); i++; } END_TEST TEST // Empty rules are allowed CHECK(ul_parse_rule("EmptySymbol = ")); FAIL_MSG("Error: %s", ul_error()); unit_t u; CHECK(ul_parse("EmptySymbol", &u)); FAIL_MSG("Error: %s", ul_error()); int i=0; for (; i < NUM_BASE_UNITS; ++i) { CHECK(u.exps[i] == 0); } CHECK(ncmp(u.factor, 1.0) == 0); END_TEST TEST unit_t u; CHECK(ul_parse(NULL, NULL) == false); CHECK(ul_parse(NULL, &u) == false); CHECK(ul_parse("kg", NULL) == false); CHECK(ul_parse_rule(NULL) == false); CHECK(ul_parse_rule("") == false); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t s = MAKE_UNIT(1.0, U_SECOND, 1); unit_t u; CHECK(ul_parse_rule("!ForcedRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("ForcedRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("NewRule = kg")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&kg, &u)); CHECK(ul_parse_rule("!NewRule = s")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse("NewRule", &u)); CHECK(ul_equal(&s, &u)); CHECK(ul_parse_rule("!NewRule = m") == false); CHECK(ul_parse_rule("!kg = kg") == false); CHECK(ul_parse_rule(" Recurse = m")); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_parse_rule("!Recurse = Recurse") == false); END_TEST TEST static char prefs[] = "YZEPTGMkh dcmunpfazy"; static ul_number factors[] = { 1e24, 1e21, 1e18, 1e15, 1e12, 1e9, 1e6, 1e3, 1e2, 1, 1e-1, 1e-2, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18, 1e-21, 1e-24, }; size_t num_prefs = strlen(prefs); FATAL((sizeof(factors) / sizeof(factors[0])) != num_prefs); for (size_t i = 0; i < num_prefs; ++i) { char expr[128] = ""; snprintf(expr, 128, "5 %cm", prefs[i]); unit_t u; CHECK(ul_parse(expr, &u)); FAIL_MSG("Failed to parse: '%s' (%s)", expr, ul_error()); CHECK(ncmp(ul_factor(&u), 5 * factors[i]) == 0); FAIL_MSG("Factor: %g instead of %g (%c)", ul_factor(&u), 5 * factors[i], prefs[i]); // check kilogram, the only base unit with a prefix snprintf(expr, 128, "%cg", prefs[i]); CHECK(ul_parse(expr, &u)); } END_TEST + + TEST + unit_t correct = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -1); + + unit_t test; + CHECK(ul_parse("kg / s", &test)); + FAIL_MSG("Error: %s", ul_error()); + + CHECK(ul_equal(&test, &correct)); + + correct.factor = 2.0; + CHECK(ul_parse("8 kg / 4 s", &test)); + CHECK(ul_equal(&test, &correct)); + END_TEST END_TEST_SUITE() TEST_SUITE(core) TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t kg2 = MAKE_UNIT(1.0, U_KILOGRAM, 1); CHECK(ul_equal(&kg, &kg2)); kg2.factor = 2.0; CHECK(!ul_equal(&kg, &kg2)); kg2.factor = 1.0; CHECK(ul_equal(&kg, &kg2)); kg2.exps[U_KILOGRAM]++; CHECK(!ul_equal(&kg, &kg2)); unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); CHECK(!ul_equal(&kg, &N)); END_TEST + TEST + unit_t one_kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); + unit_t five_kg = MAKE_UNIT(5.0, U_KILOGRAM, 1); + + CHECK(!ul_equal(&one_kg, &five_kg)); + CHECK(ul_cmp(&one_kg, &five_kg) == UL_SAME_UNIT); + + unit_t five_sec = MAKE_UNIT(5.0, U_SECOND, 1); + CHECK(ul_cmp(&five_kg, &five_sec) == UL_SAME_FACTOR); + + CHECK(ul_cmp(&one_kg, &five_sec) == UL_DIFFERENT); + + CHECK(ul_cmp(NULL, &one_kg) == UL_ERROR); + CHECK(ul_cmp(&one_kg, NULL) == UL_ERROR); + CHECK(ul_cmp(NULL, NULL) == UL_ERROR); + + /* UL_EQUAL result is tested by the previous test */ + END_TEST + TEST unit_t a = MAKE_UNIT(1.0, U_KILOGRAM, 1); unit_t b; CHECK(ul_copy(&b, &a)); FAIL_MSG("Error: %s", ul_error()); CHECK(ul_equal(&b, &a)); CHECK(!ul_copy(NULL, NULL)); CHECK(!ul_copy(&a, NULL)); CHECK(!ul_copy(NULL, &a)); END_TEST TEST unit_t a = MAKE_UNIT(2.0, U_KILOGRAM, 1); unit_t b = MAKE_UNIT(3.0, U_SECOND, -2); unit_t res; CHECK(ul_copy(&res, &a)); FAIL_MSG("Preparation failed: %s", ul_error()); CHECK(ul_combine(&res, &b)); FAIL_MSG("Error: %s", ul_error()); unit_t correct = MAKE_UNIT(6.0, U_KILOGRAM, 1, U_SECOND, -2); CHECK(ul_equal(&res, &correct)); END_TEST + + TEST + unit_t test = MAKE_UNIT(1.0, U_KILOGRAM, 1); + + CHECK(ul_factor(&test) == 1.0); + CHECK(ul_mult(&test, 5.0)); + CHECK(ul_factor(&test) == 5.0); + CHECK(ul_mult(&test, 1/5.0)); + CHECK(ul_factor(&test) == 1.0); + CHECK(ul_mult(&test, -1)); + CHECK(ul_factor(&test) == -1.0); + END_TEST END_TEST_SUITE() TEST_SUITE(format) TEST extern void _ul_getnexp(ul_number n, ul_number *m, int *e); ul_number m; int e; _ul_getnexp(1.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1.0, &m, &e); CHECK(ncmp(m, -1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(11.0, &m, &e); CHECK(ncmp(m, 1.1) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e);; _ul_getnexp(9.81, &m, &e); CHECK(ncmp(m, 9.81) == 0); FAIL_MSG("m == %g", m); CHECK(e == 0); FAIL_MSG("e == %d", e); _ul_getnexp(-1234, &m, &e); CHECK(ncmp(m, -1.234) == 0); FAIL_MSG("m == %g", m); CHECK(e == 3); FAIL_MSG("e == %d", e); _ul_getnexp(10.0, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); _ul_getnexp(0.01, &m, &e); CHECK(ncmp(m, 1.0) == 0); FAIL_MSG("m == %g", m); CHECK(e == -2); FAIL_MSG("e == %d", e); _ul_getnexp(0.99, &m, &e); CHECK(ncmp(m, 9.9) == 0); FAIL_MSG("m == %g", m); CHECK(e == -1); FAIL_MSG("e == %d", e); _ul_getnexp(10.01, &m, &e); CHECK(ncmp(m, 1.001) == 0); FAIL_MSG("m == %g", m); CHECK(e == 1); FAIL_MSG("e == %d", e); END_TEST TEST unit_t kg = MAKE_UNIT(1.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); kg.factor = 1.5; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1.5 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); kg.factor = -1.0; CHECK(ul_snprint(buffer, 128, &kg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "-1 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&kg, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&kg, UL_FMT_PLAIN)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "1 m kg s^-2") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_PLAIN) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_PLAIN)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_INLINE, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "$1 \\text{ m} \\text{ kg} \\text{ s}^{-2}$") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_INLINE) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_INLINE)); END_TEST TEST unit_t N = MAKE_UNIT(1.0, U_KILOGRAM, 1, U_SECOND, -2, U_METER, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &N, UL_FMT_LATEX_FRAC, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "\\frac{1 \\text{ m} \\text{ kg}}{\\text{s}^{2}}") == 0); FAIL_MSG("buffer: '%s'", buffer); CHECK(ul_length(&N, UL_FMT_LATEX_FRAC) == strlen(buffer)); FAIL_MSG("ul_length: %u", ul_length(&N, UL_FMT_LATEX_FRAC)); END_TEST TEST unit_t zeroKg = MAKE_UNIT(0.0, U_KILOGRAM, 1); char buffer[128]; CHECK(ul_snprint(buffer, 128, &zeroKg, UL_FMT_PLAIN, NULL)); FAIL_MSG("Error: %s", ul_error()); CHECK(strcmp(buffer, "0 kg") == 0); FAIL_MSG("buffer: '%s'", buffer); END_TEST END_TEST_SUITE() int main(void) { ul_debugging(false); if (!ul_init()) { printf("ul_init failed: %s", ul_error()); return 1; } INIT_TEST(); SET_LOGLVL(L_NORMAL); RUN_SUITE(core); RUN_SUITE(parser); RUN_SUITE(format); ul_quit(); return TEST_RESULT; } #endif /*ndef GET_TEST_DEFS*/ //################################################################################################# #ifdef GET_TEST_DEFS #define PRINT(o, lvl, ...) do { if ((o)->loglvl >= lvl) printf(__VA_ARGS__); } while (0) #define FATAL(expr) \ do { \ if (expr) { \ PRINT(_o, L_RESULT, "[%s-%d] Fatal: %s\n", _name, _id, #expr); \ exit(1); \ } \ } while (0) #define CHECK(expr) \ do { \ int _this = ++_cid; \ if (!(expr)) { \ _err++; _fail++; \ PRINT(_o, L_NORMAL, "[%s-%d-%d] Fail: '%s'\n", _name, _id, _this, #expr); \ _last = false;\ } \ else { \ PRINT(_o, L_VERBOSE, "[%s-%d-%d] Pass: '%s'\n", _name, _id, _this, #expr); \ _last = true; \ } \ } while (0) #define FAIL_MSG(msg, ...) \ do {if (!_last) PRINT(_o,L_NORMAL,msg"\n", ##__VA_ARGS__); } while (0) #define PASS_MSG(msg, ...) \ do {if (_last) PRINT(_o,L_VERBOSE,msg"\n", ##__VA_ARGS__); } while (0) #define INFO(fmt, ...) \ do { printf("* " fmt "\n", ##__VA_ARGS__); } while (0) // TEST SUITE #define TEST_SUITE(name) \ int _test_##name(_tops *_o) { \ const char *_name = #name; \ int _fail = 0; \ int _test_id = 0; \ #define END_TEST_SUITE() \ return _fail; } // SINGLE TEST #define TEST \ { int _id = ++_test_id; int _err = 0; int _cid = 0; bool _last = true; \ #define END_TEST \ if (_err > 0) { \ PRINT(_o, L_NORMAL, "[%s-%d] failed with %d error%s.\n", _name, _id, _err, _err > 1 ? "s" : ""); \ } \ else { \ PRINT(_o, L_NORMAL, "[%s-%d] passed.\n", _name, _id); \ } \ } // OTHER typedef struct { int loglvl; } _tops; enum { L_QUIET = 0, L_RESULT = 1, L_NORMAL = 2, L_VERBOSE = 3, L_ALL = 4, }; static inline int _run_suite(int (*suite)(_tops*), const char *name, _tops *o) { int num_errs = suite(o); if (num_errs == 0) { PRINT(o, L_RESULT, "[%s] passed.\n", name); } else { PRINT(o, L_RESULT, "[%s] failed with %d error%s.\n", name, num_errs, num_errs > 1 ? "s" : ""); } return num_errs; } #define INIT_TEST() \ _tops _ops; int _tres = 0; #define SET_LOGLVL(lvl) \ _ops.loglvl = (lvl); #define RUN_SUITE(name) \ _tres += _run_suite(_test_##name, #name, &_ops) #define TEST_RESULT _tres #endif /* GET_TEST_DEFS*/
jan-kuechler/unitlib
4aed61b3b8e1d8a95309274629af8dda927977ed
Added install and unistall targets to the Makefile
diff --git a/Makefile b/Makefile index c5d1825..e144b96 100644 --- a/Makefile +++ b/Makefile @@ -1,89 +1,102 @@ ## # Makefile for unitlib ## -MSVC_COMPAT = -mno-cygwin -mms-bitfields +MSVC_COMPAT = -mms-bitfields CC = gcc CFLAGS = -O2 -std=c99 -Wall -Wextra $(MSVC_COMPAT) AR = ar RANLIB = ranlib TARGET = libunit.a DLL = libunit.dll IMPLIB = libunit.lib HEADER = unitlib-config.h unitlib.h SRCFILES = unitlib.c parser.c format.c HDRFILES = unitlib.h intern.h unitlib-config.h -DLL_INSTALL = /c/Windows -LIB_INSTALL = /g/Programmieren/lib -HDR_INSTALL = /g/Programmieren/include +WIN_DLL_INSTALL = /c/Windows +WIN_LIB_INSTALL = /g/Programmieren/lib +WIN_HDR_INSTALL = /g/Programmieren/include + +PREFIX = /usr +INSTALL_LIB = $(PREFIX)/lib +INSTALL_HDR = $(PREFIX)/include OBJFILES = unitlib.o parser.o format.o TESTPROG = _test.exe SMASHPROG = _smash.exe UNITTEST = ultest .PHONY: test clean allclean all: $(TARGET) dll: $(DLL) install-dll: dll - cp $(DLL) $(DLL_INSTALL) - cp $(IMPLIB) $(LIB_INSTALL) - cp $(HEADER) $(HDR_INSTALL) - + cp $(DLL) $(WIN_DLL_INSTALL) + cp $(IMPLIB) $(WIN_LIB_INSTALL) + cp $(HEADER) $(WIN_HDR_INSTALL) + +install: + cp $(TARGET) $(INSTALL_LIB) + cp $(HEADER) $(INSTALL_HDR) + +uninstall: + rm $(INSTALL_LIB)/$(TARGET) + cd $(INSTALL_HDR) + rm $(HEADER) + test: $(TESTPROG) @./$(TESTPROG) utest: $(UNITTEST) @./$(UNITTEST) smash: $(SMASHPROG) @./$(SMASHPROG) $(TARGET): $(OBJFILES) @$(AR) rc $(TARGET) $(OBJFILES) @$(RANLIB) $(TARGET) $(DLL): $(SRCFILES) $(HDRFILES) @$(CC) $(CFLAGS) -shared -o $(DLL) $(SRCFILES) -Wl,--out-implib,$(IMPLIB) unitlib.o: unitlib.c $(HDRFILES) @$(CC) $(CFLAGS) -o unitlib.o -c unitlib.c parser.o: parser.c $(HDRFILES) @$(CC) $(CFLAGS) -o parser.o -c parser.c format.o: format.c $(HDRFILES) @$(CC) $(CFLAGS) -o format.o -c format.c $(TESTPROG): $(TARGET) _test.c @$(CC) -o $(TESTPROG) -g -L. _test.c -lunit $(SMASHPROG): $(TARGET) _test.c @$(CC) -o $(SMASHPROG) -L. -DSMASH _test.c -lunit $(UNITTEST): $(TARGET) unittest.c @$(CC) -std=gnu99 -o $(UNITTEST) -L. unittest.c -lunit clean: @rm -f $(OBJFILES) @rm -f $(TESTPROG) @rm -f $(SMASHPROG) @rm -f $(UNITTEST) @rm -f debug.log allclean: clean @rm -f $(TARGET) @rm -f $(DLL) @rm -f $(IMPLIB)