Skip to content

Commit

Permalink
Merge pull request #6 from midnightrun/master
Browse files Browse the repository at this point in the history
Configuration via YAML
  • Loading branch information
narqo authored May 20, 2020
2 parents 42bec28 + efdacdf commit c7c4aca
Show file tree
Hide file tree
Showing 30 changed files with 10,136 additions and 66 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/dist
github-weather
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,15 @@ To update user's status on GitHub, the program uses [GitHub's GraphQL API](https
token with `user` scope.

## Usage

- Add your desired values for following parameters:
- Expiration Time of the new status in minutes (default 30 min, maximum 255 min)
- GitHub Token
- OpenWeather API Key
- Query location (default Berlin,De)
- Compile and run the application with following commands:
```
$ go build -o github-weather ./
$ github-weather -github.token <gh-api-token> -owm.api-key <open-weather-api-token> -owm.query <City>
$ go build -o github-weather .
$ ./github-weather
```

`github-weather -help` will print the list of all available options.
Expand Down
11 changes: 11 additions & 0 deletions config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
expirationTime: 30

github:
clientID: "github/weather"
endpoint: "https://api.github.com/graphql"
token: "$GITHUB_TOKEN"

owm:
api_key: "$OPENWEATHER_API_KEY"
endpoint: "https://api.openweathermap.org/data/2.5/weather?appid={api-key}&units=metric"
query: "Berlin,De"
33 changes: 12 additions & 21 deletions deployments/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,30 @@
You have to create two API tokens:

- Github API token with `user` scope.
- openWeather API token.
- OpenWeather API token.

Having these tokens, create a Kubernetes secret as follows:

```bash
$ kubectl create secret generic github-weather \
--from-literal=github_token=123_YOUR_GITHUB_TOKEN_HERE_321 \
--from-literal=openweather_api_token=123_YOUR_OPEN_WEATHER_TOKEN_HERE_321
secret/github-weather created
```

*Replace with the correct values*
Having these tokens, replace the values within the [`secret.yaml`](secret.yaml) accordingly.

## Customize your city

By default, this cronjob gathers `Madrid` weather information. If you want to use another different city, just change
it in the [`cronjob.yaml`](cronjob.yaml) file.
By default, this cronjob gathers `Berlin,De` weather information. If you want to use another different city, just change
it in the [`secret.yaml`](secret.yaml) file.

```yaml
containers:
- name: github-weather
image: docker.io/varankinv/github-weather:v1.0.0
command: ["/bin/sh", "-c"]
args: ["/bin/github-weather --debug --github.token $(GITHUB_TOKEN) --owm.api-key $(OPENWEATHER_API_TOKEN) --owm.query Madrid"]
expirationTime: 30
github:
...
...
owm:
query: "Cologne,De"
```
## Deploy it
Once the secret is placed in the cluster, deploy the cronjob:
Once the secret being placed in the cluster, deploy the resources:
```bash
$ kubectl apply -f cronjob.yaml
$ kubectl apply -f deployments/
```

It is executed every ten minutes. Wait for it or...
Expand Down Expand Up @@ -66,4 +58,3 @@ $ kubectl logs -f job/test
2020/04/23 12:28:34 << {"data":{"changeUserStatus":{"status":{"id":"1246618","updatedAt":"2020-04-23T12:28:34Z","expiresAt":"2020-04-23T12:58:34Z"}}}}
2020/04/23 12:28:34 set gh status: {ID:1246618 UpdatedAt:2020-04-23 12:28:34 +0000 UTC ExpiresAt:2020-04-23 12:58:34 +0000 UTC}
```
26 changes: 13 additions & 13 deletions deployments/cronjob.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,24 @@ spec:
containers:
- name: github-weather
image: docker.io/varankinv/github-weather:v1.0.0
command: ["/bin/sh", "-c"]
args: ["/bin/github-weather --debug --github.token $(GITHUB_TOKEN) --owm.api-key $(OPENWEATHER_API_TOKEN) --owm.query Madrid"]
command: ["/bin/github-weather"]
args:
- "--debug"
- "--configuration"
- "/secrets/config.yaml"
resources:
limits:
cpu: 100m
memory: 128Mi
requests:
cpu: 100m
memory: 128Mi
env:
- name: GITHUB_TOKEN
valueFrom:
secretKeyRef:
name: github-weather
key: github_token
- name: OPENWEATHER_API_TOKEN
valueFrom:
secretKeyRef:
name: github-weather
key: openweather_api_token
volumeMounts:
- name: config-secret-volume
mountPath: "/secrets/"
readOnly: true
restartPolicy: OnFailure
volumes:
- name: config-secret-volume
secret:
secretName: gh-config-secret
17 changes: 17 additions & 0 deletions deployments/secret.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
apiVersion: v1
kind: Secret
metadata:
name: gh-config-secret
stringData:
config.yaml: |-
expirationTime: 30
github:
clientID: "github/weather"
endpoint: "https://api.github.com/graphql"
token: "$GITHUB_TOKEN"
owm:
api_key: "$OPENWEATHER_API_KEY"
endpoint: "https://api.openweathermap.org/data/2.5/weather?appid={api-key}&units=metric"
query: "Berlin,De"
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ require (
github.com/machinebox/graphql v0.2.2
github.com/matryer/is v1.3.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
gopkg.in/yaml.v2 v2.3.0
)
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@ github.com/matryer/is v1.3.0 h1:9qiso3jaJrOe6qBRJRBt2Ldht05qDiFP9le0JOIhRSI=
github.com/matryer/is v1.3.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlWXA=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
68 changes: 44 additions & 24 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,24 @@ import (
"syscall"
"time"

"gopkg.in/yaml.v2"

"github.com/machinebox/graphql"
)

const (
owmAPIEndpoint = "https://api.openweathermap.org/data/2.5/weather?appid={api-key}&units=metric"
githubAPIEndpoint = "https://api.github.com/graphql"
githubClientID = "github/weather"
)
type Config struct {
ExpirationTime uint8 `yaml:"expirationTime"`
Github struct {
ClientID string `yaml:"clientID"`
Endpoint string `yaml:"endpoint"`
Token string `yaml:"token"`
} `yaml:"github"`
Owm struct {
ApiKey string `yaml:"api_key"`
Endpoint string `yaml:"endpoint"`
Query string `yaml:"query"`
} `yaml:"owm"`
}

func main() {
ctx, cancel := context.WithCancel(context.Background())
Expand All @@ -41,50 +51,60 @@ func main() {
}

func run(ctx context.Context, args []string) error {
flags := flag.NewFlagSet("", flag.ExitOnError)

var (
debug bool

owmAPIKey string
owmQuery string

githubAPIToken string
debug bool
configPath string
)
flags.BoolVar(&debug, "debug", false, "Enable debug logging")
flags.StringVar(&owmAPIKey, "owm.api-key", "", "OpenWeather API key")
flags.StringVar(&owmQuery, "owm.query", "Berlin,de", "OpenWeather API query, city name, state and country code divided by comma")

flags.StringVar(&githubAPIToken, "github.token", "", "GitHub API token")
flags := flag.NewFlagSet("", flag.ExitOnError)
flags.BoolVar(&debug, "debug", false, "Enable debug logging")
flags.StringVar(&configPath, "configuration", "config.yaml", "Path to configuration file")

if err := flags.Parse(args); err != nil {
return err
}

if owmAPIKey == "" || githubAPIToken == "" {
return fmt.Errorf("no API credentials passed: OpenWeather %q, GitHub %q", owmAPIKey, githubAPIToken)
f, err := os.Open(configPath)
if err != nil {
return fmt.Errorf("error opening configuration file: %v", err)
}
defer f.Close()

var cfg Config
dec := yaml.NewDecoder(f)
err = dec.Decode(&cfg)
if err != nil {
return fmt.Errorf("error parsing configuration file: %v", err)
}

if cfg.Owm.ApiKey == "" || cfg.Github.Token == "" {
return fmt.Errorf("no API credentials passed: OpenWeather %q, GitHub %q", cfg.Owm.ApiKey, cfg.Github.Token)
}

if cfg.ExpirationTime == 0 {
cfg.ExpirationTime = 30
}

owm := NewOWMClient(owmAPIEndpoint, owmAPIKey)
gh := NewGitHubClient(githubAPIEndpoint, githubAPIToken)
owm := NewOWMClient(cfg.Owm.Endpoint, cfg.Owm.ApiKey)
gh := NewGitHubClient(cfg.Github.Endpoint, cfg.Github.Token)
if debug {
gh.client.Log = func(s string) {
log.Println(s)
}
}

wr, err := owm.Weather(ctx, owmQuery)
wr, err := owm.Weather(ctx, cfg.Owm.Query)
if err != nil {
return err
}

log.Printf("got owm response: %+v\n", wr)

status := ChangeUserStatusInput{
ClientMutationID: githubClientID,
ClientMutationID: cfg.Github.ClientID,
Emoji: wr.Emoji(),
Message: wr.ShortString(),
ExpiresAt: time.Now().UTC().Add(30 * time.Minute), // XXX(narqo) status's expiration time is hardcoded
ExpiresAt: time.Now().UTC().Add(time.Duration(cfg.ExpirationTime) * time.Minute),
}
sr, err := gh.ChangeUserStatus(ctx, status)
if err != nil {
Expand Down
6 changes: 1 addition & 5 deletions misc/github-weather.crontab
Original file line number Diff line number Diff line change
@@ -1,5 +1 @@
GITHUB_TOKEN=
OWM_API_KEY=
OWM_QUERY="Berlin,de"

*/10 * * * * /home/pi/github-weather.linux-arm7 -github.token "$GITHUB_TOKEN" -owm.api-key "$OWM_API_KEY" -owm.query "$OWM_QUERY" 2>&1 >> /tmp/github-weather.log
*/10 * * * * /home/pi/github-weather.linux-arm7
16 changes: 16 additions & 0 deletions vendor/gopkg.in/yaml.v2/.travis.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit c7c4aca

Please sign in to comment.